diff --git a/.editorconfig b/.editorconfig index 426f9ad31..a17bbf975 100644 --- a/.editorconfig +++ b/.editorconfig @@ -3,21 +3,28 @@ root = true [*.rs] charset=utf-8 end_of_line=lf -indent_size=space +indent_size=4 indent_style=space insert_final_newline=true max_line_length=100 -tab_width=4 +trim_trailing_whitespace=true + +[*.toml] +end_of_line=lf +indent_size=2 +indent_style=space +trim_trailing_whitespace=true + +[*.md] +insert_final_newline=true trim_trailing_whitespace=true [*.yml] end_of_line=lf indent_size=2 indent_style=space -tab_width=8 [*.sh] end_of_line=lf indent_size=2 indent_style=space -tab_width=8 diff --git a/.github/resources/frame-weight-template.hbs b/.github/resources/frame-weight-template.hbs index 225191459..621c2c491 100644 --- a/.github/resources/frame-weight-template.hbs +++ b/.github/resources/frame-weight-template.hbs @@ -1,16 +1,16 @@ // Copyright 2020-2022 Manta Network. // This file is part of Manta. - +// // Manta 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. - +// // Manta 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 Manta. If not, see . @@ -34,76 +34,76 @@ use sp_std::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}} + {{#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); impl {{pallet}}::WeightInfo for SubstrateWeight { - {{#each benchmarks as |benchmark|}} - {{#each benchmark.comments as |comment|}} - // {{comment}} - {{/each}} - fn {{benchmark.name~}} - ( - {{~#each benchmark.components as |c| ~}} - {{~#if (not c.is_used)}}_{{/if}}{{c.name}}: u32, {{/each~}} - ) -> Weight { - ({{underscore benchmark.base_weight}} as Weight) - {{#each benchmark.component_weight as |cw|}} - // Standard Error: {{underscore cw.error}} - .saturating_add(({{underscore cw.slope}} as Weight).saturating_mul({{cw.name}} as Weight)) - {{/each}} - {{#if (ne benchmark.base_reads "0")}} - .saturating_add(T::DbWeight::get().reads({{benchmark.base_reads}} as Weight)) - {{/if}} - {{#each benchmark.component_reads as |cr|}} - .saturating_add(T::DbWeight::get().reads(({{cr.slope}} as Weight).saturating_mul({{cr.name}} as Weight))) - {{/each}} - {{#if (ne benchmark.base_writes "0")}} - .saturating_add(T::DbWeight::get().writes({{benchmark.base_writes}} as Weight)) - {{/if}} - {{#each benchmark.component_writes as |cw|}} - .saturating_add(T::DbWeight::get().writes(({{cw.slope}} as Weight).saturating_mul({{cw.name}} as Weight))) - {{/each}} - } - {{/each}} + {{#each benchmarks as |benchmark|}} + {{#each benchmark.comments as |comment|}} + // {{comment}} + {{/each}} + fn {{benchmark.name~}} + ( + {{~#each benchmark.components as |c| ~}} + {{~#if (not c.is_used)}}_{{/if}}{{c.name}}: u32, {{/each~}} + ) -> Weight { + ({{underscore benchmark.base_weight}} as Weight) + {{#each benchmark.component_weight as |cw|}} + // Standard Error: {{underscore cw.error}} + .saturating_add(({{underscore cw.slope}} as Weight).saturating_mul({{cw.name}} as Weight)) + {{/each}} + {{#if (ne benchmark.base_reads "0")}} + .saturating_add(T::DbWeight::get().reads({{benchmark.base_reads}} as Weight)) + {{/if}} + {{#each benchmark.component_reads as |cr|}} + .saturating_add(T::DbWeight::get().reads(({{cr.slope}} as Weight).saturating_mul({{cr.name}} as Weight))) + {{/each}} + {{#if (ne benchmark.base_writes "0")}} + .saturating_add(T::DbWeight::get().writes({{benchmark.base_writes}} as Weight)) + {{/if}} + {{#each benchmark.component_writes as |cw|}} + .saturating_add(T::DbWeight::get().writes(({{cw.slope}} as Weight).saturating_mul({{cw.name}} as Weight))) + {{/each}} + } + {{/each}} } // For backwards compatibility and tests impl WeightInfo for () { - {{#each benchmarks as |benchmark|}} - {{#each benchmark.comments as |comment|}} - // {{comment}} - {{/each}} - fn {{benchmark.name~}} - ( - {{~#each benchmark.components as |c| ~}} - {{~#if (not c.is_used)}}_{{/if}}{{c.name}}: u32, {{/each~}} - ) -> Weight { - ({{underscore benchmark.base_weight}} as Weight) - {{#each benchmark.component_weight as |cw|}} - // Standard Error: {{underscore cw.error}} - .saturating_add(({{underscore cw.slope}} as Weight).saturating_mul({{cw.name}} as Weight)) - {{/each}} - {{#if (ne benchmark.base_reads "0")}} - .saturating_add(RocksDbWeight::get().reads({{benchmark.base_reads}} as Weight)) - {{/if}} - {{#each benchmark.component_reads as |cr|}} - .saturating_add(RocksDbWeight::get().reads(({{cr.slope}} as Weight).saturating_mul({{cr.name}} as Weight))) - {{/each}} - {{#if (ne benchmark.base_writes "0")}} - .saturating_add(RocksDbWeight::get().writes({{benchmark.base_writes}} as Weight)) - {{/if}} - {{#each benchmark.component_writes as |cw|}} - .saturating_add(RocksDbWeight::get().writes(({{cw.slope}} as Weight).saturating_mul({{cw.name}} as Weight))) - {{/each}} - } - {{/each}} + {{#each benchmarks as |benchmark|}} + {{#each benchmark.comments as |comment|}} + // {{comment}} + {{/each}} + fn {{benchmark.name~}} + ( + {{~#each benchmark.components as |c| ~}} + {{~#if (not c.is_used)}}_{{/if}}{{c.name}}: u32, {{/each~}} + ) -> Weight { + ({{underscore benchmark.base_weight}} as Weight) + {{#each benchmark.component_weight as |cw|}} + // Standard Error: {{underscore cw.error}} + .saturating_add(({{underscore cw.slope}} as Weight).saturating_mul({{cw.name}} as Weight)) + {{/each}} + {{#if (ne benchmark.base_reads "0")}} + .saturating_add(RocksDbWeight::get().reads({{benchmark.base_reads}} as Weight)) + {{/if}} + {{#each benchmark.component_reads as |cr|}} + .saturating_add(RocksDbWeight::get().reads(({{cr.slope}} as Weight).saturating_mul({{cr.name}} as Weight))) + {{/each}} + {{#if (ne benchmark.base_writes "0")}} + .saturating_add(RocksDbWeight::get().writes({{benchmark.base_writes}} as Weight)) + {{/if}} + {{#each benchmark.component_writes as |cw|}} + .saturating_add(RocksDbWeight::get().writes(({{cw.slope}} as Weight).saturating_mul({{cw.name}} as Weight))) + {{/each}} + } + {{/each}} } diff --git a/.github/workflows/check_build.yml b/.github/workflows/check_build.yml index e38e54069..d08fd078d 100644 --- a/.github/workflows/check_build.yml +++ b/.github/workflows/check_build.yml @@ -83,16 +83,16 @@ jobs: run: | curl -s https://sh.rustup.rs -sSf | sh -s -- -y source ${HOME}/.cargo/env - rustup toolchain install stable rustup toolchain install nightly - rustup default stable rustup target add wasm32-unknown-unknown --toolchain nightly + rustup default nightly rustup update + cargo install taplo-cli - name: Run yamllint uses: actionshub/yamllint@main - - name: Check Clippy & Formatting + name: Check Formatting env: RUST_BACKTRACE: full RUSTC_WRAPPER: sccache @@ -100,8 +100,9 @@ jobs: SCCACHE_DIR: /home/runner/.cache/sccache run: | source ${HOME}/.cargo/env - SKIP_WASM_BUILD=1 cargo clippy - SKIP_WASM_BUILD=1 cargo fmt + cargo fmt --all -- --check + $HOME/.cargo/bin/taplo fmt --check + $HOME/.cargo/bin/taplo lint - name: Check Build env: @@ -111,8 +112,8 @@ jobs: SCCACHE_DIR: /home/runner/.cache/sccache run: | source ${HOME}/.cargo/env - cargo check --no-default-features - cargo check --all-features + SKIP_WASM_BUILD=1 cargo check --no-default-features + SKIP_WASM_BUILD=1 cargo clippy --all-targets --all-features -- -D warnings - name: stop sccache server run: sccache --stop-server || true diff --git a/.rustfmt.toml b/.rustfmt.toml index e36335f0e..9437df19b 100644 --- a/.rustfmt.toml +++ b/.rustfmt.toml @@ -1,2 +1,3 @@ -hard_tabs=true -imports_granularity="Crate" \ No newline at end of file +edition = '2021' # Needed for direct invocation of rustfmt ourside of cargo fmt +imports_granularity = "Crate" +license_template_path = "FILE_TEMPLATE" diff --git a/.taplo.toml b/.taplo.toml new file mode 100644 index 000000000..5f3f5e1a0 --- /dev/null +++ b/.taplo.toml @@ -0,0 +1,4 @@ +[formatting] +array_auto_collapse = false +array_auto_expand = false +reorder_keys = true diff --git a/Cargo.toml b/Cargo.toml index 41e0d28fe..909e8c318 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,18 +1,18 @@ [workspace] -resolver = "2" members = [ - 'node', - 'pallets/*', - 'runtime/manta', - 'runtime/calamari', - 'runtime/dolphin', - 'runtime/common', - 'primitives', + 'node', + 'pallets/*', + 'runtime/manta', + 'runtime/calamari', + 'runtime/dolphin', + 'runtime/common', + 'primitives', ] +resolver = "2" [profile.production] -inherits = "release" codegen-units = 1 +inherits = "release" lto = true [profile.release] diff --git a/file_header.txt b/FILE_TEMPLATE similarity index 100% rename from file_header.txt rename to FILE_TEMPLATE diff --git a/node/Cargo.toml b/node/Cargo.toml index dfbc753d0..b44813736 100644 --- a/node/Cargo.toml +++ b/node/Cargo.toml @@ -1,28 +1,28 @@ [package] authors = ['Manta Network'] build = 'build.rs' +default-run = "manta" description = 'Manta Parachain Node.' edition = '2021' -rust-version = '1.57' homepage = 'https://manta.network' license = 'GPL-3.0' name = 'manta' repository = 'https://github.com/Manta-Network/Manta/' +rust-version = '1.57' version = '3.2.0' -default-run = "manta" [package.metadata.docs.rs] targets = ['x86_64-unknown-linux-gnu'] [dependencies] +async-trait = "0.1.52" +cfg-if = "1.0.0" clap = { version = "3.1", features = ["derive"] } -log = "0.4.16" codec = { package = 'parity-scale-codec', version = '3.0.0' } -cfg-if = "1.0.0" -serde = { version = "1.0.137", features = ["derive"] } -hex-literal = "0.3.4" -async-trait = "0.1.52" futures = "0.3.21" +hex-literal = "0.3.4" +log = "0.4.16" +serde = { version = "1.0.137", features = ["derive"] } # Substrate frames frame-benchmarking = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } @@ -30,8 +30,8 @@ frame-benchmarking-cli = { git = 'https://github.com/paritytech/substrate.git', try-runtime-cli = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18", optional = true } # RPC related dependencies -jsonrpc-core = "18.0.0" frame-rpc-system = { package = "substrate-frame-rpc-system", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18" } +jsonrpc-core = "18.0.0" pallet-transaction-payment-rpc = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sc-transaction-pool-api = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18" } @@ -39,29 +39,29 @@ sc-transaction-pool-api = { git = "https://github.com/paritytech/substrate.git", sc-basic-authorship = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sc-chain-spec = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sc-cli = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } +sc-client-api = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sc-consensus = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sc-executor = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } -sc-client-api = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sc-keystore = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sc-network = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18" } sc-rpc = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sc-rpc-api = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sc-service = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sc-telemetry = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } -sc-transaction-pool = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sc-tracing = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } +sc-transaction-pool = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } # Substrate primitives sp-api = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sp-block-builder = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } +sp-blockchain = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sp-consensus = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sp-consensus-aura = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } -sp-blockchain = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sp-core = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sp-inherents = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } +sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18" } sp-keystore = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18" } sp-offchain = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } -sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18" } sp-runtime = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sp-session = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sp-timestamp = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } @@ -70,16 +70,16 @@ substrate-prometheus-endpoint = { git = "https://github.com/paritytech/substrate # Cumulus dependencies cumulus-client-cli = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } -cumulus-client-consensus-common = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } cumulus-client-consensus-aura = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } +cumulus-client-consensus-common = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } cumulus-client-consensus-relay-chain = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } cumulus-client-network = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } +cumulus-client-service = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } cumulus-primitives-core = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } cumulus-primitives-parachain-inherent = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } -cumulus-client-service = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } +cumulus-relay-chain-inprocess-interface = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } cumulus-relay-chain-interface = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } cumulus-relay-chain-rpc-interface = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } -cumulus-relay-chain-inprocess-interface = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } # Polkadot dependencies polkadot-cli = { git = 'https://github.com/paritytech/polkadot.git', branch = "release-v0.9.18" } @@ -99,17 +99,17 @@ pallet-manta-pay = { path = '../pallets/manta-pay', features = ["rpc", "runtime" substrate-build-script-utils = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } [features] +fast-runtime = [ + "manta-runtime/fast-runtime", + "calamari-runtime/fast-runtime", +] runtime-benchmarks = [ - 'calamari-runtime/runtime-benchmarks', - 'polkadot-service/runtime-benchmarks', - 'manta-runtime/runtime-benchmarks', + 'calamari-runtime/runtime-benchmarks', + 'polkadot-service/runtime-benchmarks', + 'manta-runtime/runtime-benchmarks', ] try-runtime = [ - 'calamari-runtime/try-runtime', - 'manta-runtime/try-runtime', - 'try-runtime-cli', -] -fast-runtime = [ - "manta-runtime/fast-runtime", - "calamari-runtime/fast-runtime", + 'calamari-runtime/try-runtime', + 'manta-runtime/try-runtime', + 'try-runtime-cli', ] diff --git a/node/build.rs b/node/build.rs index 33194c881..19c83f571 100644 --- a/node/build.rs +++ b/node/build.rs @@ -17,7 +17,7 @@ use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed}; fn main() { - generate_cargo_keys(); + generate_cargo_keys(); - rerun_if_git_head_changed(); + rerun_if_git_head_changed(); } diff --git a/node/src/chain_specs/calamari.rs b/node/src/chain_specs/calamari.rs index de414f7e4..597ea4891 100644 --- a/node/src/chain_specs/calamari.rs +++ b/node/src/chain_specs/calamari.rs @@ -21,7 +21,7 @@ use manta_primitives::helpers::{get_account_id_from_seed, get_collator_keys_from /// Specialized `ChainSpec` for the normal parachain runtime. pub type CalamariChainSpec = - sc_service::GenericChainSpec; + sc_service::GenericChainSpec; const CALAMARI_PROTOCOL_ID: &str = "calamari"; // for p2p network configuration const KUSAMA_RELAYCHAIN_LOCAL_NET: &str = "kusama-local"; @@ -34,200 +34,200 @@ const SAFE_XCM_VERSION: u32 = 2; /// /// The input must be a tuple of individual keys (a single arg for now since we have just one key). pub fn calamari_session_keys(keys: AuraId) -> calamari_runtime::opaque::SessionKeys { - calamari_runtime::opaque::SessionKeys { aura: keys } + calamari_runtime::opaque::SessionKeys { aura: keys } } // calamari chain specs pub fn calamari_properties() -> Properties { - let mut p = Properties::new(); - p.insert("ss58format".into(), constants::CALAMARI_SS58PREFIX.into()); - p.insert("tokenDecimals".into(), constants::CALAMARI_DECIMAL.into()); - p.insert( - "tokenSymbol".into(), - constants::CALAMARI_TOKEN_SYMBOL.into(), - ); - p + let mut p = Properties::new(); + p.insert("ss58format".into(), constants::CALAMARI_SS58PREFIX.into()); + p.insert("tokenDecimals".into(), constants::CALAMARI_DECIMAL.into()); + p.insert( + "tokenSymbol".into(), + constants::CALAMARI_TOKEN_SYMBOL.into(), + ); + p } pub fn calamari_development_config() -> CalamariChainSpec { - let properties = calamari_properties(); + let properties = calamari_properties(); - CalamariChainSpec::from_genesis( - // Name - "Calamari Parachain Development", - // ID - "calamari_dev", - ChainType::Local, - move || { - calamari_dev_genesis( - // initial collators. - vec![( - get_account_id_from_seed::("Alice"), - get_collator_keys_from_seed("Alice"), - )], - vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - get_account_id_from_seed::("Alice//stash"), - get_account_id_from_seed::("Bob//stash"), - ], - ) - }, - vec![], - None, - Some(CALAMARI_PROTOCOL_ID), - None, - Some(properties), - Extensions { - relay_chain: KUSAMA_RELAYCHAIN_DEV_NET.into(), - para_id: CALAMARI_PARACHAIN_ID, - }, - ) + CalamariChainSpec::from_genesis( + // Name + "Calamari Parachain Development", + // ID + "calamari_dev", + ChainType::Local, + move || { + calamari_dev_genesis( + // initial collators. + vec![( + get_account_id_from_seed::("Alice"), + get_collator_keys_from_seed("Alice"), + )], + vec![ + get_account_id_from_seed::("Alice"), + get_account_id_from_seed::("Bob"), + get_account_id_from_seed::("Alice//stash"), + get_account_id_from_seed::("Bob//stash"), + ], + ) + }, + vec![], + None, + Some(CALAMARI_PROTOCOL_ID), + None, + Some(properties), + Extensions { + relay_chain: KUSAMA_RELAYCHAIN_DEV_NET.into(), + para_id: CALAMARI_PARACHAIN_ID, + }, + ) } pub fn calamari_local_config() -> CalamariChainSpec { - let properties = calamari_properties(); + let properties = calamari_properties(); - CalamariChainSpec::from_genesis( - // Name - "Calamari Parachain Local", - // ID - "calamari_local", - ChainType::Local, - move || { - calamari_dev_genesis( - // initial collators. - vec![ - ( - get_account_id_from_seed::("Alice"), - get_collator_keys_from_seed("Alice"), - ), - ( - get_account_id_from_seed::("Bob"), - get_collator_keys_from_seed("Bob"), - ), - ( - get_account_id_from_seed::("Charlie"), - get_collator_keys_from_seed("Charlie"), - ), - ( - get_account_id_from_seed::("Dave"), - get_collator_keys_from_seed("Dave"), - ), - ( - get_account_id_from_seed::("Eve"), - get_collator_keys_from_seed("Eve"), - ), - ], - vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - get_account_id_from_seed::("Charlie"), - get_account_id_from_seed::("Dave"), - get_account_id_from_seed::("Eve"), - get_account_id_from_seed::("Alice//stash"), - get_account_id_from_seed::("Bob//stash"), - get_account_id_from_seed::("Charlie//stash"), - get_account_id_from_seed::("Dave//stash"), - get_account_id_from_seed::("Eve//stash"), - ], - ) - }, - vec![], - None, - Some(CALAMARI_PROTOCOL_ID), - None, - Some(properties), - Extensions { - relay_chain: KUSAMA_RELAYCHAIN_LOCAL_NET.into(), - para_id: CALAMARI_PARACHAIN_ID, - }, - ) + CalamariChainSpec::from_genesis( + // Name + "Calamari Parachain Local", + // ID + "calamari_local", + ChainType::Local, + move || { + calamari_dev_genesis( + // initial collators. + vec![ + ( + get_account_id_from_seed::("Alice"), + get_collator_keys_from_seed("Alice"), + ), + ( + get_account_id_from_seed::("Bob"), + get_collator_keys_from_seed("Bob"), + ), + ( + get_account_id_from_seed::("Charlie"), + get_collator_keys_from_seed("Charlie"), + ), + ( + get_account_id_from_seed::("Dave"), + get_collator_keys_from_seed("Dave"), + ), + ( + get_account_id_from_seed::("Eve"), + get_collator_keys_from_seed("Eve"), + ), + ], + vec![ + get_account_id_from_seed::("Alice"), + get_account_id_from_seed::("Bob"), + get_account_id_from_seed::("Charlie"), + get_account_id_from_seed::("Dave"), + get_account_id_from_seed::("Eve"), + get_account_id_from_seed::("Alice//stash"), + get_account_id_from_seed::("Bob//stash"), + get_account_id_from_seed::("Charlie//stash"), + get_account_id_from_seed::("Dave//stash"), + get_account_id_from_seed::("Eve//stash"), + ], + ) + }, + vec![], + None, + Some(CALAMARI_PROTOCOL_ID), + None, + Some(properties), + Extensions { + relay_chain: KUSAMA_RELAYCHAIN_LOCAL_NET.into(), + para_id: CALAMARI_PARACHAIN_ID, + }, + ) } fn calamari_dev_genesis( - invulnerables: Vec<(AccountId, AuraId)>, - endowed_accounts: Vec, + invulnerables: Vec<(AccountId, AuraId)>, + endowed_accounts: Vec, ) -> calamari_runtime::GenesisConfig { - calamari_runtime::GenesisConfig { - system: calamari_runtime::SystemConfig { - code: calamari_runtime::WASM_BINARY - .expect("WASM binary was not build, please build it!") - .to_vec(), - }, - balances: calamari_runtime::BalancesConfig { - balances: endowed_accounts[..endowed_accounts.len() / 2] - .iter() - .map(|k| { - ( - k.clone(), - 100 * CALAMARI_ENDOWMENT / ((endowed_accounts.len() / 2) as Balance), - ) - }) - .collect(), - }, - // no need to pass anything to aura, in fact it will panic if we do. Session will take care - // of this. - aura: Default::default(), - parachain_info: calamari_runtime::ParachainInfoConfig { - parachain_id: CALAMARI_PARACHAIN_ID.into(), - }, - collator_selection: calamari_runtime::CollatorSelectionConfig { - invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(), - candidacy_bond: KMA * 1000, // How many tokens will be reserved as collator - ..Default::default() - }, - session: calamari_runtime::SessionConfig { - keys: invulnerables - .iter() - .cloned() - .map(|(acc, aura)| { - ( - acc.clone(), // account id - acc, // validator id - calamari_session_keys(aura), // session keys - ) - }) - .collect(), - }, - democracy: DemocracyConfig::default(), - council: CouncilConfig { - members: endowed_accounts.iter().take(1).cloned().collect(), - phantom: Default::default(), - }, - technical_committee: TechnicalCommitteeConfig { - members: endowed_accounts.iter().take(1).cloned().collect(), - phantom: Default::default(), - }, - council_membership: Default::default(), - technical_membership: Default::default(), - asset_manager: Default::default(), - aura_ext: Default::default(), - parachain_system: Default::default(), - polkadot_xcm: calamari_runtime::PolkadotXcmConfig { - safe_xcm_version: Some(SAFE_XCM_VERSION), - }, - } + calamari_runtime::GenesisConfig { + system: calamari_runtime::SystemConfig { + code: calamari_runtime::WASM_BINARY + .expect("WASM binary was not build, please build it!") + .to_vec(), + }, + balances: calamari_runtime::BalancesConfig { + balances: endowed_accounts[..endowed_accounts.len() / 2] + .iter() + .map(|k| { + ( + k.clone(), + 100 * CALAMARI_ENDOWMENT / ((endowed_accounts.len() / 2) as Balance), + ) + }) + .collect(), + }, + // no need to pass anything to aura, in fact it will panic if we do. Session will take care + // of this. + aura: Default::default(), + parachain_info: calamari_runtime::ParachainInfoConfig { + parachain_id: CALAMARI_PARACHAIN_ID.into(), + }, + collator_selection: calamari_runtime::CollatorSelectionConfig { + invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(), + candidacy_bond: KMA * 1000, // How many tokens will be reserved as collator + ..Default::default() + }, + session: calamari_runtime::SessionConfig { + keys: invulnerables + .iter() + .cloned() + .map(|(acc, aura)| { + ( + acc.clone(), // account id + acc, // validator id + calamari_session_keys(aura), // session keys + ) + }) + .collect(), + }, + democracy: DemocracyConfig::default(), + council: CouncilConfig { + members: endowed_accounts.iter().take(1).cloned().collect(), + phantom: Default::default(), + }, + technical_committee: TechnicalCommitteeConfig { + members: endowed_accounts.iter().take(1).cloned().collect(), + phantom: Default::default(), + }, + council_membership: Default::default(), + technical_membership: Default::default(), + asset_manager: Default::default(), + aura_ext: Default::default(), + parachain_system: Default::default(), + polkadot_xcm: calamari_runtime::PolkadotXcmConfig { + safe_xcm_version: Some(SAFE_XCM_VERSION), + }, + } } pub fn calamari_testnet_config() -> Result { - let mut spec = CalamariChainSpec::from_json_bytes( - &include_bytes!("../../../genesis/calamari-testnet-genesis.json")[..], - )?; - spec.extensions_mut().para_id = CALAMARI_PARACHAIN_ID; - Ok(spec) + let mut spec = CalamariChainSpec::from_json_bytes( + &include_bytes!("../../../genesis/calamari-testnet-genesis.json")[..], + )?; + spec.extensions_mut().para_id = CALAMARI_PARACHAIN_ID; + Ok(spec) } // Calamari testnet for ci jobs pub fn calamari_testnet_ci_config() -> Result { - CalamariChainSpec::from_json_bytes( - &include_bytes!("../../../genesis/calamari-testnet-ci-genesis.json")[..], - ) + CalamariChainSpec::from_json_bytes( + &include_bytes!("../../../genesis/calamari-testnet-ci-genesis.json")[..], + ) } // Calamari mainnet pub fn calamari_config() -> Result { - CalamariChainSpec::from_json_bytes( - &include_bytes!("../../../genesis/calamari-genesis.json")[..], - ) + CalamariChainSpec::from_json_bytes( + &include_bytes!("../../../genesis/calamari-genesis.json")[..], + ) } diff --git a/node/src/chain_specs/dolphin.rs b/node/src/chain_specs/dolphin.rs index 7b13b3279..c3f612631 100644 --- a/node/src/chain_specs/dolphin.rs +++ b/node/src/chain_specs/dolphin.rs @@ -33,189 +33,189 @@ const SAFE_XCM_VERSION: u32 = 2; /// /// The input must be a tuple of individual keys (a single arg for now since we have just one key). pub fn dolphin_session_keys(keys: AuraId) -> dolphin_runtime::opaque::SessionKeys { - dolphin_runtime::opaque::SessionKeys { aura: keys } + dolphin_runtime::opaque::SessionKeys { aura: keys } } // dolphin chain specs pub fn dolphin_properties() -> Properties { - let mut p = Properties::new(); - p.insert("ss58format".into(), constants::CALAMARI_SS58PREFIX.into()); - p.insert("tokenDecimals".into(), constants::DOLPHIN_DECIMAL.into()); - p.insert("tokenSymbol".into(), constants::DOLPHIN_TOKEN_SYMBOL.into()); - p + let mut p = Properties::new(); + p.insert("ss58format".into(), constants::CALAMARI_SS58PREFIX.into()); + p.insert("tokenDecimals".into(), constants::DOLPHIN_DECIMAL.into()); + p.insert("tokenSymbol".into(), constants::DOLPHIN_TOKEN_SYMBOL.into()); + p } pub fn dolphin_development_config() -> DolphinChainSpec { - let properties = dolphin_properties(); + let properties = dolphin_properties(); - DolphinChainSpec::from_genesis( - // Name - "Dolphin Parachain Development", - // ID - "dolphin_dev", - ChainType::Local, - move || { - dolphin_dev_genesis( - // initial collators. - vec![( - get_account_id_from_seed::("Alice"), - get_collator_keys_from_seed("Alice"), - )], - get_account_id_from_seed::("Alice"), - vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - get_account_id_from_seed::("Alice//stash"), - get_account_id_from_seed::("Bob//stash"), - ], - ) - }, - vec![], - None, - Some(DOLPHIN_PROTOCOL_ID), - None, - Some(properties), - Extensions { - relay_chain: "".into(), - para_id: DOLPHIN_PARACHAIN_ID, - }, - ) + DolphinChainSpec::from_genesis( + // Name + "Dolphin Parachain Development", + // ID + "dolphin_dev", + ChainType::Local, + move || { + dolphin_dev_genesis( + // initial collators. + vec![( + get_account_id_from_seed::("Alice"), + get_collator_keys_from_seed("Alice"), + )], + get_account_id_from_seed::("Alice"), + vec![ + get_account_id_from_seed::("Alice"), + get_account_id_from_seed::("Bob"), + get_account_id_from_seed::("Alice//stash"), + get_account_id_from_seed::("Bob//stash"), + ], + ) + }, + vec![], + None, + Some(DOLPHIN_PROTOCOL_ID), + None, + Some(properties), + Extensions { + relay_chain: "".into(), + para_id: DOLPHIN_PARACHAIN_ID, + }, + ) } pub fn dolphin_local_config() -> DolphinChainSpec { - let properties = dolphin_properties(); + let properties = dolphin_properties(); - DolphinChainSpec::from_genesis( - // Name - "Dolphin Parachain Local", - // ID - "dolphin_local", - ChainType::Local, - move || { - dolphin_dev_genesis( - // initial collators. - vec![ - ( - get_account_id_from_seed::("Alice"), - get_collator_keys_from_seed("Alice"), - ), - ( - get_account_id_from_seed::("Bob"), - get_collator_keys_from_seed("Bob"), - ), - ( - get_account_id_from_seed::("Charlie"), - get_collator_keys_from_seed("Charlie"), - ), - ( - get_account_id_from_seed::("Dave"), - get_collator_keys_from_seed("Dave"), - ), - ( - get_account_id_from_seed::("Eve"), - get_collator_keys_from_seed("Eve"), - ), - ], - get_account_id_from_seed::("Alice"), - vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - get_account_id_from_seed::("Charlie"), - get_account_id_from_seed::("Dave"), - get_account_id_from_seed::("Eve"), - get_account_id_from_seed::("Alice//stash"), - get_account_id_from_seed::("Bob//stash"), - get_account_id_from_seed::("Charlie//stash"), - get_account_id_from_seed::("Dave//stash"), - get_account_id_from_seed::("Eve//stash"), - ], - ) - }, - vec![], - None, - Some(DOLPHIN_PROTOCOL_ID), - None, - Some(properties), - Extensions { - relay_chain: "".into(), - para_id: DOLPHIN_PARACHAIN_ID, - }, - ) + DolphinChainSpec::from_genesis( + // Name + "Dolphin Parachain Local", + // ID + "dolphin_local", + ChainType::Local, + move || { + dolphin_dev_genesis( + // initial collators. + vec![ + ( + get_account_id_from_seed::("Alice"), + get_collator_keys_from_seed("Alice"), + ), + ( + get_account_id_from_seed::("Bob"), + get_collator_keys_from_seed("Bob"), + ), + ( + get_account_id_from_seed::("Charlie"), + get_collator_keys_from_seed("Charlie"), + ), + ( + get_account_id_from_seed::("Dave"), + get_collator_keys_from_seed("Dave"), + ), + ( + get_account_id_from_seed::("Eve"), + get_collator_keys_from_seed("Eve"), + ), + ], + get_account_id_from_seed::("Alice"), + vec![ + get_account_id_from_seed::("Alice"), + get_account_id_from_seed::("Bob"), + get_account_id_from_seed::("Charlie"), + get_account_id_from_seed::("Dave"), + get_account_id_from_seed::("Eve"), + get_account_id_from_seed::("Alice//stash"), + get_account_id_from_seed::("Bob//stash"), + get_account_id_from_seed::("Charlie//stash"), + get_account_id_from_seed::("Dave//stash"), + get_account_id_from_seed::("Eve//stash"), + ], + ) + }, + vec![], + None, + Some(DOLPHIN_PROTOCOL_ID), + None, + Some(properties), + Extensions { + relay_chain: "".into(), + para_id: DOLPHIN_PARACHAIN_ID, + }, + ) } fn dolphin_dev_genesis( - invulnerables: Vec<(AccountId, AuraId)>, - root_key: AccountId, - endowed_accounts: Vec, + invulnerables: Vec<(AccountId, AuraId)>, + root_key: AccountId, + endowed_accounts: Vec, ) -> dolphin_runtime::GenesisConfig { - dolphin_runtime::GenesisConfig { - system: dolphin_runtime::SystemConfig { - code: dolphin_runtime::WASM_BINARY - .expect("WASM binary was not build, please build it!") - .to_vec(), - }, - balances: dolphin_runtime::BalancesConfig { - balances: endowed_accounts[..endowed_accounts.len() / 2] - .iter() - .map(|k| { - ( - k.clone(), - 100 * DOLPHIN_ENDOWMENT / ((endowed_accounts.len() / 2) as Balance), - ) - }) - .collect(), - }, - // no need to pass anything to aura, in fact it will panic if we do. Session will take care - // of this. - aura: Default::default(), - sudo: dolphin_runtime::SudoConfig { - key: Some(root_key), - }, - parachain_info: dolphin_runtime::ParachainInfoConfig { - parachain_id: DOLPHIN_PARACHAIN_ID.into(), - }, - collator_selection: dolphin_runtime::CollatorSelectionConfig { - invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(), - candidacy_bond: DOL * 1000, // How many tokens will be reserved as collator - ..Default::default() - }, - session: dolphin_runtime::SessionConfig { - keys: invulnerables - .iter() - .cloned() - .map(|(acc, aura)| { - ( - acc.clone(), // account id - acc, // validator id - dolphin_session_keys(aura), // session keys - ) - }) - .collect(), - }, - democracy: DemocracyConfig::default(), - council: CouncilConfig { - members: endowed_accounts.iter().take(1).cloned().collect(), - phantom: Default::default(), - }, - technical_committee: TechnicalCommitteeConfig { - members: endowed_accounts.iter().take(1).cloned().collect(), - phantom: Default::default(), - }, - asset_manager: Default::default(), - council_membership: Default::default(), - technical_membership: Default::default(), - aura_ext: Default::default(), - parachain_system: Default::default(), - polkadot_xcm: dolphin_runtime::PolkadotXcmConfig { - safe_xcm_version: Some(SAFE_XCM_VERSION), - }, - } + dolphin_runtime::GenesisConfig { + system: dolphin_runtime::SystemConfig { + code: dolphin_runtime::WASM_BINARY + .expect("WASM binary was not build, please build it!") + .to_vec(), + }, + balances: dolphin_runtime::BalancesConfig { + balances: endowed_accounts[..endowed_accounts.len() / 2] + .iter() + .map(|k| { + ( + k.clone(), + 100 * DOLPHIN_ENDOWMENT / ((endowed_accounts.len() / 2) as Balance), + ) + }) + .collect(), + }, + // no need to pass anything to aura, in fact it will panic if we do. Session will take care + // of this. + aura: Default::default(), + sudo: dolphin_runtime::SudoConfig { + key: Some(root_key), + }, + parachain_info: dolphin_runtime::ParachainInfoConfig { + parachain_id: DOLPHIN_PARACHAIN_ID.into(), + }, + collator_selection: dolphin_runtime::CollatorSelectionConfig { + invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(), + candidacy_bond: DOL * 1000, // How many tokens will be reserved as collator + ..Default::default() + }, + session: dolphin_runtime::SessionConfig { + keys: invulnerables + .iter() + .cloned() + .map(|(acc, aura)| { + ( + acc.clone(), // account id + acc, // validator id + dolphin_session_keys(aura), // session keys + ) + }) + .collect(), + }, + democracy: DemocracyConfig::default(), + council: CouncilConfig { + members: endowed_accounts.iter().take(1).cloned().collect(), + phantom: Default::default(), + }, + technical_committee: TechnicalCommitteeConfig { + members: endowed_accounts.iter().take(1).cloned().collect(), + phantom: Default::default(), + }, + asset_manager: Default::default(), + council_membership: Default::default(), + technical_membership: Default::default(), + aura_ext: Default::default(), + parachain_system: Default::default(), + polkadot_xcm: dolphin_runtime::PolkadotXcmConfig { + safe_xcm_version: Some(SAFE_XCM_VERSION), + }, + } } pub fn dolphin_testnet_config() -> Result { - let mut spec = DolphinChainSpec::from_json_bytes( - &include_bytes!("../../../genesis/dolphin-testnet-genesis.json")[..], - )?; - spec.extensions_mut().para_id = DOLPHIN_PARACHAIN_ID; - Ok(spec) + let mut spec = DolphinChainSpec::from_json_bytes( + &include_bytes!("../../../genesis/dolphin-testnet-genesis.json")[..], + )?; + spec.extensions_mut().para_id = DOLPHIN_PARACHAIN_ID; + Ok(spec) } diff --git a/node/src/chain_specs/manta.rs b/node/src/chain_specs/manta.rs index dbb45c9ca..023fe021a 100644 --- a/node/src/chain_specs/manta.rs +++ b/node/src/chain_specs/manta.rs @@ -33,176 +33,176 @@ pub type MantaChainSpec = sc_service::GenericChainSpec manta_runtime::opaque::SessionKeys { - manta_runtime::opaque::SessionKeys { aura: keys } + manta_runtime::opaque::SessionKeys { aura: keys } } /// Token pub fn manta_properties() -> Properties { - let mut p = Properties::new(); - p.insert("ss58format".into(), constants::MANTA_SS58PREFIX.into()); - p.insert("tokenDecimals".into(), constants::MANTA_DECIMAL.into()); - p.insert("tokenSymbol".into(), constants::MANTA_TOKEN_SYMBOL.into()); - p + let mut p = Properties::new(); + p.insert("ss58format".into(), constants::MANTA_SS58PREFIX.into()); + p.insert("tokenDecimals".into(), constants::MANTA_DECIMAL.into()); + p.insert("tokenSymbol".into(), constants::MANTA_TOKEN_SYMBOL.into()); + p } // manta chain spec pub fn manta_development_config() -> MantaChainSpec { - let properties = manta_properties(); - MantaChainSpec::from_genesis( - // Name - "Manta Parachain Development", - // ID - "manta_dev", - ChainType::Local, - move || { - manta_dev_genesis( - // initial collators. - vec![( - get_account_id_from_seed::("Alice"), - get_collator_keys_from_seed("Alice"), - )], - get_account_id_from_seed::("Alice"), - vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - get_account_id_from_seed::("Alice//stash"), - get_account_id_from_seed::("Bob//stash"), - ], - ) - }, - vec![], - None, - Some(MANTA_PROTOCOL_ID), - None, - Some(properties), - Extensions { - relay_chain: POLKADOT_RELAYCHAIN_DEV_NET.into(), - para_id: MANTA_PARACHAIN_ID, - }, - ) + let properties = manta_properties(); + MantaChainSpec::from_genesis( + // Name + "Manta Parachain Development", + // ID + "manta_dev", + ChainType::Local, + move || { + manta_dev_genesis( + // initial collators. + vec![( + get_account_id_from_seed::("Alice"), + get_collator_keys_from_seed("Alice"), + )], + get_account_id_from_seed::("Alice"), + vec![ + get_account_id_from_seed::("Alice"), + get_account_id_from_seed::("Bob"), + get_account_id_from_seed::("Alice//stash"), + get_account_id_from_seed::("Bob//stash"), + ], + ) + }, + vec![], + None, + Some(MANTA_PROTOCOL_ID), + None, + Some(properties), + Extensions { + relay_chain: POLKADOT_RELAYCHAIN_DEV_NET.into(), + para_id: MANTA_PARACHAIN_ID, + }, + ) } pub fn manta_local_config() -> MantaChainSpec { - let properties = manta_properties(); - MantaChainSpec::from_genesis( - // Name - "Manta Parachain Local", - // ID - "manta_local", - ChainType::Local, - move || { - manta_dev_genesis( - // initial collators. - vec![ - ( - get_account_id_from_seed::("Alice"), - get_collator_keys_from_seed("Alice"), - ), - ( - get_account_id_from_seed::("Bob"), - get_collator_keys_from_seed("Bob"), - ), - ], - get_account_id_from_seed::("Alice"), - vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - get_account_id_from_seed::("Charlie"), - get_account_id_from_seed::("Dave"), - get_account_id_from_seed::("Eve"), - get_account_id_from_seed::("Alice//stash"), - get_account_id_from_seed::("Bob//stash"), - get_account_id_from_seed::("Charlie//stash"), - get_account_id_from_seed::("Dave//stash"), - get_account_id_from_seed::("Eve//stash"), - ], - ) - }, - vec![], - None, - Some(MANTA_PROTOCOL_ID), - None, - Some(properties), - Extensions { - relay_chain: POLKADOT_RELAYCHAIN_LOCAL_NET.into(), - para_id: MANTA_PARACHAIN_ID, - }, - ) + let properties = manta_properties(); + MantaChainSpec::from_genesis( + // Name + "Manta Parachain Local", + // ID + "manta_local", + ChainType::Local, + move || { + manta_dev_genesis( + // initial collators. + vec![ + ( + get_account_id_from_seed::("Alice"), + get_collator_keys_from_seed("Alice"), + ), + ( + get_account_id_from_seed::("Bob"), + get_collator_keys_from_seed("Bob"), + ), + ], + get_account_id_from_seed::("Alice"), + vec![ + get_account_id_from_seed::("Alice"), + get_account_id_from_seed::("Bob"), + get_account_id_from_seed::("Charlie"), + get_account_id_from_seed::("Dave"), + get_account_id_from_seed::("Eve"), + get_account_id_from_seed::("Alice//stash"), + get_account_id_from_seed::("Bob//stash"), + get_account_id_from_seed::("Charlie//stash"), + get_account_id_from_seed::("Dave//stash"), + get_account_id_from_seed::("Eve//stash"), + ], + ) + }, + vec![], + None, + Some(MANTA_PROTOCOL_ID), + None, + Some(properties), + Extensions { + relay_chain: POLKADOT_RELAYCHAIN_LOCAL_NET.into(), + para_id: MANTA_PARACHAIN_ID, + }, + ) } fn manta_dev_genesis( - invulnerables: Vec<(AccountId, AuraId)>, - root_key: AccountId, - endowed_accounts: Vec, + invulnerables: Vec<(AccountId, AuraId)>, + root_key: AccountId, + endowed_accounts: Vec, ) -> manta_runtime::GenesisConfig { - manta_runtime::GenesisConfig { - system: manta_runtime::SystemConfig { - code: manta_runtime::WASM_BINARY - .expect("WASM binary was not build, please build it!") - .to_vec(), - }, - balances: manta_runtime::BalancesConfig { - balances: endowed_accounts[..endowed_accounts.len() / 2] - .iter() - .map(|k| { - ( - k.clone(), - 10 * MANTA_ENDOWMENT / ((endowed_accounts.len() / 2) as Balance), - ) - }) - .collect(), - }, - // no need to pass anything to aura, in fact it will panic if we do. Session will take care - // of this. - aura: Default::default(), - sudo: manta_runtime::SudoConfig { - key: Some(root_key), - }, - parachain_info: manta_runtime::ParachainInfoConfig { - parachain_id: MANTA_PARACHAIN_ID.into(), - }, - collator_selection: manta_runtime::CollatorSelectionConfig { - invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(), - candidacy_bond: MANTA * 10000, // How many tokens will be reserved as collator - ..Default::default() - }, - session: manta_runtime::SessionConfig { - keys: invulnerables - .iter() - .cloned() - .map(|(acc, aura)| { - ( - acc.clone(), // account id - acc, // validator id - manta_session_keys(aura), // session keys - ) - }) - .collect(), - }, - aura_ext: Default::default(), - parachain_system: Default::default(), - polkadot_xcm: manta_runtime::PolkadotXcmConfig { - safe_xcm_version: Some(SAFE_XCM_VERSION), - }, - } + manta_runtime::GenesisConfig { + system: manta_runtime::SystemConfig { + code: manta_runtime::WASM_BINARY + .expect("WASM binary was not build, please build it!") + .to_vec(), + }, + balances: manta_runtime::BalancesConfig { + balances: endowed_accounts[..endowed_accounts.len() / 2] + .iter() + .map(|k| { + ( + k.clone(), + 10 * MANTA_ENDOWMENT / ((endowed_accounts.len() / 2) as Balance), + ) + }) + .collect(), + }, + // no need to pass anything to aura, in fact it will panic if we do. Session will take care + // of this. + aura: Default::default(), + sudo: manta_runtime::SudoConfig { + key: Some(root_key), + }, + parachain_info: manta_runtime::ParachainInfoConfig { + parachain_id: MANTA_PARACHAIN_ID.into(), + }, + collator_selection: manta_runtime::CollatorSelectionConfig { + invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(), + candidacy_bond: MANTA * 10000, // How many tokens will be reserved as collator + ..Default::default() + }, + session: manta_runtime::SessionConfig { + keys: invulnerables + .iter() + .cloned() + .map(|(acc, aura)| { + ( + acc.clone(), // account id + acc, // validator id + manta_session_keys(aura), // session keys + ) + }) + .collect(), + }, + aura_ext: Default::default(), + parachain_system: Default::default(), + polkadot_xcm: manta_runtime::PolkadotXcmConfig { + safe_xcm_version: Some(SAFE_XCM_VERSION), + }, + } } pub fn manta_testnet_config() -> Result { - let mut spec = MantaChainSpec::from_json_bytes( - &include_bytes!("../../../genesis/manta-testnet-genesis.json")[..], - )?; - spec.extensions_mut().para_id = MANTA_PARACHAIN_ID; - Ok(spec) + let mut spec = MantaChainSpec::from_json_bytes( + &include_bytes!("../../../genesis/manta-testnet-genesis.json")[..], + )?; + spec.extensions_mut().para_id = MANTA_PARACHAIN_ID; + Ok(spec) } pub fn manta_config() -> Result { - MantaChainSpec::from_json_bytes(&include_bytes!("../../../genesis/manta-genesis.json")[..]) + MantaChainSpec::from_json_bytes(&include_bytes!("../../../genesis/manta-genesis.json")[..]) } pub fn manta_testnet_ci_config() -> Result { - let mut spec = MantaChainSpec::from_json_bytes( - &include_bytes!("../../../genesis/manta-testnet-ci-genesis.json")[..], - )?; - spec.extensions_mut().para_id = MANTA_PARACHAIN_ID; - Ok(spec) + let mut spec = MantaChainSpec::from_json_bytes( + &include_bytes!("../../../genesis/manta-testnet-ci-genesis.json")[..], + )?; + spec.extensions_mut().para_id = MANTA_PARACHAIN_ID; + Ok(spec) } diff --git a/node/src/chain_specs/mod.rs b/node/src/chain_specs/mod.rs index 82c823853..f6be23319 100644 --- a/node/src/chain_specs/mod.rs +++ b/node/src/chain_specs/mod.rs @@ -15,10 +15,12 @@ // along with Manta. If not, see . #![allow(dead_code)] +// Tolerate clippy warning originating in ChainSpecGroup, which is a dependency +#![allow(clippy::derive_partial_eq_without_eq)] use manta_primitives::{ - constants, - types::{AccountId, AuraId, Balance}, + constants, + types::{AccountId, AuraId, Balance}, }; use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup}; use sc_service::{ChainType, Properties}; @@ -46,18 +48,20 @@ const STAGING_TELEMETRY_URL: &str = "wss://api.telemetry.manta.systems/submit/"; pub type ChainSpec = sc_service::GenericChainSpec; /// The extensions for the [`ChainSpec`]. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ChainSpecGroup, ChainSpecExtension)] +#[derive( + Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ChainSpecGroup, ChainSpecExtension, +)] #[serde(deny_unknown_fields)] pub struct Extensions { - /// The relay chain of the Parachain. - pub relay_chain: String, - /// The id of the Parachain. - pub para_id: u32, + /// The relay chain of the Parachain. + pub relay_chain: String, + /// The id of the Parachain. + pub para_id: u32, } impl Extensions { - /// Try to get the extension from the given `ChainSpec`. - pub fn try_get(chain_spec: &dyn sc_service::ChainSpec) -> Option<&Self> { - sc_chain_spec::get_extension(chain_spec.extensions()) - } + /// Try to get the extension from the given `ChainSpec`. + pub fn try_get(chain_spec: &dyn sc_service::ChainSpec) -> Option<&Self> { + sc_chain_spec::get_extension(chain_spec.extensions()) + } } diff --git a/node/src/cli.rs b/node/src/cli.rs index 5d73e5964..97a4b19d0 100644 --- a/node/src/cli.rs +++ b/node/src/cli.rs @@ -21,133 +21,133 @@ use std::path::PathBuf; /// Sub-commands supported by the collator. #[derive(Debug, clap::Subcommand)] pub enum Subcommand { - /// Export the genesis state of the parachain. - #[clap(name = "export-genesis-state")] - ExportGenesisState(ExportGenesisStateCommand), + /// Export the genesis state of the parachain. + #[clap(name = "export-genesis-state")] + ExportGenesisState(ExportGenesisStateCommand), - /// Export the genesis wasm of the parachain. - #[clap(name = "export-genesis-wasm")] - ExportGenesisWasm(ExportGenesisWasmCommand), + /// Export the genesis wasm of the parachain. + #[clap(name = "export-genesis-wasm")] + ExportGenesisWasm(ExportGenesisWasmCommand), - /// Build a chain specification. - BuildSpec(sc_cli::BuildSpecCmd), + /// Build a chain specification. + BuildSpec(sc_cli::BuildSpecCmd), - /// Validate blocks. - CheckBlock(sc_cli::CheckBlockCmd), + /// Validate blocks. + CheckBlock(sc_cli::CheckBlockCmd), - /// Export blocks. - ExportBlocks(sc_cli::ExportBlocksCmd), + /// Export blocks. + ExportBlocks(sc_cli::ExportBlocksCmd), - /// Export the state of a given block into a chain spec. - ExportState(sc_cli::ExportStateCmd), + /// Export the state of a given block into a chain spec. + ExportState(sc_cli::ExportStateCmd), - /// Import blocks. - ImportBlocks(sc_cli::ImportBlocksCmd), + /// Import blocks. + ImportBlocks(sc_cli::ImportBlocksCmd), - /// Remove the whole chain. - PurgeChain(cumulus_client_cli::PurgeChainCmd), + /// Remove the whole chain. + PurgeChain(cumulus_client_cli::PurgeChainCmd), - /// Revert the chain to a previous state. - Revert(sc_cli::RevertCmd), + /// Revert the chain to a previous state. + Revert(sc_cli::RevertCmd), - /// The custom benchmark subcommmand benchmarking runtime pallets. - #[clap(name = "benchmark", about = "Benchmark runtime pallets.")] - Benchmark(frame_benchmarking_cli::BenchmarkCmd), + /// The custom benchmark subcommmand benchmarking runtime pallets. + #[clap(name = "benchmark", about = "Benchmark runtime pallets.")] + Benchmark(frame_benchmarking_cli::BenchmarkCmd), - /// Try some command against runtime state. - #[cfg(feature = "try-runtime")] - TryRuntime(try_runtime_cli::TryRuntimeCmd), + /// Try some command against runtime state. + #[cfg(feature = "try-runtime")] + TryRuntime(try_runtime_cli::TryRuntimeCmd), - /// Try some command against runtime state. Note: `try-runtime` feature must - /// be enabled. - #[cfg(not(feature = "try-runtime"))] - TryRuntime, + /// Try some command against runtime state. Note: `try-runtime` feature must + /// be enabled. + #[cfg(not(feature = "try-runtime"))] + TryRuntime, } /// Command for exporting the genesis state of the parachain #[derive(Debug, Parser)] pub struct ExportGenesisStateCommand { - /// Output file name or stdout if unspecified. - #[clap(parse(from_os_str))] - pub output: Option, - - /// Id of the parachain this state is for. - /// - /// Default: 2084 - #[clap(long)] - pub parachain_id: Option, - - /// Write output in binary. Default is to write in hex. - #[clap(short, long)] - pub raw: bool, - - /// The name of the chain for that the genesis state should be exported. - #[clap(long)] - pub chain: Option, + /// Output file name or stdout if unspecified. + #[clap(parse(from_os_str))] + pub output: Option, + + /// Id of the parachain this state is for. + /// + /// Default: 2084 + #[clap(long)] + pub parachain_id: Option, + + /// Write output in binary. Default is to write in hex. + #[clap(short, long)] + pub raw: bool, + + /// The name of the chain for that the genesis state should be exported. + #[clap(long)] + pub chain: Option, } /// Command for exporting the genesis wasm file. #[derive(Debug, Parser)] pub struct ExportGenesisWasmCommand { - /// Output file name or stdout if unspecified. - #[clap(parse(from_os_str))] - pub output: Option, + /// Output file name or stdout if unspecified. + #[clap(parse(from_os_str))] + pub output: Option, - /// Write output in binary. Default is to write in hex. - #[clap(short, long)] - pub raw: bool, + /// Write output in binary. Default is to write in hex. + #[clap(short, long)] + pub raw: bool, - /// The name of the chain for that the genesis wasm file should be exported. - #[clap(long)] - pub chain: Option, + /// The name of the chain for that the genesis wasm file should be exported. + #[clap(long)] + pub chain: Option, } #[derive(Debug, Parser)] #[clap( - propagate_version = true, - args_conflicts_with_subcommands = true, - subcommand_negates_reqs = true + propagate_version = true, + args_conflicts_with_subcommands = true, + subcommand_negates_reqs = true )] pub struct Cli { - #[clap(subcommand)] - pub subcommand: Option, + #[clap(subcommand)] + pub subcommand: Option, - #[clap(flatten)] - pub run: cumulus_client_cli::RunCmd, + #[clap(flatten)] + pub run: cumulus_client_cli::RunCmd, - /// Relaychain arguments - #[clap(raw = true)] - pub relaychain_args: Vec, + /// Relaychain arguments + #[clap(raw = true)] + pub relaychain_args: Vec, } #[derive(Debug)] pub struct RelayChainCli { - /// The actual relay chain cli object. - pub base: polkadot_cli::RunCmd, + /// The actual relay chain cli object. + pub base: polkadot_cli::RunCmd, - /// Optional chain id that should be passed to the relay chain. - pub chain_id: Option, + /// Optional chain id that should be passed to the relay chain. + pub chain_id: Option, - /// The base path that should be used by the relay chain. - pub base_path: Option, + /// The base path that should be used by the relay chain. + pub base_path: Option, } impl RelayChainCli { - /// Parse the relay chain CLI parameters using the para chain `Configuration`. - pub fn new<'a>( - para_config: &sc_service::Configuration, - relay_chain_args: impl Iterator, - ) -> Self { - let extension = chain_specs::Extensions::try_get(&*para_config.chain_spec); - let chain_id = extension.map(|e| e.relay_chain.clone()); - let base_path = para_config - .base_path - .as_ref() - .map(|x| x.path().join("polkadot")); - Self { - base_path, - chain_id, - base: polkadot_cli::RunCmd::parse_from(relay_chain_args), - } - } + /// Parse the relay chain CLI parameters using the para chain `Configuration`. + pub fn new<'a>( + para_config: &sc_service::Configuration, + relay_chain_args: impl Iterator, + ) -> Self { + let extension = chain_specs::Extensions::try_get(&*para_config.chain_spec); + let chain_id = extension.map(|e| e.relay_chain.clone()); + let base_path = para_config + .base_path + .as_ref() + .map(|x| x.path().join("polkadot")); + Self { + base_path, + chain_id, + base: polkadot_cli::RunCmd::parse_from(relay_chain_args), + } + } } diff --git a/node/src/command.rs b/node/src/command.rs index f37f3aab9..d74dde599 100644 --- a/node/src/command.rs +++ b/node/src/command.rs @@ -1,4 +1,4 @@ -// Copyright 2019-2022 Manta Network. +// Copyright 2020-2022 Manta Network. // This file is part of Manta. // // Manta is free software: you can redistribute it and/or modify @@ -15,10 +15,10 @@ // along with Manta. If not, see . use crate::{ - chain_specs, - cli::{Cli, RelayChainCli, Subcommand}, - rpc::{self, Builder}, - service::{new_partial, CalamariRuntimeExecutor, DolphinRuntimeExecutor, MantaRuntimeExecutor}, + chain_specs, + cli::{Cli, RelayChainCli, Subcommand}, + rpc::{self, Builder}, + service::{new_partial, CalamariRuntimeExecutor, DolphinRuntimeExecutor, MantaRuntimeExecutor}, }; use codec::Encode; use cumulus_client_service::genesis::generate_genesis_block; @@ -27,8 +27,8 @@ use log::info; use manta_primitives::types::{AuraId, Header}; use polkadot_parachain::primitives::AccountIdConversion; use sc_cli::{ - ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams, - NetworkParams, Result, RuntimeVersion, SharedParams, SubstrateCli, + ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams, + NetworkParams, Result, RuntimeVersion, SharedParams, SubstrateCli, }; use sc_service::config::{BasePath, PrometheusConfig}; use sp_core::hexdisplay::HexDisplay; @@ -42,579 +42,579 @@ pub const CALAMARI_PARACHAIN_ID: u32 = 2084; pub const DOLPHIN_PARACHAIN_ID: u32 = 2084; trait IdentifyChain { - fn is_manta(&self) -> bool; - fn is_calamari(&self) -> bool; - fn is_dolphin(&self) -> bool; + fn is_manta(&self) -> bool; + fn is_calamari(&self) -> bool; + fn is_dolphin(&self) -> bool; } impl IdentifyChain for dyn sc_service::ChainSpec { - fn is_manta(&self) -> bool { - self.id().starts_with("manta") - } - fn is_calamari(&self) -> bool { - self.id().starts_with("calamari") - } - fn is_dolphin(&self) -> bool { - self.id().starts_with("dolphin") - } + fn is_manta(&self) -> bool { + self.id().starts_with("manta") + } + fn is_calamari(&self) -> bool { + self.id().starts_with("calamari") + } + fn is_dolphin(&self) -> bool { + self.id().starts_with("dolphin") + } } impl IdentifyChain for T { - fn is_manta(&self) -> bool { - ::is_manta(self) - } - fn is_calamari(&self) -> bool { - ::is_calamari(self) - } - fn is_dolphin(&self) -> bool { - ::is_dolphin(self) - } + fn is_manta(&self) -> bool { + ::is_manta(self) + } + fn is_calamari(&self) -> bool { + ::is_calamari(self) + } + fn is_dolphin(&self) -> bool { + ::is_dolphin(self) + } } fn load_spec(id: &str) -> std::result::Result, String> { - match id { - // manta chainspec - "manta-dev" => Ok(Box::new(chain_specs::manta_development_config())), - "manta-local" => Ok(Box::new(chain_specs::manta_local_config())), - "manta-testnet" => Ok(Box::new(chain_specs::manta_testnet_config()?)), - "manta-testnet-ci" => Ok(Box::new(chain_specs::manta_testnet_ci_config()?)), - "manta" => Ok(Box::new(chain_specs::manta_config()?)), - // calamari chainspec - "calamari-dev" => Ok(Box::new(chain_specs::calamari_development_config())), - "calamari-local" => Ok(Box::new(chain_specs::calamari_local_config())), - "calamari-testnet" => Ok(Box::new(chain_specs::calamari_testnet_config()?)), - "calamari-testnet-ci" => Ok(Box::new(chain_specs::calamari_testnet_ci_config()?)), - "calamari" => Ok(Box::new(chain_specs::calamari_config()?)), - // dolphin chainspec - "dolphin-dev" => Ok(Box::new(chain_specs::dolphin_development_config())), - "dolphin-local" => Ok(Box::new(chain_specs::dolphin_local_config())), - "dolphin-testnet" => Ok(Box::new(chain_specs::dolphin_testnet_config()?)), - path => { - let chain_spec = chain_specs::ChainSpec::from_json_file(path.into())?; - if chain_spec.is_manta() { - Ok(Box::new(chain_specs::MantaChainSpec::from_json_file( - path.into(), - )?)) - } else if chain_spec.is_calamari() { - Ok(Box::new(chain_specs::CalamariChainSpec::from_json_file( - path.into(), - )?)) - } else if chain_spec.is_dolphin() { - Ok(Box::new(chain_specs::DolphinChainSpec::from_json_file( - path.into(), - )?)) - } else { - Err("Please input a file name starting with manta, calamari, or dolphin.".into()) - } - } - } + match id { + // manta chainspec + "manta-dev" => Ok(Box::new(chain_specs::manta_development_config())), + "manta-local" => Ok(Box::new(chain_specs::manta_local_config())), + "manta-testnet" => Ok(Box::new(chain_specs::manta_testnet_config()?)), + "manta-testnet-ci" => Ok(Box::new(chain_specs::manta_testnet_ci_config()?)), + "manta" => Ok(Box::new(chain_specs::manta_config()?)), + // calamari chainspec + "calamari-dev" => Ok(Box::new(chain_specs::calamari_development_config())), + "calamari-local" => Ok(Box::new(chain_specs::calamari_local_config())), + "calamari-testnet" => Ok(Box::new(chain_specs::calamari_testnet_config()?)), + "calamari-testnet-ci" => Ok(Box::new(chain_specs::calamari_testnet_ci_config()?)), + "calamari" => Ok(Box::new(chain_specs::calamari_config()?)), + // dolphin chainspec + "dolphin-dev" => Ok(Box::new(chain_specs::dolphin_development_config())), + "dolphin-local" => Ok(Box::new(chain_specs::dolphin_local_config())), + "dolphin-testnet" => Ok(Box::new(chain_specs::dolphin_testnet_config()?)), + path => { + let chain_spec = chain_specs::ChainSpec::from_json_file(path.into())?; + if chain_spec.is_manta() { + Ok(Box::new(chain_specs::MantaChainSpec::from_json_file( + path.into(), + )?)) + } else if chain_spec.is_calamari() { + Ok(Box::new(chain_specs::CalamariChainSpec::from_json_file( + path.into(), + )?)) + } else if chain_spec.is_dolphin() { + Ok(Box::new(chain_specs::DolphinChainSpec::from_json_file( + path.into(), + )?)) + } else { + Err("Please input a file name starting with manta, calamari, or dolphin.".into()) + } + } + } } impl SubstrateCli for Cli { - fn impl_name() -> String { - "Manta/Calamari/Dolphin Collator".into() - } - - fn impl_version() -> String { - env!("SUBSTRATE_CLI_IMPL_VERSION").into() - } - - fn description() -> String { - format!( - "Manta/Calamari/Dolphin Collator\n\nThe command-line arguments provided first will be \ - passed to the parachain node, while the arguments provided after -- will be passed \ - to the relaychain node.\n\n\ - {} [parachain-args] -- [relaychain-args]", - Self::executable_name() - ) - } - - fn author() -> String { - env!("CARGO_PKG_AUTHORS").into() - } - - fn support_url() -> String { - "https://github.com/Manta-Network/Manta/issues/new".into() - } - - fn copyright_start_year() -> i32 { - 2020 - } - - fn load_spec(&self, id: &str) -> std::result::Result, String> { - load_spec(id) - } - - fn native_runtime_version(chain_spec: &Box) -> &'static RuntimeVersion { - if chain_spec.is_manta() { - &manta_runtime::VERSION - } else if chain_spec.is_calamari() { - &calamari_runtime::VERSION - } else if chain_spec.is_dolphin() { - &dolphin_runtime::VERSION - } else { - panic!("invalid chain spec! should be one of manta, calamari, or dolphin chain specs") - } - } + fn impl_name() -> String { + "Manta/Calamari/Dolphin Collator".into() + } + + fn impl_version() -> String { + env!("SUBSTRATE_CLI_IMPL_VERSION").into() + } + + fn description() -> String { + format!( + "Manta/Calamari/Dolphin Collator\n\nThe command-line arguments provided first will be \ + passed to the parachain node, while the arguments provided after -- will be passed \ + to the relaychain node.\n\n\ + {} [parachain-args] -- [relaychain-args]", + Self::executable_name() + ) + } + + fn author() -> String { + env!("CARGO_PKG_AUTHORS").into() + } + + fn support_url() -> String { + "https://github.com/Manta-Network/Manta/issues/new".into() + } + + fn copyright_start_year() -> i32 { + 2020 + } + + fn load_spec(&self, id: &str) -> std::result::Result, String> { + load_spec(id) + } + + fn native_runtime_version(chain_spec: &Box) -> &'static RuntimeVersion { + if chain_spec.is_manta() { + &manta_runtime::VERSION + } else if chain_spec.is_calamari() { + &calamari_runtime::VERSION + } else if chain_spec.is_dolphin() { + &dolphin_runtime::VERSION + } else { + panic!("invalid chain spec! should be one of manta, calamari, or dolphin chain specs") + } + } } impl SubstrateCli for RelayChainCli { - fn impl_name() -> String { - "Manta/Calamari/Dolphin Collator".into() - } - - fn impl_version() -> String { - env!("SUBSTRATE_CLI_IMPL_VERSION").into() - } - - fn description() -> String { - format!( - "Manta/Calamari/Dolphin collator\n\nThe command-line arguments provided first will be \ - passed to the parachain node, while the arguments provided after -- will be passed \ - to the relaychain node.\n\n\ - {} [parachain-args] -- [relaychain-args]", - Self::executable_name() - ) - } - - fn author() -> String { - env!("CARGO_PKG_AUTHORS").into() - } - - fn support_url() -> String { - "https://github.com/Manta-Network/Manta/issues/new".into() - } - - fn copyright_start_year() -> i32 { - 2020 - } - - fn load_spec(&self, id: &str) -> std::result::Result, String> { - polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id) - } - - fn native_runtime_version(chain_spec: &Box) -> &'static RuntimeVersion { - polkadot_cli::Cli::native_runtime_version(chain_spec) - } + fn impl_name() -> String { + "Manta/Calamari/Dolphin Collator".into() + } + + fn impl_version() -> String { + env!("SUBSTRATE_CLI_IMPL_VERSION").into() + } + + fn description() -> String { + format!( + "Manta/Calamari/Dolphin collator\n\nThe command-line arguments provided first will be \ + passed to the parachain node, while the arguments provided after -- will be passed \ + to the relaychain node.\n\n\ + {} [parachain-args] -- [relaychain-args]", + Self::executable_name() + ) + } + + fn author() -> String { + env!("CARGO_PKG_AUTHORS").into() + } + + fn support_url() -> String { + "https://github.com/Manta-Network/Manta/issues/new".into() + } + + fn copyright_start_year() -> i32 { + 2020 + } + + fn load_spec(&self, id: &str) -> std::result::Result, String> { + polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id) + } + + fn native_runtime_version(chain_spec: &Box) -> &'static RuntimeVersion { + polkadot_cli::Cli::native_runtime_version(chain_spec) + } } #[allow(clippy::borrowed_box)] fn extract_genesis_wasm(chain_spec: &Box) -> Result> { - let mut storage = chain_spec.build_storage()?; - storage - .top - .remove(sp_core::storage::well_known_keys::CODE) - .ok_or_else(|| "Could not find wasm file in genesis state!".into()) + let mut storage = chain_spec.build_storage()?; + storage + .top + .remove(sp_core::storage::well_known_keys::CODE) + .ok_or_else(|| "Could not find wasm file in genesis state!".into()) } macro_rules! construct_async_run { - (|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{ - let runner = $cli.create_runner($cmd)?; - if runner.config().chain_spec.is_manta() { - runner.async_run(|$config| { - let $components = new_partial::( - &$config, - crate::service::parachain_build_import_queue::<_, _, AuraId>, - )?; - let task_manager = $components.task_manager; - { $( $code )* }.map(|v| (v, task_manager)) - }) - } else if runner.config().chain_spec.is_calamari() { - runner.async_run(|$config| { - let $components = new_partial::( - &$config, - crate::service::parachain_build_import_queue::<_, _, AuraId>, - )?; - let task_manager = $components.task_manager; - { $( $code )* }.map(|v| (v, task_manager)) - }) - } else if runner.config().chain_spec.is_dolphin() { - runner.async_run(|$config| { - let $components = new_partial::( - &$config, - crate::service::parachain_build_import_queue::<_, _, AuraId>, - )?; - let task_manager = $components.task_manager; - { $( $code )* }.map(|v| (v, task_manager)) - }) - } else { - panic!("wrong chain spec, must be one of manta, calamari, or dolphin chain specs"); - } - }} + (|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{ + let runner = $cli.create_runner($cmd)?; + if runner.config().chain_spec.is_manta() { + runner.async_run(|$config| { + let $components = new_partial::( + &$config, + crate::service::parachain_build_import_queue::<_, _, AuraId>, + )?; + let task_manager = $components.task_manager; + { $( $code )* }.map(|v| (v, task_manager)) + }) + } else if runner.config().chain_spec.is_calamari() { + runner.async_run(|$config| { + let $components = new_partial::( + &$config, + crate::service::parachain_build_import_queue::<_, _, AuraId>, + )?; + let task_manager = $components.task_manager; + { $( $code )* }.map(|v| (v, task_manager)) + }) + } else if runner.config().chain_spec.is_dolphin() { + runner.async_run(|$config| { + let $components = new_partial::( + &$config, + crate::service::parachain_build_import_queue::<_, _, AuraId>, + )?; + let task_manager = $components.task_manager; + { $( $code )* }.map(|v| (v, task_manager)) + }) + } else { + panic!("wrong chain spec, must be one of manta, calamari, or dolphin chain specs"); + } + }} } /// Parse command line arguments into service configuration. pub fn run_with(cli: Cli) -> Result<()> { - match &cli.subcommand { - Some(Subcommand::BuildSpec(cmd)) => { - let runner = cli.create_runner(cmd)?; - runner.sync_run(|config| cmd.run(config.chain_spec, config.network)) - } - Some(Subcommand::CheckBlock(cmd)) => { - construct_async_run!(|components, cli, cmd, config| { - Ok(cmd.run(components.client, components.import_queue)) - }) - } - Some(Subcommand::ExportBlocks(cmd)) => { - construct_async_run!(|components, cli, cmd, config| { - Ok(cmd.run(components.client, config.database)) - }) - } - Some(Subcommand::ExportState(cmd)) => { - construct_async_run!(|components, cli, cmd, config| { - Ok(cmd.run(components.client, config.chain_spec)) - }) - } - Some(Subcommand::ImportBlocks(cmd)) => { - construct_async_run!(|components, cli, cmd, config| { - Ok(cmd.run(components.client, components.import_queue)) - }) - } - Some(Subcommand::PurgeChain(cmd)) => { - let runner = cli.create_runner(cmd)?; - - runner.sync_run(|config| { - let polkadot_cli = RelayChainCli::new( - &config, - [RelayChainCli::executable_name()] - .iter() - .chain(cli.relaychain_args.iter()), - ); - - let polkadot_config = SubstrateCli::create_configuration( - &polkadot_cli, - &polkadot_cli, - config.tokio_handle.clone(), - ) - .map_err(|err| format!("Relay chain argument error: {}", err))?; - - cmd.run(config, polkadot_config) - }) - } - Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| { - Ok(cmd.run(components.client, components.backend)) - }), - Some(Subcommand::ExportGenesisState(params)) => { - let mut builder = sc_cli::LoggerBuilder::new(""); - builder.with_profiling(sc_tracing::TracingReceiver::Log, ""); - let _ = builder.init(); - - let spec = load_spec(¶ms.chain.clone().unwrap_or_default())?; - let state_version = Cli::native_runtime_version(&spec).state_version(); - - let block: crate::service::Block = generate_genesis_block(&spec, state_version)?; - let raw_header = block.header().encode(); - let output_buf = if params.raw { - raw_header - } else { - format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes() - }; - - if let Some(output) = ¶ms.output { - std::fs::write(output, output_buf)?; - } else { - std::io::stdout().write_all(&output_buf)?; - } - - Ok(()) - } - Some(Subcommand::ExportGenesisWasm(params)) => { - let mut builder = sc_cli::LoggerBuilder::new(""); - builder.with_profiling(sc_tracing::TracingReceiver::Log, ""); - let _ = builder.init(); - - let raw_wasm_blob = - extract_genesis_wasm(&cli.load_spec(¶ms.chain.clone().unwrap_or_default())?)?; - let output_buf = if params.raw { - raw_wasm_blob - } else { - format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes() - }; - - if let Some(output) = ¶ms.output { - std::fs::write(output, output_buf)?; - } else { - std::io::stdout().write_all(&output_buf)?; - } - - Ok(()) - } - Some(Subcommand::Benchmark(cmd)) => { - let runner = cli.create_runner(cmd)?; - if runner.config().chain_spec.is_manta() { - runner.sync_run(|config| cmd.run::(config)) - } else if runner.config().chain_spec.is_calamari() { - runner.sync_run(|config| cmd.run::(config)) - } else if runner.config().chain_spec.is_dolphin() { - runner.sync_run(|config| cmd.run::(config)) - } else { - Err("Benchmarking wasn't enabled when building the node. \ - You can enable it with `--features runtime-benchmarks`." - .into()) - } - } - #[cfg(feature = "try-runtime")] - Some(Subcommand::TryRuntime(cmd)) => { - // grab the task manager. - let runner = cli.create_runner(cmd)?; - let registry = &runner - .config() - .prometheus_config - .as_ref() - .map(|cfg| &cfg.registry); - let task_manager = - sc_service::TaskManager::new(runner.config().tokio_handle.clone(), *registry) - .map_err(|e| format!("Error: {:?}", e))?; - - if runner.config().chain_spec.is_manta() { - runner.async_run(|config| { - Ok((cmd.run::(config), task_manager)) - }) - } else if runner.config().chain_spec.is_calamari() { - runner.async_run(|config| { - Ok(( - cmd.run::(config), - task_manager, - )) - }) - } else { - Err("Chain doesn't support try-runtime".into()) - } - } - #[cfg(not(feature = "try-runtime"))] - Some(Subcommand::TryRuntime) => Err("Try-runtime wasn't enabled when building the node. \ - You can enable it with `--features try-runtime`." - .into()), - None => { - let runner = cli.create_runner(&cli.run.normalize())?; - let collator_options = cli.run.collator_options(); - - runner.run_node_until_exit(|config| async move { - let para_id = crate::chain_specs::Extensions::try_get(&*config.chain_spec) - .map(|e| e.para_id) - .ok_or("Could not find parachain extension in chain-spec.")?; - - let polkadot_cli = RelayChainCli::new( - &config, - [RelayChainCli::executable_name()] - .iter() - .chain(cli.relaychain_args.iter()), - ); - - let id = ParaId::from(para_id); - - let parachain_account = - AccountIdConversion::::into_account(&id); - - let state_version = - RelayChainCli::native_runtime_version(&config.chain_spec).state_version(); - - let block: crate::service::Block = - generate_genesis_block(&config.chain_spec, state_version) - .map_err(|e| format!("{:?}", e))?; - let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode())); - - let tokio_handle = config.tokio_handle.clone(); - let polkadot_config = - SubstrateCli::create_configuration(&polkadot_cli, &polkadot_cli, tokio_handle) - .map_err(|err| format!("Relay chain argument error: {}", err))?; - - info!("Parachain id: {:?}", id); - info!("Parachain Account: {}", parachain_account); - info!("Parachain genesis state: {}", genesis_state); - info!( - "Is collating: {}", - if config.role.is_authority() { - "yes" - } else { - "no" - } - ); - - if config.chain_spec.is_manta() { - crate::service::start_parachain_node::< - manta_runtime::RuntimeApi, - MantaRuntimeExecutor, - AuraId, - _, - >(config, polkadot_config, collator_options, id, |c, p| { - Box::new(Builder::new(c, p)) - }) - .await - .map(|r| r.0) - .map_err(Into::into) - } else if config.chain_spec.is_calamari() { - crate::service::start_parachain_node::< - calamari_runtime::RuntimeApi, - CalamariRuntimeExecutor, - AuraId, - _, - >(config, polkadot_config, collator_options, id, |c, p| { - Box::new(Builder::new(c, p)) - }) - .await - .map(|r| r.0) - .map_err(Into::into) - } else if config.chain_spec.is_dolphin() { - crate::service::start_parachain_node::< - dolphin_runtime::RuntimeApi, - DolphinRuntimeExecutor, - AuraId, - _, - >(config, polkadot_config, collator_options, id, |c, p| { - Box::new(Builder::<_, _, rpc::Dolphin>::new(c, p)) - }) - .await - .map(|r| r.0) - .map_err(Into::into) - } else { - Err("chain spec error: must be one of manta or calamari chain specs".into()) - } - }) - } - } + match &cli.subcommand { + Some(Subcommand::BuildSpec(cmd)) => { + let runner = cli.create_runner(cmd)?; + runner.sync_run(|config| cmd.run(config.chain_spec, config.network)) + } + Some(Subcommand::CheckBlock(cmd)) => { + construct_async_run!(|components, cli, cmd, config| { + Ok(cmd.run(components.client, components.import_queue)) + }) + } + Some(Subcommand::ExportBlocks(cmd)) => { + construct_async_run!(|components, cli, cmd, config| { + Ok(cmd.run(components.client, config.database)) + }) + } + Some(Subcommand::ExportState(cmd)) => { + construct_async_run!(|components, cli, cmd, config| { + Ok(cmd.run(components.client, config.chain_spec)) + }) + } + Some(Subcommand::ImportBlocks(cmd)) => { + construct_async_run!(|components, cli, cmd, config| { + Ok(cmd.run(components.client, components.import_queue)) + }) + } + Some(Subcommand::PurgeChain(cmd)) => { + let runner = cli.create_runner(cmd)?; + + runner.sync_run(|config| { + let polkadot_cli = RelayChainCli::new( + &config, + [RelayChainCli::executable_name()] + .iter() + .chain(cli.relaychain_args.iter()), + ); + + let polkadot_config = SubstrateCli::create_configuration( + &polkadot_cli, + &polkadot_cli, + config.tokio_handle.clone(), + ) + .map_err(|err| format!("Relay chain argument error: {}", err))?; + + cmd.run(config, polkadot_config) + }) + } + Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| { + Ok(cmd.run(components.client, components.backend)) + }), + Some(Subcommand::ExportGenesisState(params)) => { + let mut builder = sc_cli::LoggerBuilder::new(""); + builder.with_profiling(sc_tracing::TracingReceiver::Log, ""); + let _ = builder.init(); + + let spec = load_spec(¶ms.chain.clone().unwrap_or_default())?; + let state_version = Cli::native_runtime_version(&spec).state_version(); + + let block: crate::service::Block = generate_genesis_block(&spec, state_version)?; + let raw_header = block.header().encode(); + let output_buf = if params.raw { + raw_header + } else { + format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes() + }; + + if let Some(output) = ¶ms.output { + std::fs::write(output, output_buf)?; + } else { + std::io::stdout().write_all(&output_buf)?; + } + + Ok(()) + } + Some(Subcommand::ExportGenesisWasm(params)) => { + let mut builder = sc_cli::LoggerBuilder::new(""); + builder.with_profiling(sc_tracing::TracingReceiver::Log, ""); + let _ = builder.init(); + + let raw_wasm_blob = + extract_genesis_wasm(&cli.load_spec(¶ms.chain.clone().unwrap_or_default())?)?; + let output_buf = if params.raw { + raw_wasm_blob + } else { + format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes() + }; + + if let Some(output) = ¶ms.output { + std::fs::write(output, output_buf)?; + } else { + std::io::stdout().write_all(&output_buf)?; + } + + Ok(()) + } + Some(Subcommand::Benchmark(cmd)) => { + let runner = cli.create_runner(cmd)?; + if runner.config().chain_spec.is_manta() { + runner.sync_run(|config| cmd.run::(config)) + } else if runner.config().chain_spec.is_calamari() { + runner.sync_run(|config| cmd.run::(config)) + } else if runner.config().chain_spec.is_dolphin() { + runner.sync_run(|config| cmd.run::(config)) + } else { + Err("Benchmarking wasn't enabled when building the node. \ + You can enable it with `--features runtime-benchmarks`." + .into()) + } + } + #[cfg(feature = "try-runtime")] + Some(Subcommand::TryRuntime(cmd)) => { + // grab the task manager. + let runner = cli.create_runner(cmd)?; + let registry = &runner + .config() + .prometheus_config + .as_ref() + .map(|cfg| &cfg.registry); + let task_manager = + sc_service::TaskManager::new(runner.config().tokio_handle.clone(), *registry) + .map_err(|e| format!("Error: {:?}", e))?; + + if runner.config().chain_spec.is_manta() { + runner.async_run(|config| { + Ok((cmd.run::(config), task_manager)) + }) + } else if runner.config().chain_spec.is_calamari() { + runner.async_run(|config| { + Ok(( + cmd.run::(config), + task_manager, + )) + }) + } else { + Err("Chain doesn't support try-runtime".into()) + } + } + #[cfg(not(feature = "try-runtime"))] + Some(Subcommand::TryRuntime) => Err("Try-runtime wasn't enabled when building the node. \ + You can enable it with `--features try-runtime`." + .into()), + None => { + let runner = cli.create_runner(&cli.run.normalize())?; + let collator_options = cli.run.collator_options(); + + runner.run_node_until_exit(|config| async move { + let para_id = crate::chain_specs::Extensions::try_get(&*config.chain_spec) + .map(|e| e.para_id) + .ok_or("Could not find parachain extension in chain-spec.")?; + + let polkadot_cli = RelayChainCli::new( + &config, + [RelayChainCli::executable_name()] + .iter() + .chain(cli.relaychain_args.iter()), + ); + + let id = ParaId::from(para_id); + + let parachain_account = + AccountIdConversion::::into_account(&id); + + let state_version = + RelayChainCli::native_runtime_version(&config.chain_spec).state_version(); + + let block: crate::service::Block = + generate_genesis_block(&config.chain_spec, state_version) + .map_err(|e| format!("{:?}", e))?; + let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode())); + + let tokio_handle = config.tokio_handle.clone(); + let polkadot_config = + SubstrateCli::create_configuration(&polkadot_cli, &polkadot_cli, tokio_handle) + .map_err(|err| format!("Relay chain argument error: {}", err))?; + + info!("Parachain id: {:?}", id); + info!("Parachain Account: {}", parachain_account); + info!("Parachain genesis state: {}", genesis_state); + info!( + "Is collating: {}", + if config.role.is_authority() { + "yes" + } else { + "no" + } + ); + + if config.chain_spec.is_manta() { + crate::service::start_parachain_node::< + manta_runtime::RuntimeApi, + MantaRuntimeExecutor, + AuraId, + _, + >(config, polkadot_config, collator_options, id, |c, p| { + Box::new(Builder::new(c, p)) + }) + .await + .map(|r| r.0) + .map_err(Into::into) + } else if config.chain_spec.is_calamari() { + crate::service::start_parachain_node::< + calamari_runtime::RuntimeApi, + CalamariRuntimeExecutor, + AuraId, + _, + >(config, polkadot_config, collator_options, id, |c, p| { + Box::new(Builder::new(c, p)) + }) + .await + .map(|r| r.0) + .map_err(Into::into) + } else if config.chain_spec.is_dolphin() { + crate::service::start_parachain_node::< + dolphin_runtime::RuntimeApi, + DolphinRuntimeExecutor, + AuraId, + _, + >(config, polkadot_config, collator_options, id, |c, p| { + Box::new(Builder::<_, _, rpc::Dolphin>::new(c, p)) + }) + .await + .map(|r| r.0) + .map_err(Into::into) + } else { + Err("chain spec error: must be one of manta or calamari chain specs".into()) + } + }) + } + } } /// Parse command line arguments into service configuration. pub fn run() -> Result<()> { - run_with(Cli::from_args()) + run_with(Cli::from_args()) } impl DefaultConfigurationValues for RelayChainCli { - fn p2p_listen_port() -> u16 { - 30334 - } + fn p2p_listen_port() -> u16 { + 30334 + } - fn rpc_ws_listen_port() -> u16 { - 9945 - } + fn rpc_ws_listen_port() -> u16 { + 9945 + } - fn rpc_http_listen_port() -> u16 { - 9934 - } + fn rpc_http_listen_port() -> u16 { + 9934 + } - fn prometheus_listen_port() -> u16 { - 9616 - } + fn prometheus_listen_port() -> u16 { + 9616 + } } impl CliConfiguration for RelayChainCli { - fn shared_params(&self) -> &SharedParams { - self.base.base.shared_params() - } - - fn import_params(&self) -> Option<&ImportParams> { - self.base.base.import_params() - } - - fn network_params(&self) -> Option<&NetworkParams> { - self.base.base.network_params() - } - - fn keystore_params(&self) -> Option<&KeystoreParams> { - self.base.base.keystore_params() - } - - fn base_path(&self) -> Result> { - Ok(self - .shared_params() - .base_path() - .or_else(|| self.base_path.clone().map(Into::into))) - } - - fn rpc_http(&self, default_listen_port: u16) -> Result> { - self.base.base.rpc_http(default_listen_port) - } - - fn rpc_ipc(&self) -> Result> { - self.base.base.rpc_ipc() - } - - fn rpc_ws(&self, default_listen_port: u16) -> Result> { - self.base.base.rpc_ws(default_listen_port) - } - - fn prometheus_config( - &self, - default_listen_port: u16, - chain_spec: &Box, - ) -> Result> { - self.base - .base - .prometheus_config(default_listen_port, chain_spec) - } - - fn init( - &self, - _support_url: &String, - _impl_version: &String, - _logger_hook: F, - _config: &sc_service::Configuration, - ) -> Result<()> - where - F: FnOnce(&mut sc_cli::LoggerBuilder, &sc_service::Configuration), - { - unreachable!("PolkadotCli is never initialized; qed"); - } - - fn chain_id(&self, is_dev: bool) -> Result { - let chain_id = self.base.base.chain_id(is_dev)?; - - Ok(if chain_id.is_empty() { - self.chain_id.clone().unwrap_or_default() - } else { - chain_id - }) - } - - fn role(&self, is_dev: bool) -> Result { - self.base.base.role(is_dev) - } - - fn transaction_pool(&self) -> Result { - self.base.base.transaction_pool() - } - - fn state_cache_child_ratio(&self) -> Result> { - self.base.base.state_cache_child_ratio() - } - - fn rpc_methods(&self) -> Result { - self.base.base.rpc_methods() - } - - fn rpc_ws_max_connections(&self) -> Result> { - self.base.base.rpc_ws_max_connections() - } - - fn rpc_cors(&self, is_dev: bool) -> Result>> { - self.base.base.rpc_cors(is_dev) - } - - fn default_heap_pages(&self) -> Result> { - self.base.base.default_heap_pages() - } - - fn force_authoring(&self) -> Result { - self.base.base.force_authoring() - } - - fn disable_grandpa(&self) -> Result { - self.base.base.disable_grandpa() - } - - fn max_runtime_instances(&self) -> Result> { - self.base.base.max_runtime_instances() - } - - fn announce_block(&self) -> Result { - self.base.base.announce_block() - } - - fn telemetry_endpoints( - &self, - chain_spec: &Box, - ) -> Result> { - self.base.base.telemetry_endpoints(chain_spec) - } + fn shared_params(&self) -> &SharedParams { + self.base.base.shared_params() + } + + fn import_params(&self) -> Option<&ImportParams> { + self.base.base.import_params() + } + + fn network_params(&self) -> Option<&NetworkParams> { + self.base.base.network_params() + } + + fn keystore_params(&self) -> Option<&KeystoreParams> { + self.base.base.keystore_params() + } + + fn base_path(&self) -> Result> { + Ok(self + .shared_params() + .base_path() + .or_else(|| self.base_path.clone().map(Into::into))) + } + + fn rpc_http(&self, default_listen_port: u16) -> Result> { + self.base.base.rpc_http(default_listen_port) + } + + fn rpc_ipc(&self) -> Result> { + self.base.base.rpc_ipc() + } + + fn rpc_ws(&self, default_listen_port: u16) -> Result> { + self.base.base.rpc_ws(default_listen_port) + } + + fn prometheus_config( + &self, + default_listen_port: u16, + chain_spec: &Box, + ) -> Result> { + self.base + .base + .prometheus_config(default_listen_port, chain_spec) + } + + fn init( + &self, + _support_url: &String, + _impl_version: &String, + _logger_hook: F, + _config: &sc_service::Configuration, + ) -> Result<()> + where + F: FnOnce(&mut sc_cli::LoggerBuilder, &sc_service::Configuration), + { + unreachable!("PolkadotCli is never initialized; qed"); + } + + fn chain_id(&self, is_dev: bool) -> Result { + let chain_id = self.base.base.chain_id(is_dev)?; + + Ok(if chain_id.is_empty() { + self.chain_id.clone().unwrap_or_default() + } else { + chain_id + }) + } + + fn role(&self, is_dev: bool) -> Result { + self.base.base.role(is_dev) + } + + fn transaction_pool(&self) -> Result { + self.base.base.transaction_pool() + } + + fn state_cache_child_ratio(&self) -> Result> { + self.base.base.state_cache_child_ratio() + } + + fn rpc_methods(&self) -> Result { + self.base.base.rpc_methods() + } + + fn rpc_ws_max_connections(&self) -> Result> { + self.base.base.rpc_ws_max_connections() + } + + fn rpc_cors(&self, is_dev: bool) -> Result>> { + self.base.base.rpc_cors(is_dev) + } + + fn default_heap_pages(&self) -> Result> { + self.base.base.default_heap_pages() + } + + fn force_authoring(&self) -> Result { + self.base.base.force_authoring() + } + + fn disable_grandpa(&self) -> Result { + self.base.base.disable_grandpa() + } + + fn max_runtime_instances(&self) -> Result> { + self.base.base.max_runtime_instances() + } + + fn announce_block(&self) -> Result { + self.base.base.announce_block() + } + + fn telemetry_endpoints( + &self, + chain_spec: &Box, + ) -> Result> { + self.base.base.telemetry_endpoints(chain_spec) + } } diff --git a/node/src/main.rs b/node/src/main.rs index 8485e00b2..ad6b2a517 100644 --- a/node/src/main.rs +++ b/node/src/main.rs @@ -27,5 +27,5 @@ mod rpc; mod service; fn main() -> sc_cli::Result<()> { - command::run() + command::run() } diff --git a/node/src/rpc/common.rs b/node/src/rpc/common.rs index ff27c5e05..2af22cbc8 100644 --- a/node/src/rpc/common.rs +++ b/node/src/rpc/common.rs @@ -20,7 +20,7 @@ use crate::rpc::{Builder, RpcExtension}; use frame_rpc_system::{AccountNonceApi, FullSystem, SystemApi}; use manta_primitives::types::{AccountId, Balance, Block, Index as Nonce}; use pallet_transaction_payment_rpc::{ - TransactionPayment, TransactionPaymentApi, TransactionPaymentRuntimeApi, + TransactionPayment, TransactionPaymentApi, TransactionPaymentRuntimeApi, }; use sc_client_api::HeaderBackend; use sc_rpc::{DenyUnsafe, SubscriptionTaskExecutor}; @@ -34,21 +34,21 @@ pub struct Common; impl RpcExtensionBuilder for Builder where - C: 'static + ProvideRuntimeApi + HeaderBackend, - C::Api: BlockBuilder - + AccountNonceApi - + TransactionPaymentRuntimeApi, - P: 'static + TransactionPool, + C: 'static + ProvideRuntimeApi + HeaderBackend, + C::Api: BlockBuilder + + AccountNonceApi + + TransactionPaymentRuntimeApi, + P: 'static + TransactionPool, { - type Output = RpcExtension; + type Output = RpcExtension; - #[inline] - fn build(&self, deny: DenyUnsafe, _: SubscriptionTaskExecutor) -> Result { - let mut io = RpcExtension::default(); - io.extend_with( - FullSystem::new(self.client.clone(), self.transaction_pool.clone(), deny).to_delegate(), - ); - io.extend_with(TransactionPayment::new(self.client.clone()).to_delegate()); - Ok(io) - } + #[inline] + fn build(&self, deny: DenyUnsafe, _: SubscriptionTaskExecutor) -> Result { + let mut io = RpcExtension::default(); + io.extend_with( + FullSystem::new(self.client.clone(), self.transaction_pool.clone(), deny).to_delegate(), + ); + io.extend_with(TransactionPayment::new(self.client.clone()).to_delegate()); + Ok(io) + } } diff --git a/node/src/rpc/dolphin.rs b/node/src/rpc/dolphin.rs index 49813a030..e05641c82 100644 --- a/node/src/rpc/dolphin.rs +++ b/node/src/rpc/dolphin.rs @@ -20,8 +20,8 @@ use crate::rpc::{common::Common, Builder, RpcExtension}; use frame_rpc_system::AccountNonceApi; use manta_primitives::types::{AccountId, Balance, Block, Index as Nonce}; use pallet_manta_pay::{ - rpc::{Pull, PullApi}, - runtime::PullLedgerDiffApi, + rpc::{Pull, PullApi}, + runtime::PullLedgerDiffApi, }; use pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi; use sc_client_api::HeaderBackend; @@ -36,23 +36,23 @@ pub struct Dolphin; impl RpcExtensionBuilder for Builder where - C: 'static + ProvideRuntimeApi + HeaderBackend, - C::Api: BlockBuilder - + AccountNonceApi - + PullLedgerDiffApi - + TransactionPaymentRuntimeApi, - P: 'static + TransactionPool, + C: 'static + ProvideRuntimeApi + HeaderBackend, + C::Api: BlockBuilder + + AccountNonceApi + + PullLedgerDiffApi + + TransactionPaymentRuntimeApi, + P: 'static + TransactionPool, { - type Output = RpcExtension; + type Output = RpcExtension; - #[inline] - fn build( - &self, - deny: DenyUnsafe, - subscription_executor: SubscriptionTaskExecutor, - ) -> Result { - let mut io = self.using::().build(deny, subscription_executor)?; - io.extend_with(Pull::new(self.client.clone()).to_delegate()); - Ok(io) - } + #[inline] + fn build( + &self, + deny: DenyUnsafe, + subscription_executor: SubscriptionTaskExecutor, + ) -> Result { + let mut io = self.using::().build(deny, subscription_executor)?; + io.extend_with(Pull::new(self.client.clone()).to_delegate()); + Ok(io) + } } diff --git a/node/src/rpc/mod.rs b/node/src/rpc/mod.rs index b4aac119d..33f865cb0 100644 --- a/node/src/rpc/mod.rs +++ b/node/src/rpc/mod.rs @@ -30,30 +30,30 @@ pub type RpcExtension = jsonrpc_core::IoHandler; /// RPC Extension Builder pub struct Builder { - /// Client - client: Arc, + /// Client + client: Arc, - /// Transaction Poool - transaction_pool: Arc

, + /// Transaction Poool + transaction_pool: Arc

, - /// Runtime Marker - __: PhantomData, + /// Runtime Marker + __: PhantomData, } impl Builder { - /// Builds a new RPC Extension [`Builder`] from `client` and `transaction_pool`. - #[inline] - pub fn new(client: Arc, transaction_pool: Arc

) -> Self { - Self { - client, - transaction_pool, - __: PhantomData, - } - } - - /// Converts `self` into a [`Builder`] with the `T` marker. - #[inline] - pub fn using(&self) -> Builder { - Builder::new(self.client.clone(), self.transaction_pool.clone()) - } + /// Builds a new RPC Extension [`Builder`] from `client` and `transaction_pool`. + #[inline] + pub fn new(client: Arc, transaction_pool: Arc

) -> Self { + Self { + client, + transaction_pool, + __: PhantomData, + } + } + + /// Converts `self` into a [`Builder`] with the `T` marker. + #[inline] + pub fn using(&self) -> Builder { + Builder::new(self.client.clone(), self.transaction_pool.clone()) + } } diff --git a/node/src/service.rs b/node/src/service.rs index 08d8c43f2..cf9ea8bf0 100644 --- a/node/src/service.rs +++ b/node/src/service.rs @@ -20,16 +20,16 @@ use core::marker::PhantomData; use cumulus_client_cli::CollatorOptions; use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion}; use cumulus_client_consensus_common::{ - ParachainBlockImport, ParachainCandidate, ParachainConsensus, + ParachainBlockImport, ParachainCandidate, ParachainConsensus, }; use cumulus_client_consensus_relay_chain::Verifier as RelayChainVerifier; use cumulus_client_network::BlockAnnounceValidator; use cumulus_client_service::{ - prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams, + prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams, }; use cumulus_primitives_core::{ - relay_chain::v1::{Hash as PHash, PersistedValidationData}, - ParaId, + relay_chain::v1::{Hash as PHash, PersistedValidationData}, + ParaId, }; use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain; use cumulus_relay_chain_interface::{RelayChainError, RelayChainInterface, RelayChainResult}; @@ -41,8 +41,8 @@ pub use manta_primitives::types::{AccountId, Balance, Block, Hash, Header, Index use futures::lock::Mutex; use sc_client_api::ExecutorProvider; use sc_consensus::{ - import_queue::{BasicQueue, Verifier as VerifierT}, - BlockImportParams, + import_queue::{BasicQueue, Verifier as VerifierT}, + BlockImportParams, }; use sc_executor::NativeElseWasmExecutor; use sc_network::NetworkService; @@ -55,9 +55,9 @@ use sp_core::crypto::Pair; use sp_keystore::SyncCryptoStorePtr; use sp_offchain::OffchainWorkerApi; use sp_runtime::{ - app_crypto::AppKey, - generic::BlockId, - traits::{BlakeTwo256, Header as HeaderT}, + app_crypto::AppKey, + generic::BlockId, + traits::{BlakeTwo256, Header as HeaderT}, }; use sp_session::SessionKeys; use sp_transaction_pool::runtime_api::TaggedTransactionQueue; @@ -67,43 +67,43 @@ use substrate_prometheus_endpoint::Registry; /// Native Manta Parachain executor instance. pub struct MantaRuntimeExecutor; impl sc_executor::NativeExecutionDispatch for MantaRuntimeExecutor { - type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions; + type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions; - fn dispatch(method: &str, data: &[u8]) -> Option> { - manta_runtime::api::dispatch(method, data) - } + fn dispatch(method: &str, data: &[u8]) -> Option> { + manta_runtime::api::dispatch(method, data) + } - fn native_version() -> sc_executor::NativeVersion { - manta_runtime::native_version() - } + fn native_version() -> sc_executor::NativeVersion { + manta_runtime::native_version() + } } /// Native Calamari Parachain executor instance. pub struct CalamariRuntimeExecutor; impl sc_executor::NativeExecutionDispatch for CalamariRuntimeExecutor { - type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions; + type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions; - fn dispatch(method: &str, data: &[u8]) -> Option> { - calamari_runtime::api::dispatch(method, data) - } + fn dispatch(method: &str, data: &[u8]) -> Option> { + calamari_runtime::api::dispatch(method, data) + } - fn native_version() -> sc_executor::NativeVersion { - calamari_runtime::native_version() - } + fn native_version() -> sc_executor::NativeVersion { + calamari_runtime::native_version() + } } /// Native Dolphin Parachain executor instance. pub struct DolphinRuntimeExecutor; impl sc_executor::NativeExecutionDispatch for DolphinRuntimeExecutor { - type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions; + type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions; - fn dispatch(method: &str, data: &[u8]) -> Option> { - dolphin_runtime::api::dispatch(method, data) - } + fn dispatch(method: &str, data: &[u8]) -> Option> { + dolphin_runtime::api::dispatch(method, data) + } - fn native_version() -> sc_executor::NativeVersion { - dolphin_runtime::native_version() - } + fn native_version() -> sc_executor::NativeVersion { + dolphin_runtime::native_version() + } } /// Full Client Implementation Type @@ -117,12 +117,12 @@ pub type TransactionPool = sc_transaction_pool::FullPool = sc_service::PartialComponents< - Client, - TFullBackend, - (), - ImportQueue, - TransactionPool, - (Option, Option), + Client, + TFullBackend, + (), + ImportQueue, + TransactionPool, + (Option, Option), >; /// State Backend Type @@ -133,103 +133,103 @@ pub type StateBackend = sc_client_api::StateBackendFor, Bloc /// Use this macro if you don't actually need the full service, but just the builder in order to /// be able to perform chain operations. pub fn new_partial( - config: &Configuration, - build_import_queue: BIQ, + config: &Configuration, + build_import_queue: BIQ, ) -> Result, Error> where - RuntimeApi: ConstructRuntimeApi> + Send + Sync + 'static, - RuntimeApi::RuntimeApi: TaggedTransactionQueue - + sp_api::Metadata - + SessionKeys - + ApiExt - + OffchainWorkerApi - + sp_block_builder::BlockBuilder, - StateBackend: sp_api::StateBackend, - Executor: NativeExecutionDispatch + 'static, - BIQ: FnOnce( - Arc>, - &Configuration, - Option, - &TaskManager, - ) -> Result, Error>, + RuntimeApi: ConstructRuntimeApi> + Send + Sync + 'static, + RuntimeApi::RuntimeApi: TaggedTransactionQueue + + sp_api::Metadata + + SessionKeys + + ApiExt + + OffchainWorkerApi + + sp_block_builder::BlockBuilder, + StateBackend: sp_api::StateBackend, + Executor: NativeExecutionDispatch + 'static, + BIQ: FnOnce( + Arc>, + &Configuration, + Option, + &TaskManager, + ) -> Result, Error>, { - let telemetry = config - .telemetry_endpoints - .clone() - .filter(|x| !x.is_empty()) - .map(|endpoints| -> Result<_, sc_telemetry::Error> { - let worker = TelemetryWorker::new(16)?; - let telemetry = worker.handle().new_telemetry(endpoints); - Ok((worker, telemetry)) - }) - .transpose()?; - let executor = sc_executor::NativeElseWasmExecutor::::new( - config.wasm_method, - config.default_heap_pages, - config.max_runtime_instances, - config.runtime_cache_size, - ); - let (client, backend, keystore_container, task_manager) = - sc_service::new_full_parts::( - config, - telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()), - executor, - )?; - let client = Arc::new(client); - let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle()); - let telemetry = telemetry.map(|(worker, telemetry)| { - task_manager - .spawn_handle() - .spawn("telemetry", None, worker.run()); - telemetry - }); - let transaction_pool = sc_transaction_pool::BasicPool::new_full( - config.transaction_pool.clone(), - config.role.is_authority().into(), - config.prometheus_registry(), - task_manager.spawn_essential_handle(), - client.clone(), - ); - let import_queue = build_import_queue( - client.clone(), - config, - telemetry.as_ref().map(|telemetry| telemetry.handle()), - &task_manager, - )?; - Ok(PartialComponents { - backend, - client, - import_queue, - keystore_container, - task_manager, - transaction_pool, - select_chain: (), - other: (telemetry, telemetry_worker_handle), - }) + let telemetry = config + .telemetry_endpoints + .clone() + .filter(|x| !x.is_empty()) + .map(|endpoints| -> Result<_, sc_telemetry::Error> { + let worker = TelemetryWorker::new(16)?; + let telemetry = worker.handle().new_telemetry(endpoints); + Ok((worker, telemetry)) + }) + .transpose()?; + let executor = sc_executor::NativeElseWasmExecutor::::new( + config.wasm_method, + config.default_heap_pages, + config.max_runtime_instances, + config.runtime_cache_size, + ); + let (client, backend, keystore_container, task_manager) = + sc_service::new_full_parts::( + config, + telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()), + executor, + )?; + let client = Arc::new(client); + let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle()); + let telemetry = telemetry.map(|(worker, telemetry)| { + task_manager + .spawn_handle() + .spawn("telemetry", None, worker.run()); + telemetry + }); + let transaction_pool = sc_transaction_pool::BasicPool::new_full( + config.transaction_pool.clone(), + config.role.is_authority().into(), + config.prometheus_registry(), + task_manager.spawn_essential_handle(), + client.clone(), + ); + let import_queue = build_import_queue( + client.clone(), + config, + telemetry.as_ref().map(|telemetry| telemetry.handle()), + &task_manager, + )?; + Ok(PartialComponents { + backend, + client, + import_queue, + keystore_container, + task_manager, + transaction_pool, + select_chain: (), + other: (telemetry, telemetry_worker_handle), + }) } async fn build_relay_chain_interface( - polkadot_config: Configuration, - parachain_config: &Configuration, - telemetry_worker_handle: Option, - task_manager: &mut TaskManager, - collator_options: CollatorOptions, + polkadot_config: Configuration, + parachain_config: &Configuration, + telemetry_worker_handle: Option, + task_manager: &mut TaskManager, + collator_options: CollatorOptions, ) -> RelayChainResult<( - Arc<(dyn RelayChainInterface + 'static)>, - Option, + Arc<(dyn RelayChainInterface + 'static)>, + Option, )> { - match collator_options.relay_chain_rpc_url { - Some(relay_chain_url) => Ok(( - Arc::new(RelayChainRPCInterface::new(relay_chain_url).await?) as Arc<_>, - None, - )), - None => build_inprocess_relay_chain( - polkadot_config, - parachain_config, - telemetry_worker_handle, - task_manager, - ), - } + match collator_options.relay_chain_rpc_url { + Some(relay_chain_url) => Ok(( + Arc::new(RelayChainRPCInterface::new(relay_chain_url).await?) as Arc<_>, + None, + )), + None => build_inprocess_relay_chain( + polkadot_config, + parachain_config, + telemetry_worker_handle, + task_manager, + ), + } } /// Start a node with the given parachain `Configuration` and relay chain `Configuration`. @@ -237,517 +237,519 @@ async fn build_relay_chain_interface( /// This is the actual implementation that is abstract over the executor and the runtime api. #[sc_tracing::logging::prefix_logs_with("Parachain")] async fn start_node_impl( - parachain_config: Configuration, - polkadot_config: Configuration, - collator_options: CollatorOptions, - id: ParaId, - rpc_extensions_builder: RB, - build_import_queue: BIQ, - build_consensus: BIC, + parachain_config: Configuration, + polkadot_config: Configuration, + collator_options: CollatorOptions, + id: ParaId, + rpc_extensions_builder: RB, + build_import_queue: BIQ, + build_consensus: BIC, ) -> Result<(TaskManager, Arc>), Error> where - RuntimeApi: ConstructRuntimeApi> + Send + Sync + 'static, - RuntimeApi::RuntimeApi: TaggedTransactionQueue - + sp_api::Metadata - + SessionKeys - + ApiExt - + OffchainWorkerApi - + sp_block_builder::BlockBuilder - + cumulus_primitives_core::CollectCollationInfo - + pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi - + frame_rpc_system::AccountNonceApi, - StateBackend: sp_api::StateBackend, - Executor: sc_executor::NativeExecutionDispatch + 'static, - RB: Fn( - Arc>, - Arc>, - ) -> Box< - (dyn sc_service::RpcExtensionBuilder + Send + 'static), - >, - BIQ: FnOnce( - Arc>, - &Configuration, - Option, - &TaskManager, - ) -> Result, Error> - + 'static, - BIC: FnOnce( - Arc>, - Option<&Registry>, - Option, - &TaskManager, - Arc, - Arc>, - Arc>, - SyncCryptoStorePtr, - bool, - ) -> Result>, Error>, + RuntimeApi: ConstructRuntimeApi> + Send + Sync + 'static, + RuntimeApi::RuntimeApi: TaggedTransactionQueue + + sp_api::Metadata + + SessionKeys + + ApiExt + + OffchainWorkerApi + + sp_block_builder::BlockBuilder + + cumulus_primitives_core::CollectCollationInfo + + pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi + + frame_rpc_system::AccountNonceApi, + StateBackend: sp_api::StateBackend, + Executor: sc_executor::NativeExecutionDispatch + 'static, + RB: Fn( + Arc>, + Arc>, + ) -> Box< + (dyn sc_service::RpcExtensionBuilder + Send + 'static), + >, + BIQ: FnOnce( + Arc>, + &Configuration, + Option, + &TaskManager, + ) -> Result, Error> + + 'static, + BIC: FnOnce( + Arc>, + Option<&Registry>, + Option, + &TaskManager, + Arc, + Arc>, + Arc>, + SyncCryptoStorePtr, + bool, + ) -> Result>, Error>, { - if matches!(parachain_config.role, Role::Light) { - return Err("Light client not supported!".into()); - } - - let parachain_config = prepare_node_config(parachain_config); - - let params = new_partial::(¶chain_config, build_import_queue)?; - let (mut telemetry, telemetry_worker_handle) = params.other; - - let mut task_manager = params.task_manager; - let (relay_chain_interface, collator_key) = build_relay_chain_interface( - polkadot_config, - ¶chain_config, - telemetry_worker_handle, - &mut task_manager, - collator_options.clone(), - ) - .await - .map_err(|e| match e { - RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x, - s => s.to_string().into(), - })?; - - let client = params.client.clone(); - let backend = params.backend.clone(); - let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id); - - let force_authoring = parachain_config.force_authoring; - let validator = parachain_config.role.is_authority(); - let prometheus_registry = parachain_config.prometheus_registry().cloned(); - let transaction_pool = params.transaction_pool.clone(); - let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue); - let (network, system_rpc_tx, start_network) = - sc_service::build_network(sc_service::BuildNetworkParams { - config: ¶chain_config, - client: client.clone(), - transaction_pool: transaction_pool.clone(), - spawn_handle: task_manager.spawn_handle(), - import_queue: import_queue.clone(), - block_announce_validator_builder: Some(Box::new(|_| { - Box::new(block_announce_validator) - })), - warp_sync: None, - })?; - - sc_service::spawn_tasks(sc_service::SpawnTasksParams { - rpc_extensions_builder: rpc_extensions_builder(client.clone(), transaction_pool.clone()), - client: client.clone(), - transaction_pool: transaction_pool.clone(), - task_manager: &mut task_manager, - config: parachain_config, - keystore: params.keystore_container.sync_keystore(), - backend: backend.clone(), - network: network.clone(), - system_rpc_tx, - telemetry: telemetry.as_mut(), - })?; - - let announce_block = { - let network = network.clone(); - Arc::new(move |hash, data| network.announce_block(hash, data)) - }; - - let relay_chain_slot_duration = core::time::Duration::from_secs(6); - if validator { - let parachain_consensus = build_consensus( - client.clone(), - prometheus_registry.as_ref(), - telemetry.as_ref().map(|t| t.handle()), - &task_manager, - relay_chain_interface.clone(), - transaction_pool, - network, - params.keystore_container.sync_keystore(), - force_authoring, - )?; - let spawner = task_manager.spawn_handle(); - start_collator(StartCollatorParams { - para_id: id, - block_status: client.clone(), - announce_block, - client: client.clone(), - task_manager: &mut task_manager, - relay_chain_interface, - spawner, - parachain_consensus, - import_queue, - collator_key: collator_key.expect("Command line arguments do not allow this. qed"), - relay_chain_slot_duration, - }) - .await?; - } else { - start_full_node(StartFullNodeParams { - client: client.clone(), - announce_block, - task_manager: &mut task_manager, - para_id: id, - relay_chain_interface, - relay_chain_slot_duration, - import_queue, - collator_options, - })?; - } - - start_network.start_network(); - Ok((task_manager, client)) + if matches!(parachain_config.role, Role::Light) { + return Err("Light client not supported!".into()); + } + + let parachain_config = prepare_node_config(parachain_config); + + let params = new_partial::(¶chain_config, build_import_queue)?; + let (mut telemetry, telemetry_worker_handle) = params.other; + + let mut task_manager = params.task_manager; + let (relay_chain_interface, collator_key) = build_relay_chain_interface( + polkadot_config, + ¶chain_config, + telemetry_worker_handle, + &mut task_manager, + collator_options.clone(), + ) + .await + .map_err(|e| match e { + RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x, + s => s.to_string().into(), + })?; + + let client = params.client.clone(); + let backend = params.backend.clone(); + let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id); + + let force_authoring = parachain_config.force_authoring; + let validator = parachain_config.role.is_authority(); + let prometheus_registry = parachain_config.prometheus_registry().cloned(); + let transaction_pool = params.transaction_pool.clone(); + let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue); + let (network, system_rpc_tx, start_network) = + sc_service::build_network(sc_service::BuildNetworkParams { + config: ¶chain_config, + client: client.clone(), + transaction_pool: transaction_pool.clone(), + spawn_handle: task_manager.spawn_handle(), + import_queue: import_queue.clone(), + block_announce_validator_builder: Some(Box::new(|_| { + Box::new(block_announce_validator) + })), + warp_sync: None, + })?; + + sc_service::spawn_tasks(sc_service::SpawnTasksParams { + rpc_extensions_builder: rpc_extensions_builder(client.clone(), transaction_pool.clone()), + client: client.clone(), + transaction_pool: transaction_pool.clone(), + task_manager: &mut task_manager, + config: parachain_config, + keystore: params.keystore_container.sync_keystore(), + backend: backend.clone(), + network: network.clone(), + system_rpc_tx, + telemetry: telemetry.as_mut(), + })?; + + let announce_block = { + let network = network.clone(); + Arc::new(move |hash, data| network.announce_block(hash, data)) + }; + + let relay_chain_slot_duration = core::time::Duration::from_secs(6); + if validator { + let parachain_consensus = build_consensus( + client.clone(), + prometheus_registry.as_ref(), + telemetry.as_ref().map(|t| t.handle()), + &task_manager, + relay_chain_interface.clone(), + transaction_pool, + network, + params.keystore_container.sync_keystore(), + force_authoring, + )?; + let spawner = task_manager.spawn_handle(); + start_collator(StartCollatorParams { + para_id: id, + block_status: client.clone(), + announce_block, + client: client.clone(), + task_manager: &mut task_manager, + relay_chain_interface, + spawner, + parachain_consensus, + import_queue, + collator_key: collator_key.expect("Command line arguments do not allow this. qed"), + relay_chain_slot_duration, + }) + .await?; + } else { + start_full_node(StartFullNodeParams { + client: client.clone(), + announce_block, + task_manager: &mut task_manager, + para_id: id, + relay_chain_interface, + relay_chain_slot_duration, + import_queue, + collator_options, + })?; + } + + start_network.start_network(); + Ok((task_manager, client)) } enum BuildOnAccess { - Uninitialized(Option R + Send + Sync>>), - Initialized(R), + Uninitialized(Option R + Send + Sync>>), + Initialized(R), } impl BuildOnAccess { - fn get_mut(&mut self) -> &mut R { - loop { - match self { - Self::Uninitialized(f) => { - *self = Self::Initialized((f.take().unwrap())()); - } - Self::Initialized(ref mut r) => return r, - } - } - } + fn get_mut(&mut self) -> &mut R { + loop { + match self { + Self::Uninitialized(f) => { + *self = Self::Initialized((f.take().unwrap())()); + } + Self::Initialized(ref mut r) => return r, + } + } + } } /// Special [`ParachainConsensus`] implementation that waits for the upgrade from /// shell to a parachain runtime that implements Aura. struct WaitForAuraConsensus { - client: Arc, - aura_consensus: Arc>>>>, - relay_chain_consensus: Arc>>>, - _phantom: PhantomData, + client: Arc, + aura_consensus: Arc>>>>, + relay_chain_consensus: Arc>>>, + _phantom: PhantomData, } impl Clone for WaitForAuraConsensus { - fn clone(&self) -> Self { - Self { - client: self.client.clone(), - aura_consensus: self.aura_consensus.clone(), - relay_chain_consensus: self.relay_chain_consensus.clone(), - _phantom: PhantomData, - } - } + fn clone(&self) -> Self { + Self { + client: self.client.clone(), + aura_consensus: self.aura_consensus.clone(), + relay_chain_consensus: self.relay_chain_consensus.clone(), + _phantom: PhantomData, + } + } } #[async_trait::async_trait] impl ParachainConsensus for WaitForAuraConsensus where - Client: sp_api::ProvideRuntimeApi + Send + Sync, - Client::Api: AuraApi, - AuraId: Send + Codec + Sync, + Client: sp_api::ProvideRuntimeApi + Send + Sync, + Client::Api: AuraApi, + AuraId: Send + Codec + Sync, { - async fn produce_candidate( - &mut self, - parent: &Header, - relay_parent: PHash, - validation_data: &PersistedValidationData, - ) -> Option> { - let block_id = BlockId::hash(parent.hash()); - if self - .client - .runtime_api() - .has_api::>(&block_id) - .unwrap_or(false) - { - self.aura_consensus - .lock() - .await - .get_mut() - .produce_candidate(parent, relay_parent, validation_data) - .await - } else { - self.relay_chain_consensus - .lock() - .await - .produce_candidate(parent, relay_parent, validation_data) - .await - } - } + async fn produce_candidate( + &mut self, + parent: &Header, + relay_parent: PHash, + validation_data: &PersistedValidationData, + ) -> Option> { + let block_id = BlockId::hash(parent.hash()); + if self + .client + .runtime_api() + .has_api::>(&block_id) + .unwrap_or(false) + { + self.aura_consensus + .lock() + .await + .get_mut() + .produce_candidate(parent, relay_parent, validation_data) + .await + } else { + self.relay_chain_consensus + .lock() + .await + .produce_candidate(parent, relay_parent, validation_data) + .await + } + } } struct Verifier { - client: Arc, - aura_verifier: BuildOnAccess>>, - relay_chain_verifier: Box>, - _phantom: PhantomData, + client: Arc, + aura_verifier: BuildOnAccess>>, + relay_chain_verifier: Box>, + _phantom: PhantomData, } #[async_trait::async_trait] impl VerifierT for Verifier where - Client: sp_api::ProvideRuntimeApi + Send + Sync, - Client::Api: AuraApi, - AuraId: Send + Sync + Codec, + Client: sp_api::ProvideRuntimeApi + Send + Sync, + Client::Api: AuraApi, + AuraId: Send + Sync + Codec, { - async fn verify( - &mut self, - block_import: BlockImportParams, - ) -> Result< - ( - BlockImportParams, - Option)>>, - ), - String, - > { - let block_id = BlockId::hash(*block_import.header.parent_hash()); - - if self - .client - .runtime_api() - .has_api::>(&block_id) - .unwrap_or(false) - { - self.aura_verifier.get_mut().verify(block_import).await - } else { - self.relay_chain_verifier.verify(block_import).await - } - } + async fn verify( + &mut self, + block_import: BlockImportParams, + ) -> Result< + ( + BlockImportParams, + Option)>>, + ), + String, + > { + let block_id = BlockId::hash(*block_import.header.parent_hash()); + + if self + .client + .runtime_api() + .has_api::>(&block_id) + .unwrap_or(false) + { + self.aura_verifier.get_mut().verify(block_import).await + } else { + self.relay_chain_verifier.verify(block_import).await + } + } } /// Build the import queue for the calamari/manta runtime. pub fn parachain_build_import_queue( - client: Arc>, - config: &Configuration, - telemetry_handle: Option, - task_manager: &TaskManager, + client: Arc>, + config: &Configuration, + telemetry_handle: Option, + task_manager: &TaskManager, ) -> Result, Error> where - RuntimeApi: ConstructRuntimeApi> + Send + Sync + 'static, - RuntimeApi::RuntimeApi: TaggedTransactionQueue - + sp_api::Metadata - + SessionKeys - + ApiExt - + OffchainWorkerApi - + sp_block_builder::BlockBuilder - + sp_consensus_aura::AuraApi::Pair as Pair>::Public>, - StateBackend: sp_api::StateBackend, - Executor: sc_executor::NativeExecutionDispatch + 'static, - <::Pair as Pair>::Signature: - TryFrom> + std::hash::Hash + sp_runtime::traits::Member + Codec, + RuntimeApi: ConstructRuntimeApi> + Send + Sync + 'static, + RuntimeApi::RuntimeApi: TaggedTransactionQueue + + sp_api::Metadata + + SessionKeys + + ApiExt + + OffchainWorkerApi + + sp_block_builder::BlockBuilder + + sp_consensus_aura::AuraApi::Pair as Pair>::Public>, + StateBackend: sp_api::StateBackend, + Executor: sc_executor::NativeExecutionDispatch + 'static, + <::Pair as Pair>::Signature: + TryFrom> + std::hash::Hash + sp_runtime::traits::Member + Codec, { - let client2 = client.clone(); - - let aura_verifier = move || { - let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client2).unwrap(); - Box::new(cumulus_client_consensus_aura::build_verifier::< - ::Pair, - _, - _, - _, - >(cumulus_client_consensus_aura::BuildVerifierParams { - client: client2.clone(), - create_inherent_data_providers: move |_, _| async move { - let time = sp_timestamp::InherentDataProvider::from_system_time(); - - let slot = - sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration( - *time, - slot_duration, - ); - - Ok((time, slot)) - }, - can_author_with: sp_consensus::CanAuthorWithNativeVersion::new( - client2.executor().clone(), - ), - telemetry: telemetry_handle, - })) as Box<_> - }; - - let relay_chain_verifier = Box::new(RelayChainVerifier::new(client.clone(), |_, _| async { - Ok(()) - })); - - let verifier = Verifier { - client: client.clone(), - relay_chain_verifier, - aura_verifier: BuildOnAccess::Uninitialized(Some(Box::new(aura_verifier))), - _phantom: PhantomData, - }; - - let registry = config.prometheus_registry(); - let spawner = task_manager.spawn_essential_handle(); - - Ok(BasicQueue::new( - verifier, - Box::new(ParachainBlockImport::new(client)), - None, - &spawner, - registry, - )) + let client2 = client.clone(); + + let aura_verifier = move || { + let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client2).unwrap(); + Box::new(cumulus_client_consensus_aura::build_verifier::< + ::Pair, + _, + _, + _, + >( + cumulus_client_consensus_aura::BuildVerifierParams { + client: client2.clone(), + create_inherent_data_providers: move |_, _| async move { + let time = sp_timestamp::InherentDataProvider::from_system_time(); + + let slot = + sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration( + *time, + slot_duration, + ); + + Ok((time, slot)) + }, + can_author_with: sp_consensus::CanAuthorWithNativeVersion::new( + client2.executor().clone(), + ), + telemetry: telemetry_handle, + }, + )) as Box<_> + }; + + let relay_chain_verifier = Box::new(RelayChainVerifier::new(client.clone(), |_, _| async { + Ok(()) + })); + + let verifier = Verifier { + client: client.clone(), + relay_chain_verifier, + aura_verifier: BuildOnAccess::Uninitialized(Some(Box::new(aura_verifier))), + _phantom: PhantomData, + }; + + let registry = config.prometheus_registry(); + let spawner = task_manager.spawn_essential_handle(); + + Ok(BasicQueue::new( + verifier, + Box::new(ParachainBlockImport::new(client)), + None, + &spawner, + registry, + )) } /// Start a calamari/manta parachain node. pub async fn start_parachain_node( - parachain_config: Configuration, - polkadot_config: Configuration, - collator_options: CollatorOptions, - id: ParaId, - rpc: RPC, + parachain_config: Configuration, + polkadot_config: Configuration, + collator_options: CollatorOptions, + id: ParaId, + rpc: RPC, ) -> Result<(TaskManager, Arc>), Error> where - RuntimeApi: ConstructRuntimeApi> + Send + Sync + 'static, - RuntimeApi::RuntimeApi: TaggedTransactionQueue - + sp_api::Metadata - + SessionKeys - + ApiExt - + OffchainWorkerApi - + sp_block_builder::BlockBuilder - + cumulus_primitives_core::CollectCollationInfo - + sp_consensus_aura::AuraApi::Pair as Pair>::Public> - + pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi - + frame_rpc_system::AccountNonceApi, - StateBackend: sp_api::StateBackend, - Executor: sc_executor::NativeExecutionDispatch + 'static, - <::Pair as Pair>::Signature: - TryFrom> + std::hash::Hash + sp_runtime::traits::Member + Codec, - RPC: Fn( - Arc>, - Arc>, - ) -> Box< - (dyn sc_service::RpcExtensionBuilder + Send + 'static), - >, + RuntimeApi: ConstructRuntimeApi> + Send + Sync + 'static, + RuntimeApi::RuntimeApi: TaggedTransactionQueue + + sp_api::Metadata + + SessionKeys + + ApiExt + + OffchainWorkerApi + + sp_block_builder::BlockBuilder + + cumulus_primitives_core::CollectCollationInfo + + sp_consensus_aura::AuraApi::Pair as Pair>::Public> + + pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi + + frame_rpc_system::AccountNonceApi, + StateBackend: sp_api::StateBackend, + Executor: sc_executor::NativeExecutionDispatch + 'static, + <::Pair as Pair>::Signature: + TryFrom> + std::hash::Hash + sp_runtime::traits::Member + Codec, + RPC: Fn( + Arc>, + Arc>, + ) -> Box< + (dyn sc_service::RpcExtensionBuilder + Send + 'static), + >, { - start_node_impl::( - parachain_config, - polkadot_config, - collator_options, - id, - rpc, - parachain_build_import_queue::<_, _, AuraId>, - |client, - prometheus_registry, - telemetry, - task_manager, - relay_chain_interface, - transaction_pool, - sync_oracle, - keystore, - force_authoring| { - let client2 = client.clone(); - let spawn_handle = task_manager.spawn_handle(); - let transaction_pool2 = transaction_pool.clone(); - let telemetry2 = telemetry.clone(); - let prometheus_registry2 = prometheus_registry.map(|r| (*r).clone()); - let relay_chain_for_aura = relay_chain_interface.clone(); - - let aura_consensus = BuildOnAccess::Uninitialized(Some(Box::new(move || { - let slot_duration = - cumulus_client_consensus_aura::slot_duration(&*client2).unwrap(); - - let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording( - spawn_handle, - client2.clone(), - transaction_pool2, - prometheus_registry2.as_ref(), - telemetry2.clone(), - ); - - AuraConsensus::build::<::Pair, _, _, _, _, _, _>( - BuildAuraConsensusParams { - proposer_factory, - create_inherent_data_providers: - move |_, (relay_parent, validation_data)| { - let relay_chain_for_aura = relay_chain_for_aura.clone(); - async move { - let parachain_inherent = - cumulus_primitives_parachain_inherent::ParachainInherentData::create_at( - relay_parent, - &relay_chain_for_aura, - &validation_data, - id, - ).await; - let time = - sp_timestamp::InherentDataProvider::from_system_time(); - - let slot = - sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration( - *time, - slot_duration, - ); - - let parachain_inherent = - parachain_inherent.ok_or_else(|| { - Box::::from( - "Failed to create parachain inherent", - ) - })?; - Ok((time, slot, parachain_inherent)) - } - }, - block_import: client2.clone(), - para_client: client2.clone(), - backoff_authoring_blocks: Option::<()>::None, - sync_oracle, - keystore, - force_authoring, - slot_duration, - // We got around 500ms for proposing - block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32), - // And a maximum of 750ms if slots are skipped - max_block_proposal_slot_portion: Some(SlotProportion::new(1f32 / 16f32)), - telemetry: telemetry2, - }, - ) - }))); - - let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?; - let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording( - task_manager.spawn_handle(), - client.clone(), - transaction_pool, - prometheus_registry, - telemetry, - ); - - let relay_chain_consensus = - cumulus_client_consensus_relay_chain::build_relay_chain_consensus( - cumulus_client_consensus_relay_chain::BuildRelayChainConsensusParams { - para_id: id, - proposer_factory, - block_import: client.clone(), - relay_chain_interface: relay_chain_interface.clone(), - create_inherent_data_providers: - move |_, (relay_parent, validation_data)| { - let relay_chain_interface = relay_chain_interface.clone(); - async move { - let parachain_inherent = - cumulus_primitives_parachain_inherent::ParachainInherentData::create_at( - relay_parent, - &relay_chain_interface, - &validation_data, - id, - ).await; - let time = - sp_timestamp::InherentDataProvider::from_system_time(); - - let slot = - sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration( - *time, - slot_duration, - ); - - let parachain_inherent = - parachain_inherent.ok_or_else(|| { - Box::::from( - "Failed to create parachain inherent", - ) - })?; - Ok((time, slot, parachain_inherent)) - } - }, - }, - ); - - let parachain_consensus = Box::new(WaitForAuraConsensus { - client, - aura_consensus: Arc::new(Mutex::new(aura_consensus)), - relay_chain_consensus: Arc::new(Mutex::new(relay_chain_consensus)), - _phantom: PhantomData, - }); - - Ok(parachain_consensus) - }, - ) - .await + start_node_impl::( + parachain_config, + polkadot_config, + collator_options, + id, + rpc, + parachain_build_import_queue::<_, _, AuraId>, + |client, + prometheus_registry, + telemetry, + task_manager, + relay_chain_interface, + transaction_pool, + sync_oracle, + keystore, + force_authoring| { + let client2 = client.clone(); + let spawn_handle = task_manager.spawn_handle(); + let transaction_pool2 = transaction_pool.clone(); + let telemetry2 = telemetry.clone(); + let prometheus_registry2 = prometheus_registry.map(|r| (*r).clone()); + let relay_chain_for_aura = relay_chain_interface.clone(); + + let aura_consensus = BuildOnAccess::Uninitialized(Some(Box::new(move || { + let slot_duration = + cumulus_client_consensus_aura::slot_duration(&*client2).unwrap(); + + let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording( + spawn_handle, + client2.clone(), + transaction_pool2, + prometheus_registry2.as_ref(), + telemetry2.clone(), + ); + + AuraConsensus::build::<::Pair, _, _, _, _, _, _>( + BuildAuraConsensusParams { + proposer_factory, + create_inherent_data_providers: + move |_, (relay_parent, validation_data)| { + let relay_chain_for_aura = relay_chain_for_aura.clone(); + async move { + let parachain_inherent = + cumulus_primitives_parachain_inherent::ParachainInherentData::create_at( + relay_parent, + &relay_chain_for_aura, + &validation_data, + id, + ).await; + let time = + sp_timestamp::InherentDataProvider::from_system_time(); + + let slot = + sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration( + *time, + slot_duration, + ); + + let parachain_inherent = + parachain_inherent.ok_or_else(|| { + Box::::from( + "Failed to create parachain inherent", + ) + })?; + Ok((time, slot, parachain_inherent)) + } + }, + block_import: client2.clone(), + para_client: client2.clone(), + backoff_authoring_blocks: Option::<()>::None, + sync_oracle, + keystore, + force_authoring, + slot_duration, + // We got around 500ms for proposing + block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32), + // And a maximum of 750ms if slots are skipped + max_block_proposal_slot_portion: Some(SlotProportion::new(1f32 / 16f32)), + telemetry: telemetry2, + }, + ) + }))); + + let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?; + let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording( + task_manager.spawn_handle(), + client.clone(), + transaction_pool, + prometheus_registry, + telemetry, + ); + + let relay_chain_consensus = + cumulus_client_consensus_relay_chain::build_relay_chain_consensus( + cumulus_client_consensus_relay_chain::BuildRelayChainConsensusParams { + para_id: id, + proposer_factory, + block_import: client.clone(), + relay_chain_interface: relay_chain_interface.clone(), + create_inherent_data_providers: + move |_, (relay_parent, validation_data)| { + let relay_chain_interface = relay_chain_interface.clone(); + async move { + let parachain_inherent = + cumulus_primitives_parachain_inherent::ParachainInherentData::create_at( + relay_parent, + &relay_chain_interface, + &validation_data, + id, + ).await; + let time = + sp_timestamp::InherentDataProvider::from_system_time(); + + let slot = + sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration( + *time, + slot_duration, + ); + + let parachain_inherent = + parachain_inherent.ok_or_else(|| { + Box::::from( + "Failed to create parachain inherent", + ) + })?; + Ok((time, slot, parachain_inherent)) + } + }, + }, + ); + + let parachain_consensus = Box::new(WaitForAuraConsensus { + client, + aura_consensus: Arc::new(Mutex::new(aura_consensus)), + relay_chain_consensus: Arc::new(Mutex::new(relay_chain_consensus)), + _phantom: PhantomData, + }); + + Ok(parachain_consensus) + }, + ) + .await } diff --git a/pallets/asset-manager/Cargo.toml b/pallets/asset-manager/Cargo.toml index e4fcf923f..e709e1bc3 100644 --- a/pallets/asset-manager/Cargo.toml +++ b/pallets/asset-manager/Cargo.toml @@ -1,53 +1,53 @@ [package] -authors = ['Manta Network'] -name = "pallet-asset-manager" -version = "3.2.0" +authors = ['Manta Network'] edition = "2021" -homepage = 'https://manta.network' -license = 'GPL-3.0' +homepage = 'https://manta.network' +license = 'GPL-3.0' +name = "pallet-asset-manager" repository = 'https://github.com/Manta-Network/Manta/' +version = "3.2.0" [dependencies] codec = { package = "parity-scale-codec", version = '3.0.0', default-features = false } -scale-info = { version = "2.0.0", default-features = false, features = ["derive"] } -sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18", default-features = false } +frame-benchmarking = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18", default-features = false, optional = true } frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18", default-features = false } frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18", default-features = false } +log = { version = "0.4.0", default-features = false } +manta-primitives = { path = "../../primitives", default-features = false } +scale-info = { version = "2.0.0", default-features = false, features = ["derive"] } +sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18", default-features = false } sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18", default-features = false } -frame-benchmarking = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18", default-features = false, optional = true } xcm = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } -manta-primitives = { path = "../../primitives", default-features = false } -log = { version = "0.4.0", default-features = false } # 3rd party dependencies -orml-traits = { git = "https://github.com/manta-network/open-runtime-module-library.git", default-features = false, rev="7e2f985" } +orml-traits = { git = "https://github.com/manta-network/open-runtime-module-library.git", default-features = false, rev = "7e2f985" } [dev-dependencies] -sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18" } -pallet-balances = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } pallet-assets = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } +pallet-balances = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18" } +sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18" } [features] default = ["std"] +runtime-benchmarks = [ + 'frame-benchmarking', + 'frame-support/runtime-benchmarks', + 'frame-system/runtime-benchmarks', + 'manta-primitives/runtime-benchmarks', +] std = [ - "codec/std", - "scale-info/std", - "sp-runtime/std", - "frame-support/std", - "frame-system/std", - "sp-std/std", - "manta-primitives/std", - "orml-traits/std", - 'log/std', - 'xcm/std', + "codec/std", + "scale-info/std", + "sp-runtime/std", + "frame-support/std", + "frame-system/std", + "sp-std/std", + "manta-primitives/std", + "orml-traits/std", + 'log/std', + 'xcm/std', ] try-runtime = [ - "frame-support/try-runtime", -] -runtime-benchmarks = [ - 'frame-benchmarking', - 'frame-support/runtime-benchmarks', - 'frame-system/runtime-benchmarks', - 'manta-primitives/runtime-benchmarks', + "frame-support/try-runtime", ] diff --git a/pallets/asset-manager/src/benchmarking.rs b/pallets/asset-manager/src/benchmarking.rs index 266102d8a..0d6b73bc7 100644 --- a/pallets/asset-manager/src/benchmarking.rs +++ b/pallets/asset-manager/src/benchmarking.rs @@ -25,123 +25,123 @@ use xcm::latest::prelude::*; use manta_primitives::assets::{AssetConfig, UnitsToWeightRatio}; fn assert_last_event(generic_event: ::Event) { - let events = frame_system::Pallet::::events(); - let system_event: ::Event = generic_event.into(); - // compare to the last event record - let EventRecord { event, .. } = &events[events.len() - 1]; - assert_eq!(event, &system_event); + let events = frame_system::Pallet::::events(); + let system_event: ::Event = generic_event.into(); + // compare to the last event record + let EventRecord { event, .. } = &events[events.len() - 1]; + assert_eq!(event, &system_event); } benchmarks! { - where_clause { where >::AssetLocation: From } - - register_asset { - let location = >::AssetLocation::default(); - let metadata = >::AssetRegistrarMetadata::default(); - }: _(RawOrigin::Root, location.clone(), metadata) - verify { - assert_eq!(Pallet::::asset_id_location(>::StartNonNativeAssetId::get()), Some(location)); - } - - set_units_per_second { - let start = >::StartNonNativeAssetId::get(); - let end = start + 1000; - for i in start..end { - let location: MultiLocation = MultiLocation::new(0, X1(Parachain(i))); - let location = >::AssetLocation::from(location.clone()); - let metadata = >::AssetRegistrarMetadata::default(); - Pallet::::register_asset(RawOrigin::Root.into(), location.clone(), metadata.clone())?; - Pallet::::set_units_per_second(RawOrigin::Root.into(), i, 0)?; - } - // does not really matter what we register, as long as it is different than the previous - let location = >::AssetLocation::default(); - let metadata = >::AssetRegistrarMetadata::default(); - let amount = 10; - Pallet::::register_asset(RawOrigin::Root.into(), location, metadata)?; - }: _(RawOrigin::Root, end, amount) - verify { - assert_eq!(Pallet::::get_units_per_second(end), Some(amount)); - } - - update_asset_location { - let start = >::StartNonNativeAssetId::get(); - let end = start + 1000; - for i in start..end { - let location: MultiLocation = MultiLocation::new(0, X1(Parachain(i))); - let location = >::AssetLocation::from(location.clone()); - let metadata = >::AssetRegistrarMetadata::default(); - Pallet::::register_asset(RawOrigin::Root.into(), location.clone(), metadata.clone())?; - } - // does not really matter what we register, as long as it is different than the previous - let location = >::AssetLocation::default(); - let metadata = >::AssetRegistrarMetadata::default(); - Pallet::::register_asset(RawOrigin::Root.into(), location, metadata)?; - let new_location = >::AssetLocation::from(MultiLocation::new(0, X1(Parachain(end)))); - }: _(RawOrigin::Root, end, new_location.clone()) - verify { - assert_eq!(Pallet::::asset_id_location(end), Some(new_location)); - } - - update_asset_metadata { - let start = >::StartNonNativeAssetId::get(); - let end = start + 1000; - for i in start..end { - let location: MultiLocation = MultiLocation::new(0, X1(Parachain(i))); - let location = >::AssetLocation::from(location.clone()); - let metadata = >::AssetRegistrarMetadata::default(); - Pallet::::register_asset(RawOrigin::Root.into(), location.clone(), metadata.clone())?; - } - // does not really matter what we register, as long as it is different than the previous - let location = >::AssetLocation::default(); - let metadata = >::AssetRegistrarMetadata::default(); - Pallet::::register_asset(RawOrigin::Root.into(), location, metadata.clone())?; - }: _(RawOrigin::Root, end, metadata.clone()) - verify { - assert_last_event::(Event::AssetMetadataUpdated { asset_id: end, metadata }.into()); - } - - mint_asset { - let start = >::StartNonNativeAssetId::get(); - let end = start + 1000; - for i in start..end { - let location = >::AssetLocation::from(MultiLocation::new(0, X1(Parachain(i)))); - let metadata = >::AssetRegistrarMetadata::default(); - Pallet::::register_asset(RawOrigin::Root.into(), location.clone(), metadata.clone())?; - } - let beneficiary: T::AccountId = whitelisted_caller(); - let amount = 100; - // does not really matter what we register, as long as it is different than the previous - let location = >::AssetLocation::default(); - let metadata = >::AssetRegistrarMetadata::default(); - Pallet::::register_asset(RawOrigin::Root.into(), location, metadata)?; - }: _(RawOrigin::Root, end, beneficiary.clone(), amount) - verify { - assert_last_event::(Event::AssetMinted { asset_id: end, beneficiary, amount }.into()); - } - - set_min_xcm_fee { - let start = >::StartNonNativeAssetId::get(); - let end = start + 1000; - for i in start..end { - - let location: MultiLocation = MultiLocation::new(0, X1(Parachain(i))); - let location = >::AssetLocation::from(location.clone()); - let metadata = >::AssetRegistrarMetadata::default(); - - Pallet::::register_asset(RawOrigin::Root.into(), location.clone(), metadata.clone())?; - Pallet::::set_units_per_second(RawOrigin::Root.into(), i, 0)?; - } - - // does not really matter what we register, as long as it is different than the previous - let location = >::AssetLocation::default(); - let metadata = >::AssetRegistrarMetadata::default(); - let min_xcm_fee = 10; - Pallet::::register_asset(RawOrigin::Root.into(), location.clone(), metadata.clone())?; - - }: _(RawOrigin::Root, location.clone(), min_xcm_fee) - verify { - assert_eq!(Pallet::::get_min_xcm_fee(location), Some(min_xcm_fee)); - } + where_clause { where >::AssetLocation: From } + + register_asset { + let location = >::AssetLocation::default(); + let metadata = >::AssetRegistrarMetadata::default(); + }: _(RawOrigin::Root, location.clone(), metadata) + verify { + assert_eq!(Pallet::::asset_id_location(>::StartNonNativeAssetId::get()), Some(location)); + } + + set_units_per_second { + let start = >::StartNonNativeAssetId::get(); + let end = start + 1000; + for i in start..end { + let location: MultiLocation = MultiLocation::new(0, X1(Parachain(i))); + let location = >::AssetLocation::from(location.clone()); + let metadata = >::AssetRegistrarMetadata::default(); + Pallet::::register_asset(RawOrigin::Root.into(), location.clone(), metadata.clone())?; + Pallet::::set_units_per_second(RawOrigin::Root.into(), i, 0)?; + } + // does not really matter what we register, as long as it is different than the previous + let location = >::AssetLocation::default(); + let metadata = >::AssetRegistrarMetadata::default(); + let amount = 10; + Pallet::::register_asset(RawOrigin::Root.into(), location, metadata)?; + }: _(RawOrigin::Root, end, amount) + verify { + assert_eq!(Pallet::::get_units_per_second(end), Some(amount)); + } + + update_asset_location { + let start = >::StartNonNativeAssetId::get(); + let end = start + 1000; + for i in start..end { + let location: MultiLocation = MultiLocation::new(0, X1(Parachain(i))); + let location = >::AssetLocation::from(location.clone()); + let metadata = >::AssetRegistrarMetadata::default(); + Pallet::::register_asset(RawOrigin::Root.into(), location.clone(), metadata.clone())?; + } + // does not really matter what we register, as long as it is different than the previous + let location = >::AssetLocation::default(); + let metadata = >::AssetRegistrarMetadata::default(); + Pallet::::register_asset(RawOrigin::Root.into(), location, metadata)?; + let new_location = >::AssetLocation::from(MultiLocation::new(0, X1(Parachain(end)))); + }: _(RawOrigin::Root, end, new_location.clone()) + verify { + assert_eq!(Pallet::::asset_id_location(end), Some(new_location)); + } + + update_asset_metadata { + let start = >::StartNonNativeAssetId::get(); + let end = start + 1000; + for i in start..end { + let location: MultiLocation = MultiLocation::new(0, X1(Parachain(i))); + let location = >::AssetLocation::from(location.clone()); + let metadata = >::AssetRegistrarMetadata::default(); + Pallet::::register_asset(RawOrigin::Root.into(), location.clone(), metadata.clone())?; + } + // does not really matter what we register, as long as it is different than the previous + let location = >::AssetLocation::default(); + let metadata = >::AssetRegistrarMetadata::default(); + Pallet::::register_asset(RawOrigin::Root.into(), location, metadata.clone())?; + }: _(RawOrigin::Root, end, metadata.clone()) + verify { + assert_last_event::(Event::AssetMetadataUpdated { asset_id: end, metadata }.into()); + } + + mint_asset { + let start = >::StartNonNativeAssetId::get(); + let end = start + 1000; + for i in start..end { + let location = >::AssetLocation::from(MultiLocation::new(0, X1(Parachain(i)))); + let metadata = >::AssetRegistrarMetadata::default(); + Pallet::::register_asset(RawOrigin::Root.into(), location.clone(), metadata.clone())?; + } + let beneficiary: T::AccountId = whitelisted_caller(); + let amount = 100; + // does not really matter what we register, as long as it is different than the previous + let location = >::AssetLocation::default(); + let metadata = >::AssetRegistrarMetadata::default(); + Pallet::::register_asset(RawOrigin::Root.into(), location, metadata)?; + }: _(RawOrigin::Root, end, beneficiary.clone(), amount) + verify { + assert_last_event::(Event::AssetMinted { asset_id: end, beneficiary, amount }.into()); + } + + set_min_xcm_fee { + let start = >::StartNonNativeAssetId::get(); + let end = start + 1000; + for i in start..end { + + let location: MultiLocation = MultiLocation::new(0, X1(Parachain(i))); + let location = >::AssetLocation::from(location.clone()); + let metadata = >::AssetRegistrarMetadata::default(); + + Pallet::::register_asset(RawOrigin::Root.into(), location.clone(), metadata.clone())?; + Pallet::::set_units_per_second(RawOrigin::Root.into(), i, 0)?; + } + + // does not really matter what we register, as long as it is different than the previous + let location = >::AssetLocation::default(); + let metadata = >::AssetRegistrarMetadata::default(); + let min_xcm_fee = 10; + Pallet::::register_asset(RawOrigin::Root.into(), location.clone(), metadata)?; + + }: _(RawOrigin::Root, location.clone(), min_xcm_fee) + verify { + assert_eq!(Pallet::::get_min_xcm_fee(location), Some(min_xcm_fee)); + } } impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::Runtime); diff --git a/pallets/asset-manager/src/lib.rs b/pallets/asset-manager/src/lib.rs index 7323280df..51282d032 100644 --- a/pallets/asset-manager/src/lib.rs +++ b/pallets/asset-manager/src/lib.rs @@ -43,608 +43,608 @@ mod tests; #[frame_support::pallet] pub mod pallet { - use crate::weights::WeightInfo; - use frame_support::{ - pallet_prelude::*, - traits::{Contains, StorageVersion}, - transactional, PalletId, - }; - use frame_system::pallet_prelude::*; - use manta_primitives::{ - assets::{ - AssetConfig, AssetIdLocationGetter, AssetMetadata, AssetRegistrar, FungibleLedger, - UnitsToWeightRatio, - }, - types::{AssetId, Balance}, - }; - use orml_traits::GetByKey; - use sp_runtime::{ - traits::{AccountIdConversion, One}, - ArithmeticError, - }; - use xcm::latest::prelude::*; - - /// Alias for the junction Parachain(#[codec(compact)] u32), - pub(crate) type ParaId = u32; - pub(crate) type AssetCount = u32; - - #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] - pub struct Pallet(_); - - /// Convert AssetId and AssetLocation - impl AssetIdLocationGetter<>::AssetLocation> - for Pallet - { - fn get_asset_id( - loc: &>::AssetLocation, - ) -> Option { - LocationAssetId::::get(loc) - } - - fn get_asset_location( - id: AssetId, - ) -> Option<>::AssetLocation> { - AssetIdLocation::::get(id) - } - } - - /// Get unit per second from `AssetId` - impl UnitsToWeightRatio for Pallet { - fn get_units_per_second(id: AssetId) -> Option { - UnitsPerSecond::::get(id) - } - } - - #[pallet::config] - pub trait Config: frame_system::Config { - /// The overarching event type. - type Event: From> + IsType<::Event>; - - /// Asset configuration, e.g. AssetId, Balance, Metadata - type AssetConfig: AssetConfig; - - /// The origin which may forcibly create or destroy an asset or otherwise alter privileged - /// attributes. - type ModifierOrigin: EnsureOrigin; - - /// Pallet ID - type PalletId: Get; - - /// Weight information for the extrinsics in this pallet. - type WeightInfo: crate::weights::WeightInfo; - } - - #[pallet::genesis_config] - pub struct GenesisConfig { - pub start_id: AssetId, - pub _marker: PhantomData, - } - - #[cfg(feature = "std")] - impl Default for GenesisConfig { - fn default() -> Self { - Self { - start_id: >::StartNonNativeAssetId::get(), - _marker: PhantomData, - } - } - } - - #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { - fn build(&self) { - NextAssetId::::set(self.start_id); - let asset_id = >::NativeAssetId::get(); - let metadata = >::NativeAssetMetadata::get(); - let location = >::NativeAssetLocation::get(); - AssetIdLocation::::insert(&asset_id, &location); - AssetIdMetadata::::insert(&asset_id, &metadata); - LocationAssetId::::insert(&location, &asset_id); - } - } - - #[pallet::event] - #[pallet::generate_deposit(pub(super) fn deposit_event)] - pub enum Event { - /// A new asset registered. - AssetRegistered { - asset_id: AssetId, - asset_address: >::AssetLocation, - metadata: >::AssetRegistrarMetadata, - }, - /// An asset's location has been updated. - AssetLocationUpdated { - asset_id: AssetId, - location: >::AssetLocation, - }, - /// An asset;s metadata has been updated. - AssetMetadataUpdated { - asset_id: AssetId, - metadata: >::AssetRegistrarMetadata, - }, - /// Update units per second of an asset - UnitsPerSecondUpdated { - asset_id: AssetId, - units_per_second: u128, - }, - /// Asset minted. - AssetMinted { - asset_id: AssetId, - beneficiary: T::AccountId, - amount: Balance, - }, - /// Update min xcm fee of an asset - MinXcmFeeUpdated { - reserve_chain: >::AssetLocation, - min_xcm_fee: u128, - }, - } - - /// Error. - #[pallet::error] - pub enum Error { - /// Location already exists. - LocationAlreadyExists, - /// Error creating asset, e.g. error returned from the implementation layer. - ErrorCreatingAsset, - /// Update a non-exist asset. - UpdateNonExistAsset, - /// Cannot update reserved assets metadata (0 and 1) - CannotUpdateNativeAssetMetadata, - /// Asset already registered. - AssetAlreadyRegistered, - /// Error on minting asset. - MintError, - /// Fail to update para id. - UpdateParaIdError, - } - - /// AssetId to MultiLocation Map. - /// This is mostly useful when sending an asset to a foreign location. - #[pallet::storage] - #[pallet::getter(fn asset_id_location)] - pub(super) type AssetIdLocation = - StorageMap<_, Blake2_128Concat, AssetId, >::AssetLocation>; - - /// MultiLocation to AssetId Map. - /// This is mostly useful when receiving an asset from a foreign location. - #[pallet::storage] - #[pallet::getter(fn location_asset_id)] - pub(super) type LocationAssetId = - StorageMap<_, Blake2_128Concat, >::AssetLocation, AssetId>; - - /// AssetId to AssetRegistrar Map. - #[pallet::storage] - #[pallet::getter(fn asset_id_metadata)] - pub(super) type AssetIdMetadata = StorageMap< - _, - Blake2_128Concat, - AssetId, - >::AssetRegistrarMetadata, - >; - - /// Get the next available AssetId. - #[pallet::storage] - #[pallet::getter(fn next_asset_id)] - pub type NextAssetId = StorageValue<_, AssetId, ValueQuery>; - - /// XCM transfer cost for different asset. - #[pallet::storage] - pub type UnitsPerSecond = StorageMap<_, Blake2_128Concat, AssetId, u128>; - - /// Minimum xcm execution fee paid on destination chain. - #[pallet::storage] - #[pallet::getter(fn get_min_xcm_fee)] - pub type MinXcmFee = - StorageMap<_, Blake2_128Concat, >::AssetLocation, u128>; - - /// The count of associated assets for each para id except relaychain. - #[pallet::storage] - #[pallet::getter(fn get_para_id)] - pub type AllowedDestParaIds = StorageMap<_, Blake2_128Concat, ParaId, AssetCount>; - - #[pallet::call] - impl Pallet { - /// Register a new asset in the asset manager. - /// - /// * `origin`: Caller of this extrinsic, the access control is specified by `ForceOrigin`. - /// * `location`: Location of the asset. - /// * `metadata`: Asset metadata. - /// * `min_balance`: Minimum balance to keep an account alive, used in conjunction with `is_sufficient`. - /// * `is_sufficient`: Whether this asset needs users to have an existential deposit to hold - /// this asset. - #[pallet::weight(T::WeightInfo::register_asset())] - #[transactional] - pub fn register_asset( - origin: OriginFor, - location: >::AssetLocation, - metadata: >::AssetRegistrarMetadata, - ) -> DispatchResult { - T::ModifierOrigin::ensure_origin(origin)?; - ensure!( - !LocationAssetId::::contains_key(&location), - Error::::LocationAlreadyExists - ); - let asset_id = Self::get_next_asset_id()?; - >::AssetRegistrar::create_asset( - asset_id, - metadata.min_balance(), - metadata.clone().into(), - metadata.is_sufficient(), - ) - .map_err(|_| Error::::ErrorCreatingAsset)?; - AssetIdLocation::::insert(&asset_id, &location); - AssetIdMetadata::::insert(&asset_id, &metadata); - LocationAssetId::::insert(&location, &asset_id); - - // If it's a new para id, which will be inserted with AssetCount as 1. - // If not, AssetCount will increased by 1. - if let Some(para_id) = - Self::get_para_id_from_multilocation(location.clone().into().as_ref()) - { - Self::increase_count_of_associated_assets(para_id)?; - } - - Self::deposit_event(Event::::AssetRegistered { - asset_id, - asset_address: location, - metadata, - }); - Ok(()) - } - - /// Update an asset by its asset id in the asset manager. - /// - /// * `origin`: Caller of this extrinsic, the access control is specified by `ForceOrigin`. - /// * `asset_id`: AssetId to be updated. - /// * `location`: `location` to update the asset location. - #[pallet::weight(T::WeightInfo::update_asset_location())] - #[transactional] - pub fn update_asset_location( - origin: OriginFor, - #[pallet::compact] asset_id: AssetId, - location: >::AssetLocation, - ) -> DispatchResult { - // checks validity - T::ModifierOrigin::ensure_origin(origin)?; - ensure!( - AssetIdLocation::::contains_key(&asset_id), - Error::::UpdateNonExistAsset - ); - ensure!( - !LocationAssetId::::contains_key(&location), - Error::::LocationAlreadyExists - ); - // change the ledger state. - let old_location = - AssetIdLocation::::get(&asset_id).ok_or(Error::::UpdateNonExistAsset)?; - LocationAssetId::::remove(&old_location); - LocationAssetId::::insert(&location, &asset_id); - AssetIdLocation::::insert(&asset_id, &location); - - // 1. If the new location has new para id, insert the new para id, - // the old para id will be deleted if AssetCount <= 1, or decreased by 1. - // 2. If the new location doesn't contain a new para id, do nothing to AssetCount - if let Some(old_para_id) = - Self::get_para_id_from_multilocation(old_location.into().as_ref()) - { - if AllowedDestParaIds::::get(old_para_id) <= Some(::one()) { - AllowedDestParaIds::::remove(old_para_id); - } else { - AllowedDestParaIds::::try_mutate(old_para_id, |cnt| -> DispatchResult { - let new_cnt = cnt - .map(|c| c - ::one()) - .ok_or(Error::::UpdateParaIdError)?; - *cnt = Some(new_cnt); - Ok(()) - })?; - } - } - - // If it's a new para id, which will be inserted with AssetCount as 1. - // If not, AssetCount will increased by 1. - if let Some(para_id) = - Self::get_para_id_from_multilocation(location.clone().into().as_ref()) - { - Self::increase_count_of_associated_assets(para_id)?; - } - - // deposit event. - Self::deposit_event(Event::::AssetLocationUpdated { asset_id, location }); - Ok(()) - } - - /// Update an asset's metadata by its `asset_id` - /// - /// * `origin`: Caller of this extrinsic, the access control is specified by `ForceOrigin`. - /// * `asset_id`: AssetId to be updated. - /// * `metadata`: new `metadata` to be associated with `asset_id`. - #[pallet::weight(T::WeightInfo::update_asset_metadata())] - #[transactional] - pub fn update_asset_metadata( - origin: OriginFor, - #[pallet::compact] asset_id: AssetId, - metadata: >::AssetRegistrarMetadata, - ) -> DispatchResult { - T::ModifierOrigin::ensure_origin(origin)?; - ensure!( - asset_id != >::NativeAssetId::get(), - Error::::CannotUpdateNativeAssetMetadata - ); - ensure!( - AssetIdLocation::::contains_key(&asset_id), - Error::::UpdateNonExistAsset - ); - >::AssetRegistrar::update_asset_metadata( - asset_id, - metadata.clone().into(), - )?; - AssetIdMetadata::::insert(&asset_id, &metadata); - Self::deposit_event(Event::::AssetMetadataUpdated { asset_id, metadata }); - Ok(()) - } - - /// Update an asset by its asset id in the asset manager. - /// - /// * `origin`: Caller of this extrinsic, the access control is specified by `ForceOrigin`. - /// * `asset_id`: AssetId to be updated. - /// * `units_per_second`: units per second for `asset_id` - #[pallet::weight(T::WeightInfo::set_units_per_second())] - #[transactional] - pub fn set_units_per_second( - origin: OriginFor, - #[pallet::compact] asset_id: AssetId, - #[pallet::compact] units_per_second: u128, - ) -> DispatchResult { - T::ModifierOrigin::ensure_origin(origin)?; - ensure!( - AssetIdLocation::::contains_key(&asset_id), - Error::::UpdateNonExistAsset - ); - UnitsPerSecond::::insert(&asset_id, &units_per_second); - Self::deposit_event(Event::::UnitsPerSecondUpdated { - asset_id, - units_per_second, - }); - Ok(()) - } - - /// Mint asset by its asset id to a beneficiary. - /// - /// * `origin`: Caller of this extrinsic, the access control is specified by `ForceOrigin`. - /// * `asset_id`: AssetId to be updated. - /// * `beneficiary`: Account to mint the asset. - /// * `amount`: Amount of asset being minted. - #[pallet::weight(T::WeightInfo::mint_asset())] - #[transactional] - pub fn mint_asset( - origin: OriginFor, - #[pallet::compact] asset_id: AssetId, - beneficiary: T::AccountId, - amount: Balance, - ) -> DispatchResult { - T::ModifierOrigin::ensure_origin(origin)?; - ensure!( - AssetIdLocation::::contains_key(&asset_id), - Error::::UpdateNonExistAsset - ); - ensure!( - >::FungibleLedger::mint( - asset_id, - &beneficiary, - amount - ) - .is_ok(), - Error::::MintError - ); - Self::deposit_event(Event::::AssetMinted { - asset_id, - beneficiary, - amount, - }); - Ok(()) - } - - /// Set min xcm fee for asset/s on their reserve chain. - /// - /// * `origin`: Caller of this extrinsic, the access control is specified by `ForceOrigin`. - /// * `reserve_chain`: Multilocation to be haven min xcm fee. - /// * `min_xcm_fee`: Amount of min_xcm_fee. - #[pallet::weight(T::WeightInfo::set_min_xcm_fee())] - #[transactional] - pub fn set_min_xcm_fee( - origin: OriginFor, - reserve_chain: >::AssetLocation, - #[pallet::compact] min_xcm_fee: u128, - ) -> DispatchResult { - T::ModifierOrigin::ensure_origin(origin)?; - MinXcmFee::::insert(&reserve_chain, &min_xcm_fee); - Self::deposit_event(Event::::MinXcmFeeUpdated { - reserve_chain, - min_xcm_fee, - }); - Ok(()) - } - } - - impl Pallet { - /// Get and increment the `NextAssetID` by one. - fn get_next_asset_id() -> Result { - NextAssetId::::try_mutate(|current| -> Result { - let id = *current; - *current = current.checked_add(1u32).ok_or(ArithmeticError::Overflow)?; - Ok(id) - }) - } - - /// The account ID of AssetManager - pub fn account_id() -> T::AccountId { - T::PalletId::get().into_account() - } - - /// Get para id from asset location - pub(crate) fn get_para_id_from_multilocation( - location: Option<&MultiLocation>, - ) -> Option { - if let Some(MultiLocation { interior, .. }) = location { - match interior { - Junctions::X1(Junction::Parachain(para_id)) - | Junctions::X2(Junction::Parachain(para_id), ..) - | Junctions::X3(Junction::Parachain(para_id), ..) - | Junctions::X4(Junction::Parachain(para_id), ..) - | Junctions::X5(Junction::Parachain(para_id), ..) - | Junctions::X6(Junction::Parachain(para_id), ..) - | Junctions::X7(Junction::Parachain(para_id), ..) - | Junctions::X8(Junction::Parachain(para_id), ..) => Some(*para_id), - _ => None, - } - } else { - None - } - } - - /// Increases the count of associated assets for the para id. - pub(crate) fn increase_count_of_associated_assets(para_id: ParaId) -> DispatchResult { - // If it's a new para id, which will be inserted with AssetCount as 1. - // If not, AssetCount will increased by 1. - if AllowedDestParaIds::::contains_key(para_id) { - AllowedDestParaIds::::try_mutate(para_id, |count| -> DispatchResult { - let new_count = count - .map(|c| c + ::one()) - .ok_or(Error::::UpdateParaIdError)?; - *count = Some(new_count); - Ok(()) - }) - } else { - AllowedDestParaIds::::insert(para_id, ::one()); - Ok(()) - } - } - } - - /// Check the multilocation is supported by calamari/manta. - impl Contains for Pallet { - fn contains(location: &MultiLocation) -> bool { - // check parents - if location.parents != 1 { - return false; - } - - match location.interior { - // Send tokens back to relaychain. - Junctions::X1(Junction::AccountId32 { .. }) => true, - // Send tokens to sibling chain. - Junctions::X2(Junction::Parachain(para_id), Junction::AccountId32 { .. }) - | Junctions::X2(Junction::Parachain(para_id), Junction::AccountKey20 { .. }) => { - AllowedDestParaIds::::contains_key(para_id) - } - // We don't support X3 or longer Junctions. - _ => false, - } - } - } - - /// Get min-xcm-fee by multilocation. - impl GetByKey for Pallet { - fn get(location: &MultiLocation) -> u128 { - let location = - >::AssetLocation::from(location.clone()); - match MinXcmFee::::get(&location) { - Some(min_fee) => min_fee, - None => u128::MAX, - } - } - } - - #[pallet::hooks] - impl Hooks> for Pallet { - fn on_runtime_upgrade() -> Weight { - // currently, it's 0 on calamari. - let storage_version = Self::on_chain_storage_version(); - if storage_version < 1 { - log::info!(target: "asset-manager", "Start to execute storage migration for asset-manager."); - - let mut reads: Weight = 0; - let mut writes: Weight = 0; - LocationAssetId::::iter().for_each(|(location, _asset_id)| { - reads += 1; - if let Some(para_id) = - Self::get_para_id_from_multilocation(location.into().as_ref()) - { - if para_id != 2084 { - let _ = Self::increase_count_of_associated_assets(para_id); - reads += 1; // There's one read in method increase_count_of_associated_assets. - writes += 1; // There's one write in method increase_count_of_associated_assets. - } - } - }); - - // Update storage version. - StorageVersion::new(1u16).put::(); - writes += 1; - - T::DbWeight::get() - .reads(reads) - .saturating_add(T::DbWeight::get().writes(writes)) - } else { - log::info!("✅ no migration for asset-manager."); - // only 1 read - T::DbWeight::get().reads(1) - } - } - - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result<(), &'static str> { - let storage_version = Self::on_chain_storage_version(); - - if storage_version >= 1 { - return Err("Storage version is >= 1, the migration won't be executed."); - } - - Ok(()) - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade() -> Result<(), &'static str> { - let storage_version = Self::on_chain_storage_version(); - - if storage_version < 1 { - return Err("Storage version is >= 1, the migration won't be executed."); - } - - let acala = (2000, 3); // karura has 3 asset locations on calamari. - let moonbeam = (2023, 1); // moonbean has 1 asset location on calamari. - let calamari = 2084; // our own asset location won't be counted. - if AllowedDestParaIds::::get(acala.0) == Some(acala.1) - && AllowedDestParaIds::::get(moonbeam.0) == Some(moonbeam.1) - && AllowedDestParaIds::::get(calamari).is_none() - { - log::info!( - "✅ Storage migration for asset-manager has been executed successfully." - ); - Ok(()) - } else { - return Err("Failed to executed storage migration for asset-manager."); - } - } - } - - #[cfg(feature = "std")] - impl GenesisConfig { - /// Direct implementation of `GenesisBuild::build_storage`. - /// - /// Kept in order not to break dependency. - pub fn build_storage(&self) -> Result { - >::build_storage(self) - } - - /// Direct implementation of `GenesisBuild::assimilate_storage`. - /// - /// Kept in order not to break dependency. - pub fn assimilate_storage(&self, storage: &mut sp_runtime::Storage) -> Result<(), String> { - >::assimilate_storage(self, storage) - } - } + use crate::weights::WeightInfo; + use frame_support::{ + pallet_prelude::*, + traits::{Contains, StorageVersion}, + transactional, PalletId, + }; + use frame_system::pallet_prelude::*; + use manta_primitives::{ + assets::{ + AssetConfig, AssetIdLocationGetter, AssetMetadata, AssetRegistrar, FungibleLedger, + UnitsToWeightRatio, + }, + types::{AssetId, Balance}, + }; + use orml_traits::GetByKey; + use sp_runtime::{ + traits::{AccountIdConversion, One}, + ArithmeticError, + }; + use xcm::latest::prelude::*; + + /// Alias for the junction Parachain(#[codec(compact)] u32), + pub(crate) type ParaId = u32; + pub(crate) type AssetCount = u32; + + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + #[pallet::without_storage_info] + pub struct Pallet(_); + + /// Convert AssetId and AssetLocation + impl AssetIdLocationGetter<>::AssetLocation> + for Pallet + { + fn get_asset_id( + loc: &>::AssetLocation, + ) -> Option { + LocationAssetId::::get(loc) + } + + fn get_asset_location( + id: AssetId, + ) -> Option<>::AssetLocation> { + AssetIdLocation::::get(id) + } + } + + /// Get unit per second from `AssetId` + impl UnitsToWeightRatio for Pallet { + fn get_units_per_second(id: AssetId) -> Option { + UnitsPerSecond::::get(id) + } + } + + #[pallet::config] + pub trait Config: frame_system::Config { + /// The overarching event type. + type Event: From> + IsType<::Event>; + + /// Asset configuration, e.g. AssetId, Balance, Metadata + type AssetConfig: AssetConfig; + + /// The origin which may forcibly create or destroy an asset or otherwise alter privileged + /// attributes. + type ModifierOrigin: EnsureOrigin; + + /// Pallet ID + type PalletId: Get; + + /// Weight information for the extrinsics in this pallet. + type WeightInfo: crate::weights::WeightInfo; + } + + #[pallet::genesis_config] + pub struct GenesisConfig { + pub start_id: AssetId, + pub _marker: PhantomData, + } + + #[cfg(feature = "std")] + impl Default for GenesisConfig { + fn default() -> Self { + Self { + start_id: >::StartNonNativeAssetId::get(), + _marker: PhantomData, + } + } + } + + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) { + NextAssetId::::set(self.start_id); + let asset_id = >::NativeAssetId::get(); + let metadata = >::NativeAssetMetadata::get(); + let location = >::NativeAssetLocation::get(); + AssetIdLocation::::insert(&asset_id, &location); + AssetIdMetadata::::insert(&asset_id, &metadata); + LocationAssetId::::insert(&location, &asset_id); + } + } + + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { + /// A new asset registered. + AssetRegistered { + asset_id: AssetId, + asset_address: >::AssetLocation, + metadata: >::AssetRegistrarMetadata, + }, + /// An asset's location has been updated. + AssetLocationUpdated { + asset_id: AssetId, + location: >::AssetLocation, + }, + /// An asset;s metadata has been updated. + AssetMetadataUpdated { + asset_id: AssetId, + metadata: >::AssetRegistrarMetadata, + }, + /// Update units per second of an asset + UnitsPerSecondUpdated { + asset_id: AssetId, + units_per_second: u128, + }, + /// Asset minted. + AssetMinted { + asset_id: AssetId, + beneficiary: T::AccountId, + amount: Balance, + }, + /// Update min xcm fee of an asset + MinXcmFeeUpdated { + reserve_chain: >::AssetLocation, + min_xcm_fee: u128, + }, + } + + /// Error. + #[pallet::error] + pub enum Error { + /// Location already exists. + LocationAlreadyExists, + /// Error creating asset, e.g. error returned from the implementation layer. + ErrorCreatingAsset, + /// Update a non-exist asset. + UpdateNonExistAsset, + /// Cannot update reserved assets metadata (0 and 1) + CannotUpdateNativeAssetMetadata, + /// Asset already registered. + AssetAlreadyRegistered, + /// Error on minting asset. + MintError, + /// Fail to update para id. + UpdateParaIdError, + } + + /// AssetId to MultiLocation Map. + /// This is mostly useful when sending an asset to a foreign location. + #[pallet::storage] + #[pallet::getter(fn asset_id_location)] + pub(super) type AssetIdLocation = + StorageMap<_, Blake2_128Concat, AssetId, >::AssetLocation>; + + /// MultiLocation to AssetId Map. + /// This is mostly useful when receiving an asset from a foreign location. + #[pallet::storage] + #[pallet::getter(fn location_asset_id)] + pub(super) type LocationAssetId = + StorageMap<_, Blake2_128Concat, >::AssetLocation, AssetId>; + + /// AssetId to AssetRegistrar Map. + #[pallet::storage] + #[pallet::getter(fn asset_id_metadata)] + pub(super) type AssetIdMetadata = StorageMap< + _, + Blake2_128Concat, + AssetId, + >::AssetRegistrarMetadata, + >; + + /// Get the next available AssetId. + #[pallet::storage] + #[pallet::getter(fn next_asset_id)] + pub type NextAssetId = StorageValue<_, AssetId, ValueQuery>; + + /// XCM transfer cost for different asset. + #[pallet::storage] + pub type UnitsPerSecond = StorageMap<_, Blake2_128Concat, AssetId, u128>; + + /// Minimum xcm execution fee paid on destination chain. + #[pallet::storage] + #[pallet::getter(fn get_min_xcm_fee)] + pub type MinXcmFee = + StorageMap<_, Blake2_128Concat, >::AssetLocation, u128>; + + /// The count of associated assets for each para id except relaychain. + #[pallet::storage] + #[pallet::getter(fn get_para_id)] + pub type AllowedDestParaIds = StorageMap<_, Blake2_128Concat, ParaId, AssetCount>; + + #[pallet::call] + impl Pallet { + /// Register a new asset in the asset manager. + /// + /// * `origin`: Caller of this extrinsic, the access control is specified by `ForceOrigin`. + /// * `location`: Location of the asset. + /// * `metadata`: Asset metadata. + /// * `min_balance`: Minimum balance to keep an account alive, used in conjunction with `is_sufficient`. + /// * `is_sufficient`: Whether this asset needs users to have an existential deposit to hold + /// this asset. + #[pallet::weight(T::WeightInfo::register_asset())] + #[transactional] + pub fn register_asset( + origin: OriginFor, + location: >::AssetLocation, + metadata: >::AssetRegistrarMetadata, + ) -> DispatchResult { + T::ModifierOrigin::ensure_origin(origin)?; + ensure!( + !LocationAssetId::::contains_key(&location), + Error::::LocationAlreadyExists + ); + let asset_id = Self::get_next_asset_id()?; + >::AssetRegistrar::create_asset( + asset_id, + metadata.min_balance(), + metadata.clone().into(), + metadata.is_sufficient(), + ) + .map_err(|_| Error::::ErrorCreatingAsset)?; + AssetIdLocation::::insert(&asset_id, &location); + AssetIdMetadata::::insert(&asset_id, &metadata); + LocationAssetId::::insert(&location, &asset_id); + + // If it's a new para id, which will be inserted with AssetCount as 1. + // If not, AssetCount will increased by 1. + if let Some(para_id) = + Self::get_para_id_from_multilocation(location.clone().into().as_ref()) + { + Self::increase_count_of_associated_assets(para_id)?; + } + + Self::deposit_event(Event::::AssetRegistered { + asset_id, + asset_address: location, + metadata, + }); + Ok(()) + } + + /// Update an asset by its asset id in the asset manager. + /// + /// * `origin`: Caller of this extrinsic, the access control is specified by `ForceOrigin`. + /// * `asset_id`: AssetId to be updated. + /// * `location`: `location` to update the asset location. + #[pallet::weight(T::WeightInfo::update_asset_location())] + #[transactional] + pub fn update_asset_location( + origin: OriginFor, + #[pallet::compact] asset_id: AssetId, + location: >::AssetLocation, + ) -> DispatchResult { + // checks validity + T::ModifierOrigin::ensure_origin(origin)?; + ensure!( + AssetIdLocation::::contains_key(&asset_id), + Error::::UpdateNonExistAsset + ); + ensure!( + !LocationAssetId::::contains_key(&location), + Error::::LocationAlreadyExists + ); + // change the ledger state. + let old_location = + AssetIdLocation::::get(&asset_id).ok_or(Error::::UpdateNonExistAsset)?; + LocationAssetId::::remove(&old_location); + LocationAssetId::::insert(&location, &asset_id); + AssetIdLocation::::insert(&asset_id, &location); + + // 1. If the new location has new para id, insert the new para id, + // the old para id will be deleted if AssetCount <= 1, or decreased by 1. + // 2. If the new location doesn't contain a new para id, do nothing to AssetCount + if let Some(old_para_id) = + Self::get_para_id_from_multilocation(old_location.into().as_ref()) + { + if AllowedDestParaIds::::get(old_para_id) <= Some(::one()) { + AllowedDestParaIds::::remove(old_para_id); + } else { + AllowedDestParaIds::::try_mutate(old_para_id, |cnt| -> DispatchResult { + let new_cnt = cnt + .map(|c| c - ::one()) + .ok_or(Error::::UpdateParaIdError)?; + *cnt = Some(new_cnt); + Ok(()) + })?; + } + } + + // If it's a new para id, which will be inserted with AssetCount as 1. + // If not, AssetCount will increased by 1. + if let Some(para_id) = + Self::get_para_id_from_multilocation(location.clone().into().as_ref()) + { + Self::increase_count_of_associated_assets(para_id)?; + } + + // deposit event. + Self::deposit_event(Event::::AssetLocationUpdated { asset_id, location }); + Ok(()) + } + + /// Update an asset's metadata by its `asset_id` + /// + /// * `origin`: Caller of this extrinsic, the access control is specified by `ForceOrigin`. + /// * `asset_id`: AssetId to be updated. + /// * `metadata`: new `metadata` to be associated with `asset_id`. + #[pallet::weight(T::WeightInfo::update_asset_metadata())] + #[transactional] + pub fn update_asset_metadata( + origin: OriginFor, + #[pallet::compact] asset_id: AssetId, + metadata: >::AssetRegistrarMetadata, + ) -> DispatchResult { + T::ModifierOrigin::ensure_origin(origin)?; + ensure!( + asset_id != >::NativeAssetId::get(), + Error::::CannotUpdateNativeAssetMetadata + ); + ensure!( + AssetIdLocation::::contains_key(&asset_id), + Error::::UpdateNonExistAsset + ); + >::AssetRegistrar::update_asset_metadata( + asset_id, + metadata.clone().into(), + )?; + AssetIdMetadata::::insert(&asset_id, &metadata); + Self::deposit_event(Event::::AssetMetadataUpdated { asset_id, metadata }); + Ok(()) + } + + /// Update an asset by its asset id in the asset manager. + /// + /// * `origin`: Caller of this extrinsic, the access control is specified by `ForceOrigin`. + /// * `asset_id`: AssetId to be updated. + /// * `units_per_second`: units per second for `asset_id` + #[pallet::weight(T::WeightInfo::set_units_per_second())] + #[transactional] + pub fn set_units_per_second( + origin: OriginFor, + #[pallet::compact] asset_id: AssetId, + #[pallet::compact] units_per_second: u128, + ) -> DispatchResult { + T::ModifierOrigin::ensure_origin(origin)?; + ensure!( + AssetIdLocation::::contains_key(&asset_id), + Error::::UpdateNonExistAsset + ); + UnitsPerSecond::::insert(&asset_id, &units_per_second); + Self::deposit_event(Event::::UnitsPerSecondUpdated { + asset_id, + units_per_second, + }); + Ok(()) + } + + /// Mint asset by its asset id to a beneficiary. + /// + /// * `origin`: Caller of this extrinsic, the access control is specified by `ForceOrigin`. + /// * `asset_id`: AssetId to be updated. + /// * `beneficiary`: Account to mint the asset. + /// * `amount`: Amount of asset being minted. + #[pallet::weight(T::WeightInfo::mint_asset())] + #[transactional] + pub fn mint_asset( + origin: OriginFor, + #[pallet::compact] asset_id: AssetId, + beneficiary: T::AccountId, + amount: Balance, + ) -> DispatchResult { + T::ModifierOrigin::ensure_origin(origin)?; + ensure!( + AssetIdLocation::::contains_key(&asset_id), + Error::::UpdateNonExistAsset + ); + ensure!( + >::FungibleLedger::mint( + asset_id, + &beneficiary, + amount + ) + .is_ok(), + Error::::MintError + ); + Self::deposit_event(Event::::AssetMinted { + asset_id, + beneficiary, + amount, + }); + Ok(()) + } + + /// Set min xcm fee for asset/s on their reserve chain. + /// + /// * `origin`: Caller of this extrinsic, the access control is specified by `ForceOrigin`. + /// * `reserve_chain`: Multilocation to be haven min xcm fee. + /// * `min_xcm_fee`: Amount of min_xcm_fee. + #[pallet::weight(T::WeightInfo::set_min_xcm_fee())] + #[transactional] + pub fn set_min_xcm_fee( + origin: OriginFor, + reserve_chain: >::AssetLocation, + #[pallet::compact] min_xcm_fee: u128, + ) -> DispatchResult { + T::ModifierOrigin::ensure_origin(origin)?; + MinXcmFee::::insert(&reserve_chain, &min_xcm_fee); + Self::deposit_event(Event::::MinXcmFeeUpdated { + reserve_chain, + min_xcm_fee, + }); + Ok(()) + } + } + + impl Pallet { + /// Get and increment the `NextAssetID` by one. + fn get_next_asset_id() -> Result { + NextAssetId::::try_mutate(|current| -> Result { + let id = *current; + *current = current.checked_add(1u32).ok_or(ArithmeticError::Overflow)?; + Ok(id) + }) + } + + /// The account ID of AssetManager + pub fn account_id() -> T::AccountId { + T::PalletId::get().into_account() + } + + /// Get para id from asset location + pub(crate) fn get_para_id_from_multilocation( + location: Option<&MultiLocation>, + ) -> Option { + if let Some(MultiLocation { interior, .. }) = location { + match interior { + Junctions::X1(Junction::Parachain(para_id)) + | Junctions::X2(Junction::Parachain(para_id), ..) + | Junctions::X3(Junction::Parachain(para_id), ..) + | Junctions::X4(Junction::Parachain(para_id), ..) + | Junctions::X5(Junction::Parachain(para_id), ..) + | Junctions::X6(Junction::Parachain(para_id), ..) + | Junctions::X7(Junction::Parachain(para_id), ..) + | Junctions::X8(Junction::Parachain(para_id), ..) => Some(*para_id), + _ => None, + } + } else { + None + } + } + + /// Increases the count of associated assets for the para id. + pub(crate) fn increase_count_of_associated_assets(para_id: ParaId) -> DispatchResult { + // If it's a new para id, which will be inserted with AssetCount as 1. + // If not, AssetCount will increased by 1. + if AllowedDestParaIds::::contains_key(para_id) { + AllowedDestParaIds::::try_mutate(para_id, |count| -> DispatchResult { + let new_count = count + .map(|c| c + ::one()) + .ok_or(Error::::UpdateParaIdError)?; + *count = Some(new_count); + Ok(()) + }) + } else { + AllowedDestParaIds::::insert(para_id, ::one()); + Ok(()) + } + } + } + + /// Check the multilocation is supported by calamari/manta. + impl Contains for Pallet { + fn contains(location: &MultiLocation) -> bool { + // check parents + if location.parents != 1 { + return false; + } + + match location.interior { + // Send tokens back to relaychain. + Junctions::X1(Junction::AccountId32 { .. }) => true, + // Send tokens to sibling chain. + Junctions::X2(Junction::Parachain(para_id), Junction::AccountId32 { .. }) + | Junctions::X2(Junction::Parachain(para_id), Junction::AccountKey20 { .. }) => { + AllowedDestParaIds::::contains_key(para_id) + } + // We don't support X3 or longer Junctions. + _ => false, + } + } + } + + /// Get min-xcm-fee by multilocation. + impl GetByKey for Pallet { + fn get(location: &MultiLocation) -> u128 { + let location = + >::AssetLocation::from(location.clone()); + match MinXcmFee::::get(&location) { + Some(min_fee) => min_fee, + None => u128::MAX, + } + } + } + + #[pallet::hooks] + impl Hooks> for Pallet { + fn on_runtime_upgrade() -> Weight { + // currently, it's 0 on calamari. + let storage_version = Self::on_chain_storage_version(); + if storage_version < 1 { + log::info!(target: "asset-manager", "Start to execute storage migration for asset-manager."); + + let mut reads: Weight = 0; + let mut writes: Weight = 0; + LocationAssetId::::iter().for_each(|(location, _asset_id)| { + reads += 1; + if let Some(para_id) = + Self::get_para_id_from_multilocation(location.into().as_ref()) + { + if para_id != 2084 { + let _ = Self::increase_count_of_associated_assets(para_id); + reads += 1; // There's one read in method increase_count_of_associated_assets. + writes += 1; // There's one write in method increase_count_of_associated_assets. + } + } + }); + + // Update storage version. + StorageVersion::new(1u16).put::(); + writes += 1; + + T::DbWeight::get() + .reads(reads) + .saturating_add(T::DbWeight::get().writes(writes)) + } else { + log::info!("✅ no migration for asset-manager."); + // only 1 read + T::DbWeight::get().reads(1) + } + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result<(), &'static str> { + let storage_version = Self::on_chain_storage_version(); + + if storage_version >= 1 { + return Err("Storage version is >= 1, the migration won't be executed."); + } + + Ok(()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade() -> Result<(), &'static str> { + let storage_version = Self::on_chain_storage_version(); + + if storage_version < 1 { + return Err("Storage version is >= 1, the migration won't be executed."); + } + + let acala = (2000, 3); // karura has 3 asset locations on calamari. + let moonbeam = (2023, 1); // moonbean has 1 asset location on calamari. + let calamari = 2084; // our own asset location won't be counted. + if AllowedDestParaIds::::get(acala.0) == Some(acala.1) + && AllowedDestParaIds::::get(moonbeam.0) == Some(moonbeam.1) + && AllowedDestParaIds::::get(calamari).is_none() + { + log::info!( + "✅ Storage migration for asset-manager has been executed successfully." + ); + Ok(()) + } else { + Err("Failed to executed storage migration for asset-manager.") + } + } + } + + #[cfg(feature = "std")] + impl GenesisConfig { + /// Direct implementation of `GenesisBuild::build_storage`. + /// + /// Kept in order not to break dependency. + pub fn build_storage(&self) -> Result { + >::build_storage(self) + } + + /// Direct implementation of `GenesisBuild::assimilate_storage`. + /// + /// Kept in order not to break dependency. + pub fn assimilate_storage(&self, storage: &mut sp_runtime::Storage) -> Result<(), String> { + >::assimilate_storage(self, storage) + } + } } diff --git a/pallets/asset-manager/src/mock.rs b/pallets/asset-manager/src/mock.rs index 8eb22a928..73403f98e 100644 --- a/pallets/asset-manager/src/mock.rs +++ b/pallets/asset-manager/src/mock.rs @@ -21,233 +21,233 @@ use crate as pallet_asset_manager; use frame_support::{ - construct_runtime, pallet_prelude::DispatchResult, parameter_types, traits::ConstU32, PalletId, + construct_runtime, pallet_prelude::DispatchResult, parameter_types, traits::ConstU32, PalletId, }; use frame_system as system; use frame_system::EnsureRoot; use manta_primitives::{ - assets::{ - AssetConfig, AssetLocation, AssetRegistrar, AssetRegistrarMetadata, AssetStorageMetadata, - ConcreteFungibleLedger, - }, - constants::{ASSET_MANAGER_PALLET_ID, ASSET_STRING_LIMIT}, - types::{AccountId, AssetId, Balance}, + assets::{ + AssetConfig, AssetLocation, AssetRegistrar, AssetRegistrarMetadata, AssetStorageMetadata, + ConcreteFungibleLedger, + }, + constants::{ASSET_MANAGER_PALLET_ID, ASSET_STRING_LIMIT}, + types::{AccountId, AssetId, Balance}, }; use sp_core::{H160, H256}; use sp_runtime::{ - testing::Header, - traits::{BlakeTwo256, IdentityLookup}, + testing::Header, + traits::{BlakeTwo256, IdentityLookup}, }; use sp_std::marker::PhantomData; use xcm::{ - prelude::{Parachain, X1}, - v1::MultiLocation, - VersionedMultiLocation, + prelude::{Parachain, X1}, + v1::MultiLocation, + VersionedMultiLocation, }; parameter_types! { - pub const BlockHashCount: u64 = 250; - pub const SS58Prefix: u8 = 78; + pub const BlockHashCount: u64 = 250; + pub const SS58Prefix: u8 = 78; } impl system::Config for Runtime { - type BaseCallFilter = frame_support::traits::Everything; - type BlockWeights = (); - type BlockLength = (); - type DbWeight = (); - type Origin = Origin; - type Call = Call; - type Index = u64; - type BlockNumber = u64; - type Hash = H256; - type Hashing = BlakeTwo256; - type AccountId = AccountId; - type Lookup = IdentityLookup; - type Header = Header; - type Event = Event; - type BlockHashCount = BlockHashCount; - 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>; + type BaseCallFilter = frame_support::traits::Everything; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type Origin = Origin; + type Call = Call; + type Index = u64; + type BlockNumber = u64; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = AccountId; + type Lookup = IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = BlockHashCount; + 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>; } parameter_types! { - pub const AssetDeposit: Balance = 0; // Does not really matter as this will be only called by root - pub const AssetAccountDeposit: Balance = 0; - pub const ApprovalDeposit: Balance = 0; - pub const AssetsStringLimit: u32 = ASSET_STRING_LIMIT; - pub const MetadataDepositBase: Balance = 0; - pub const MetadataDepositPerByte: Balance = 0; + pub const AssetDeposit: Balance = 0; // Does not really matter as this will be only called by root + pub const AssetAccountDeposit: Balance = 0; + pub const ApprovalDeposit: Balance = 0; + pub const AssetsStringLimit: u32 = ASSET_STRING_LIMIT; + pub const MetadataDepositBase: Balance = 0; + pub const MetadataDepositPerByte: Balance = 0; } impl pallet_assets::Config for Runtime { - type Event = Event; - type Balance = Balance; - type AssetId = AssetId; - type Currency = Balances; - type ForceOrigin = EnsureRoot; - type AssetDeposit = AssetDeposit; - type AssetAccountDeposit = AssetAccountDeposit; - type MetadataDepositBase = MetadataDepositBase; - type MetadataDepositPerByte = MetadataDepositPerByte; - type ApprovalDeposit = ApprovalDeposit; - type StringLimit = AssetsStringLimit; - type Freezer = (); - type Extra = (); - type WeightInfo = (); + type Event = Event; + type Balance = Balance; + type AssetId = AssetId; + type Currency = Balances; + type ForceOrigin = EnsureRoot; + type AssetDeposit = AssetDeposit; + type AssetAccountDeposit = AssetAccountDeposit; + type MetadataDepositBase = MetadataDepositBase; + type MetadataDepositPerByte = MetadataDepositPerByte; + type ApprovalDeposit = ApprovalDeposit; + type StringLimit = AssetsStringLimit; + type Freezer = (); + type Extra = (); + type WeightInfo = (); } parameter_types! { - pub ExistentialDeposit: Balance = 1; - pub const MaxLocks: u32 = 50; - pub const MaxReserves: u32 = 50; + 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 Event = Event; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; - type WeightInfo = (); - type MaxReserves = MaxReserves; - type ReserveIdentifier = [u8; 8]; + type MaxLocks = MaxLocks; + type Balance = Balance; + type Event = Event; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = (); + type MaxReserves = MaxReserves; + type ReserveIdentifier = [u8; 8]; } pub struct MantaAssetRegistrar; impl AssetRegistrar for MantaAssetRegistrar { - fn create_asset( - asset_id: AssetId, - min_balance: Balance, - metadata: AssetStorageMetadata, - is_sufficient: bool, - ) -> DispatchResult { - Assets::force_create( - Origin::root(), - asset_id, - AssetManager::account_id(), - is_sufficient, - min_balance, - )?; - - Assets::force_set_metadata( - Origin::root(), - asset_id, - metadata.name, - metadata.symbol, - metadata.decimals, - metadata.is_frozen, - ) - } - - fn update_asset_metadata(asset_id: AssetId, metadata: AssetStorageMetadata) -> DispatchResult { - Assets::force_set_metadata( - Origin::root(), - asset_id, - metadata.name, - metadata.symbol, - metadata.decimals, - metadata.is_frozen, - ) - } + fn create_asset( + asset_id: AssetId, + min_balance: Balance, + metadata: AssetStorageMetadata, + is_sufficient: bool, + ) -> DispatchResult { + Assets::force_create( + Origin::root(), + asset_id, + AssetManager::account_id(), + is_sufficient, + min_balance, + )?; + + Assets::force_set_metadata( + Origin::root(), + asset_id, + metadata.name, + metadata.symbol, + metadata.decimals, + metadata.is_frozen, + ) + } + + fn update_asset_metadata(asset_id: AssetId, metadata: AssetStorageMetadata) -> DispatchResult { + Assets::force_set_metadata( + Origin::root(), + asset_id, + metadata.name, + metadata.symbol, + metadata.decimals, + metadata.is_frozen, + ) + } } parameter_types! { - pub const DummyAssetId: AssetId = 0; - pub const NativeAssetId: AssetId = 1; - pub const StartNonNativeAssetId: AssetId = 8; - pub NativeAssetLocation: AssetLocation = AssetLocation( - VersionedMultiLocation::V1(MultiLocation::new(1, X1(Parachain(1024))))); - pub NativeAssetMetadata: AssetRegistrarMetadata = AssetRegistrarMetadata { - name: b"Dolphin".to_vec(), - symbol: b"DOL".to_vec(), - decimals: 18, - min_balance: 1u128, - evm_address: None, - is_frozen: false, - is_sufficient: true, - }; - pub const AssetManagerPalletId: PalletId = ASSET_MANAGER_PALLET_ID; + pub const DummyAssetId: AssetId = 0; + pub const NativeAssetId: AssetId = 1; + pub const StartNonNativeAssetId: AssetId = 8; + pub NativeAssetLocation: AssetLocation = AssetLocation( + VersionedMultiLocation::V1(MultiLocation::new(1, X1(Parachain(1024))))); + pub NativeAssetMetadata: AssetRegistrarMetadata = AssetRegistrarMetadata { + name: b"Dolphin".to_vec(), + symbol: b"DOL".to_vec(), + decimals: 18, + min_balance: 1u128, + evm_address: None, + is_frozen: false, + is_sufficient: true, + }; + pub const AssetManagerPalletId: PalletId = ASSET_MANAGER_PALLET_ID; } #[derive(Clone, Eq, PartialEq)] pub struct MantaAssetConfig; impl AssetConfig for MantaAssetConfig { - type DummyAssetId = DummyAssetId; - type NativeAssetId = NativeAssetId; - type StartNonNativeAssetId = StartNonNativeAssetId; - type AssetRegistrarMetadata = AssetRegistrarMetadata; - type NativeAssetLocation = NativeAssetLocation; - type NativeAssetMetadata = NativeAssetMetadata; - type StorageMetadata = AssetStorageMetadata; - type AssetLocation = AssetLocation; - type AssetRegistrar = MantaAssetRegistrar; - type FungibleLedger = ConcreteFungibleLedger; + type DummyAssetId = DummyAssetId; + type NativeAssetId = NativeAssetId; + type StartNonNativeAssetId = StartNonNativeAssetId; + type AssetRegistrarMetadata = AssetRegistrarMetadata; + type NativeAssetLocation = NativeAssetLocation; + type NativeAssetMetadata = NativeAssetMetadata; + type StorageMetadata = AssetStorageMetadata; + type AssetLocation = AssetLocation; + type AssetRegistrar = MantaAssetRegistrar; + type FungibleLedger = ConcreteFungibleLedger; } impl pallet_asset_manager::Config for Runtime { - type Event = Event; - type AssetConfig = MantaAssetConfig; - type ModifierOrigin = EnsureRoot; - type PalletId = AssetManagerPalletId; - type WeightInfo = (); + type Event = Event; + type AssetConfig = MantaAssetConfig; + type ModifierOrigin = EnsureRoot; + type PalletId = AssetManagerPalletId; + type WeightInfo = (); } type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - System: frame_system::{Pallet, Call, Storage, Config, Event} = 0, - Assets: pallet_assets::{Pallet, Storage, Event} = 1, - AssetManager: pallet_asset_manager::{Pallet, Call, Storage, Event} = 2, - Balances: pallet_balances::{Pallet, Call, Storage, Config, Event} = 3, - } + pub enum Runtime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Storage, Config, Event} = 0, + Assets: pallet_assets::{Pallet, Storage, Event} = 1, + AssetManager: pallet_asset_manager::{Pallet, Call, Storage, Event} = 2, + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event} = 3, + } ); pub const PALLET_BALANCES_INDEX: u8 = 3; pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); - pallet_asset_manager::GenesisConfig:: { - start_id: >::StartNonNativeAssetId::get(), - _marker: PhantomData::::default(), - } - .assimilate_storage(&mut t) - .unwrap(); - sp_io::TestExternalities::new(t) + let mut t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); + pallet_asset_manager::GenesisConfig:: { + start_id: >::StartNonNativeAssetId::get(), + _marker: PhantomData::::default(), + } + .assimilate_storage(&mut t) + .unwrap(); + sp_io::TestExternalities::new(t) } pub(crate) fn create_asset_metadata( - name: &str, - symbol: &str, - decimals: u8, - min_balance: u128, - evm_address: Option, - is_frozen: bool, - is_sufficient: bool, + name: &str, + symbol: &str, + decimals: u8, + min_balance: u128, + evm_address: Option, + is_frozen: bool, + is_sufficient: bool, ) -> AssetRegistrarMetadata { - AssetRegistrarMetadata { - name: name.as_bytes().to_vec(), - symbol: symbol.as_bytes().to_vec(), - decimals, - min_balance, - evm_address, - is_frozen, - is_sufficient, - } + AssetRegistrarMetadata { + name: name.as_bytes().to_vec(), + symbol: symbol.as_bytes().to_vec(), + decimals, + min_balance, + evm_address, + is_frozen, + is_sufficient, + } } diff --git a/pallets/asset-manager/src/tests.rs b/pallets/asset-manager/src/tests.rs index 42cd37820..abb44d919 100644 --- a/pallets/asset-manager/src/tests.rs +++ b/pallets/asset-manager/src/tests.rs @@ -17,12 +17,12 @@ //! unit tests for asset-manager use crate::{ - self as asset_manager, AssetIdLocation, AssetIdMetadata, Error, LocationAssetId, UnitsPerSecond, + self as asset_manager, AssetIdLocation, AssetIdMetadata, Error, LocationAssetId, UnitsPerSecond, }; use asset_manager::mock::*; use frame_support::{ - assert_noop, assert_ok, - traits::{fungibles::InspectMetadata, Contains}, + assert_noop, assert_ok, + traits::{fungibles::InspectMetadata, Contains}, }; use manta_primitives::assets::{AssetConfig, AssetLocation, FungibleLedger}; use orml_traits::GetByKey; @@ -33,509 +33,509 @@ pub const ALICE: sp_runtime::AccountId32 = sp_runtime::AccountId32::new([0u8; 32 #[test] fn basic_setup_should_work() { - new_test_ext().execute_with(|| { - let asset_id = >::NativeAssetId::get(); - let asset_location = >::NativeAssetLocation::get(); - let asset_metadata = >::NativeAssetMetadata::get(); - assert_eq!( - AssetIdLocation::::get(asset_id), - Some(asset_location.clone()) - ); - assert_eq!( - AssetIdMetadata::::get(asset_id), - Some(asset_metadata) - ); - assert_eq!( - LocationAssetId::::get(asset_location), - Some(asset_id) - ); - }); + new_test_ext().execute_with(|| { + let asset_id = >::NativeAssetId::get(); + let asset_location = >::NativeAssetLocation::get(); + let asset_metadata = >::NativeAssetMetadata::get(); + assert_eq!( + AssetIdLocation::::get(asset_id), + Some(asset_location.clone()) + ); + assert_eq!( + AssetIdMetadata::::get(asset_id), + Some(asset_metadata) + ); + assert_eq!( + LocationAssetId::::get(asset_location), + Some(asset_id) + ); + }); } #[test] fn wrong_modifier_origin_should_not_work() { - new_test_ext().execute_with(|| { - let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1u128, None, false, true); - let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); - assert_noop!( - AssetManager::register_asset( - Origin::signed([0u8; 32].into()), - source_location.clone(), - asset_metadata.clone() - ), - BadOrigin - ); - assert_noop!( - AssetManager::update_asset_location( - Origin::signed([2u8; 32].into()), - 0, - source_location - ), - BadOrigin - ); - assert_noop!( - AssetManager::update_asset_metadata( - Origin::signed([3u8; 32].into()), - 0, - asset_metadata - ), - BadOrigin - ); - assert_noop!( - AssetManager::set_units_per_second(Origin::signed([4u8; 32].into()), 0, 0), - BadOrigin - ); - }) + new_test_ext().execute_with(|| { + let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1u128, None, false, true); + let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); + assert_noop!( + AssetManager::register_asset( + Origin::signed([0u8; 32].into()), + source_location.clone(), + asset_metadata.clone() + ), + BadOrigin + ); + assert_noop!( + AssetManager::update_asset_location( + Origin::signed([2u8; 32].into()), + 0, + source_location + ), + BadOrigin + ); + assert_noop!( + AssetManager::update_asset_metadata( + Origin::signed([3u8; 32].into()), + 0, + asset_metadata + ), + BadOrigin + ); + assert_noop!( + AssetManager::set_units_per_second(Origin::signed([4u8; 32].into()), 0, 0), + BadOrigin + ); + }) } #[test] fn register_asset_should_work() { - let para_id = 1; - let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1u128, None, false, true); - let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); - let new_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( - 1, - X2(Parachain(para_id), PalletInstance(PALLET_BALANCES_INDEX)), - ))); - new_test_ext().execute_with(|| { - let mut counter: u32 = - >::StartNonNativeAssetId::get(); - // Register relay chain native token - assert_ok!(AssetManager::register_asset( - Origin::root(), - source_location.clone(), - asset_metadata.clone() - )); - assert_eq!( - AssetIdLocation::::get(counter), - Some(source_location.clone()) - ); - // relaychain has no para id. - assert!(!crate::AllowedDestParaIds::::contains_key(para_id)); - counter += 1; - // Register twice will fail - assert_noop!( - AssetManager::register_asset(Origin::root(), source_location, asset_metadata.clone()), - Error::::LocationAlreadyExists - ); - // Register a new asset - assert_ok!(AssetManager::register_asset( - Origin::root(), - new_location.clone(), - asset_metadata.clone() - )); - assert_eq!(AssetIdLocation::::get(counter), Some(new_location)); - // check para ids - assert!(crate::AllowedDestParaIds::::contains_key(para_id)); - }) + let para_id = 1; + let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1u128, None, false, true); + let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); + let new_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( + 1, + X2(Parachain(para_id), PalletInstance(PALLET_BALANCES_INDEX)), + ))); + new_test_ext().execute_with(|| { + let mut counter: u32 = + >::StartNonNativeAssetId::get(); + // Register relay chain native token + assert_ok!(AssetManager::register_asset( + Origin::root(), + source_location.clone(), + asset_metadata.clone() + )); + assert_eq!( + AssetIdLocation::::get(counter), + Some(source_location.clone()) + ); + // relaychain has no para id. + assert!(!crate::AllowedDestParaIds::::contains_key(para_id)); + counter += 1; + // Register twice will fail + assert_noop!( + AssetManager::register_asset(Origin::root(), source_location, asset_metadata.clone()), + Error::::LocationAlreadyExists + ); + // Register a new asset + assert_ok!(AssetManager::register_asset( + Origin::root(), + new_location.clone(), + asset_metadata.clone() + )); + assert_eq!(AssetIdLocation::::get(counter), Some(new_location)); + // check para ids + assert!(crate::AllowedDestParaIds::::contains_key(para_id)); + }) } #[test] fn update_asset() { - let para_id = 1; - let original_decimals = 12; - let asset_metadata = create_asset_metadata( - "Kusama", - "KSM", - original_decimals, - 1u128, - None, - false, - false, - ); - let mut new_metadata = asset_metadata.clone(); - let new_name = b"NotKusama".to_vec(); - let new_symbol = b"NotKSM".to_vec(); - let new_decimals = original_decimals + 1; - new_metadata.name = new_name.clone(); - new_metadata.symbol = new_symbol.clone(); - new_metadata.decimals = new_decimals; - let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); - let new_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( - 1, - X2(Parachain(para_id), PalletInstance(PALLET_BALANCES_INDEX)), - ))); - new_test_ext().execute_with(|| { - // Register relay chain native token - let asset_id = >::StartNonNativeAssetId::get(); - assert_ok!(AssetManager::register_asset( - Origin::root(), - source_location.clone(), - asset_metadata.clone() - )); - assert_eq!( - AssetIdLocation::::get(asset_id), - Some(source_location.clone()) - ); - // Cannot update asset 1. Will be reserved for the native asset. - let native_asset_id = >::NativeAssetId::get(); - assert_noop!( - AssetManager::update_asset_metadata( - Origin::root(), - native_asset_id, - new_metadata.clone(), - ), - Error::::CannotUpdateNativeAssetMetadata - ); - assert_ok!(AssetManager::update_asset_metadata( - Origin::root(), - asset_id, - new_metadata.clone(), - ),); - assert_eq!(Assets::name(&asset_id), new_name); - assert_eq!(Assets::symbol(&asset_id), new_symbol); - assert_eq!(Assets::decimals(&asset_id), new_decimals); - // Update the asset location - assert_ok!(AssetManager::update_asset_location( - Origin::root(), - asset_id, - new_location.clone() - )); - // Update asset units per seconds - assert_ok!(AssetManager::set_units_per_second( - Origin::root(), - asset_id, - 125u128 - )); - assert_eq!(UnitsPerSecond::::get(asset_id), Some(125)); - let next_asset_id = asset_id + 1; - // Update a non-exist asset should fail - assert_noop!( - AssetManager::update_asset_location( - Origin::root(), - next_asset_id, - new_location.clone() - ), - Error::::UpdateNonExistAsset - ); - assert_noop!( - AssetManager::update_asset_metadata( - Origin::root(), - next_asset_id, - new_metadata.clone() - ), - Error::::UpdateNonExistAsset - ); - // Re-registering the original location and metadata should work, - // as we modified the previous asset. - assert_ok!(AssetManager::register_asset( - Origin::root(), - source_location.clone(), - asset_metadata.clone() - )); - // But updating the asset to an existing location will fail. - assert_noop!( - AssetManager::update_asset_location(Origin::root(), next_asset_id, new_location), - Error::::LocationAlreadyExists - ); + let para_id = 1; + let original_decimals = 12; + let asset_metadata = create_asset_metadata( + "Kusama", + "KSM", + original_decimals, + 1u128, + None, + false, + false, + ); + let mut new_metadata = asset_metadata.clone(); + let new_name = b"NotKusama".to_vec(); + let new_symbol = b"NotKSM".to_vec(); + let new_decimals = original_decimals + 1; + new_metadata.name = new_name.clone(); + new_metadata.symbol = new_symbol.clone(); + new_metadata.decimals = new_decimals; + let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); + let new_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( + 1, + X2(Parachain(para_id), PalletInstance(PALLET_BALANCES_INDEX)), + ))); + new_test_ext().execute_with(|| { + // Register relay chain native token + let asset_id = >::StartNonNativeAssetId::get(); + assert_ok!(AssetManager::register_asset( + Origin::root(), + source_location.clone(), + asset_metadata.clone() + )); + assert_eq!( + AssetIdLocation::::get(asset_id), + Some(source_location.clone()) + ); + // Cannot update asset 1. Will be reserved for the native asset. + let native_asset_id = >::NativeAssetId::get(); + assert_noop!( + AssetManager::update_asset_metadata( + Origin::root(), + native_asset_id, + new_metadata.clone(), + ), + Error::::CannotUpdateNativeAssetMetadata + ); + assert_ok!(AssetManager::update_asset_metadata( + Origin::root(), + asset_id, + new_metadata.clone(), + ),); + assert_eq!(Assets::name(&asset_id), new_name); + assert_eq!(Assets::symbol(&asset_id), new_symbol); + assert_eq!(Assets::decimals(&asset_id), new_decimals); + // Update the asset location + assert_ok!(AssetManager::update_asset_location( + Origin::root(), + asset_id, + new_location.clone() + )); + // Update asset units per seconds + assert_ok!(AssetManager::set_units_per_second( + Origin::root(), + asset_id, + 125u128 + )); + assert_eq!(UnitsPerSecond::::get(asset_id), Some(125)); + let next_asset_id = asset_id + 1; + // Update a non-exist asset should fail + assert_noop!( + AssetManager::update_asset_location( + Origin::root(), + next_asset_id, + new_location.clone() + ), + Error::::UpdateNonExistAsset + ); + assert_noop!( + AssetManager::update_asset_metadata( + Origin::root(), + next_asset_id, + new_metadata.clone() + ), + Error::::UpdateNonExistAsset + ); + // Re-registering the original location and metadata should work, + // as we modified the previous asset. + assert_ok!(AssetManager::register_asset( + Origin::root(), + source_location.clone(), + asset_metadata.clone() + )); + // But updating the asset to an existing location will fail. + assert_noop!( + AssetManager::update_asset_location(Origin::root(), next_asset_id, new_location), + Error::::LocationAlreadyExists + ); - // If the existing asset location has been changed para id, the old para id should be - // deleted from `AllowedDestParaIds` and new one should be inserted. - let new_para_id = para_id + 1; - let new_location_2 = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( - 1, - X2( - Parachain(new_para_id), - PalletInstance(PALLET_BALANCES_INDEX), - ), - ))); - assert!(crate::AllowedDestParaIds::::contains_key(para_id)); + // If the existing asset location has been changed para id, the old para id should be + // deleted from `AllowedDestParaIds` and new one should be inserted. + let new_para_id = para_id + 1; + let new_location_2 = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( + 1, + X2( + Parachain(new_para_id), + PalletInstance(PALLET_BALANCES_INDEX), + ), + ))); + assert!(crate::AllowedDestParaIds::::contains_key(para_id)); - assert_ok!(AssetManager::update_asset_location( - Origin::root(), - asset_id, - new_location_2, - )); - // Old para id should be deleted. - assert!(!crate::AllowedDestParaIds::::contains_key(para_id)); - assert!(crate::AllowedDestParaIds::::contains_key( - new_para_id - )); - }) + assert_ok!(AssetManager::update_asset_location( + Origin::root(), + asset_id, + new_location_2, + )); + // Old para id should be deleted. + assert!(!crate::AllowedDestParaIds::::contains_key(para_id)); + assert!(crate::AllowedDestParaIds::::contains_key( + new_para_id + )); + }) } #[test] fn check_para_id_info_when_update_asset_location() { - new_test_ext().execute_with(|| { - let manta_para_id = 2015; - let manta_asset_metadata = - create_asset_metadata("Manta", "MANTA", 18, 1u128, None, false, false); - let mut manta_native_location = AssetLocation(VersionedMultiLocation::V1( - MultiLocation::new(1, X1(Parachain(manta_para_id))), - )); + new_test_ext().execute_with(|| { + let manta_para_id = 2015; + let manta_asset_metadata = + create_asset_metadata("Manta", "MANTA", 18, 1u128, None, false, false); + let mut manta_native_location = AssetLocation(VersionedMultiLocation::V1( + MultiLocation::new(1, X1(Parachain(manta_para_id))), + )); - // regitering manta native asset should work. - assert_ok!(AssetManager::register_asset( - Origin::root(), - manta_native_location, - manta_asset_metadata - )); - let manta_asset_id = crate::NextAssetId::::get() - 1; - // check para id - assert!(crate::AllowedDestParaIds::::contains_key( - manta_para_id - )); - assert_eq!( - crate::AllowedDestParaIds::::get(manta_para_id), - Some(1) - ); + // regitering manta native asset should work. + assert_ok!(AssetManager::register_asset( + Origin::root(), + manta_native_location, + manta_asset_metadata + )); + let manta_asset_id = crate::NextAssetId::::get() - 1; + // check para id + assert!(crate::AllowedDestParaIds::::contains_key( + manta_para_id + )); + assert_eq!( + crate::AllowedDestParaIds::::get(manta_para_id), + Some(1) + ); - // create a non manta asset. - let manta_non_native_asset_metadata = - create_asset_metadata("Manta", "eMANTA", 18, 1u128, None, false, false); - let mut manta_non_native_location = - AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( - 1, - X2(Parachain(manta_para_id), GeneralKey(b"eMANTA".to_vec())), - ))); - // regitering manta non native asset should work. - assert_ok!(AssetManager::register_asset( - Origin::root(), - manta_non_native_location, - manta_non_native_asset_metadata - )); - let manta_non_native_asset_id = crate::NextAssetId::::get() - 1; - // ParaId=manta_para_id should have 2 assets. - assert_eq!( - crate::AllowedDestParaIds::::get(manta_para_id), - Some(2) - ); + // create a non manta asset. + let manta_non_native_asset_metadata = + create_asset_metadata("Manta", "eMANTA", 18, 1u128, None, false, false); + let mut manta_non_native_location = + AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( + 1, + X2(Parachain(manta_para_id), GeneralKey(b"eMANTA".to_vec())), + ))); + // regitering manta non native asset should work. + assert_ok!(AssetManager::register_asset( + Origin::root(), + manta_non_native_location, + manta_non_native_asset_metadata + )); + let manta_non_native_asset_id = crate::NextAssetId::::get() - 1; + // ParaId=manta_para_id should have 2 assets. + assert_eq!( + crate::AllowedDestParaIds::::get(manta_para_id), + Some(2) + ); - // Update new para id for manta native location - let new_para_id = manta_para_id + 1; - manta_native_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( - 1, - X2(Parachain(new_para_id), GeneralKey(b"MANTA".to_vec())), - ))); - assert_ok!(AssetManager::update_asset_location( - Origin::root(), - manta_asset_id, - manta_native_location, - )); - // ParaId=manta_para_id should have 1 asset. - assert_eq!( - crate::AllowedDestParaIds::::get(manta_para_id), - Some(1) - ); - // ParaId=new_para_id should have 1 asset. - assert_eq!( - crate::AllowedDestParaIds::::get(new_para_id), - Some(1) - ); + // Update new para id for manta native location + let new_para_id = manta_para_id + 1; + manta_native_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( + 1, + X2(Parachain(new_para_id), GeneralKey(b"MANTA".to_vec())), + ))); + assert_ok!(AssetManager::update_asset_location( + Origin::root(), + manta_asset_id, + manta_native_location, + )); + // ParaId=manta_para_id should have 1 asset. + assert_eq!( + crate::AllowedDestParaIds::::get(manta_para_id), + Some(1) + ); + // ParaId=new_para_id should have 1 asset. + assert_eq!( + crate::AllowedDestParaIds::::get(new_para_id), + Some(1) + ); - // Update para id for manta_non_native_location - let new_para_id_again = new_para_id + 1; - manta_non_native_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( - 1, - X2(Parachain(new_para_id_again), GeneralKey(b"eMANTA".to_vec())), - ))); - assert_ok!(AssetManager::update_asset_location( - Origin::root(), - manta_non_native_asset_id, - manta_non_native_location, - )); - // ParaId=manta_para_id should deleted. - assert!(!crate::AllowedDestParaIds::::contains_key( - manta_para_id - )); - // ParaId=new_para_id_again should have 1 asset. - assert_eq!( - crate::AllowedDestParaIds::::get(new_para_id_again), - Some(1) - ); - // ParaId=new_para_id should have 1 asset. - assert_eq!( - crate::AllowedDestParaIds::::get(new_para_id), - Some(1) - ); - }); + // Update para id for manta_non_native_location + let new_para_id_again = new_para_id + 1; + manta_non_native_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( + 1, + X2(Parachain(new_para_id_again), GeneralKey(b"eMANTA".to_vec())), + ))); + assert_ok!(AssetManager::update_asset_location( + Origin::root(), + manta_non_native_asset_id, + manta_non_native_location, + )); + // ParaId=manta_para_id should deleted. + assert!(!crate::AllowedDestParaIds::::contains_key( + manta_para_id + )); + // ParaId=new_para_id_again should have 1 asset. + assert_eq!( + crate::AllowedDestParaIds::::get(new_para_id_again), + Some(1) + ); + // ParaId=new_para_id should have 1 asset. + assert_eq!( + crate::AllowedDestParaIds::::get(new_para_id), + Some(1) + ); + }); } #[test] fn mint_asset() { - new_test_ext().execute_with(|| { - // mint native asset - let native_asset_id = >::NativeAssetId::get(); - assert_ok!( - >::FungibleLedger::mint( - native_asset_id, - &ALICE, - 1000_000 - ) - ); + new_test_ext().execute_with(|| { + // mint native asset + let native_asset_id = >::NativeAssetId::get(); + assert_ok!( + >::FungibleLedger::mint( + native_asset_id, + &ALICE, + 1_000_000 + ) + ); - // mint non-native asset - let non_native_asset_id = - >::StartNonNativeAssetId::get(); - let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1u128, None, false, true); - let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); - assert_ok!(AssetManager::register_asset( - Origin::root(), - source_location, - asset_metadata - )); - assert_ok!( - >::FungibleLedger::mint( - non_native_asset_id, - &ALICE, - 1000_000 - ) - ); - }); + // mint non-native asset + let non_native_asset_id = + >::StartNonNativeAssetId::get(); + let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1u128, None, false, true); + let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); + assert_ok!(AssetManager::register_asset( + Origin::root(), + source_location, + asset_metadata + )); + assert_ok!( + >::FungibleLedger::mint( + non_native_asset_id, + &ALICE, + 1_000_000 + ) + ); + }); } #[test] fn filter_asset_location_should_work() { - let kusama_asset_metadata = - create_asset_metadata("Kusama", "KSM", 12, 1u128, None, false, false); - let kusama_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); + let kusama_asset_metadata = + create_asset_metadata("Kusama", "KSM", 12, 1u128, None, false, false); + let kusama_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); - let para_id = 2015; - let manta_asset_metadata = - create_asset_metadata("Manta", "MANTA", 18, 1u128, None, false, false); - let manta_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( - 1, - X1(Parachain(para_id)), - ))); - new_test_ext().execute_with(|| { - // Register relay chain native token - assert_ok!(AssetManager::register_asset( - Origin::root(), - kusama_location.clone(), - kusama_asset_metadata.clone() - )); - let kusama_asset_id = crate::NextAssetId::::get() - 1; - assert_eq!( - AssetIdLocation::::get(kusama_asset_id), - Some(kusama_location.clone()) - ); + let para_id = 2015; + let manta_asset_metadata = + create_asset_metadata("Manta", "MANTA", 18, 1u128, None, false, false); + let manta_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( + 1, + X1(Parachain(para_id)), + ))); + new_test_ext().execute_with(|| { + // Register relay chain native token + assert_ok!(AssetManager::register_asset( + Origin::root(), + kusama_location.clone(), + kusama_asset_metadata.clone() + )); + let kusama_asset_id = crate::NextAssetId::::get() - 1; + assert_eq!( + AssetIdLocation::::get(kusama_asset_id), + Some(kusama_location.clone()) + ); - // Register manta para chain native token - assert_ok!(AssetManager::register_asset( - Origin::root(), - manta_location.clone(), - manta_asset_metadata.clone() - )); + // Register manta para chain native token + assert_ok!(AssetManager::register_asset( + Origin::root(), + manta_location.clone(), + manta_asset_metadata.clone() + )); - let manta_asset_id = crate::NextAssetId::::get() - 1; - assert_eq!( - AssetIdLocation::::get(manta_asset_id), - Some(manta_location.clone()) - ); + let manta_asset_id = crate::NextAssetId::::get() - 1; + assert_eq!( + AssetIdLocation::::get(manta_asset_id), + Some(manta_location.clone()) + ); - // correct location should work - let relay_dest = MultiLocation { - parents: 1, - interior: X1(AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }), - }; - let para_dest = MultiLocation { - parents: 1, - interior: X2( - Parachain(para_id), - AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }, - ), - }; - assert!(crate::Pallet::::contains(¶_dest)); - assert!(crate::Pallet::::contains(&relay_dest)); + // correct location should work + let relay_dest = MultiLocation { + parents: 1, + interior: X1(AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }), + }; + let para_dest = MultiLocation { + parents: 1, + interior: X2( + Parachain(para_id), + AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }, + ), + }; + assert!(crate::Pallet::::contains(¶_dest)); + assert!(crate::Pallet::::contains(&relay_dest)); - // wrong location should be filtered - let wrong_relay_dest = MultiLocation { - parents: 1, - interior: Here, - }; - let wrong_para_dest = MultiLocation { - parents: 1, - interior: X2( - Parachain(para_id + 1), - AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }, - ), - }; - assert!(!crate::Pallet::::contains(&wrong_relay_dest)); - assert!(!crate::Pallet::::contains(&wrong_para_dest)); + // wrong location should be filtered + let wrong_relay_dest = MultiLocation { + parents: 1, + interior: Here, + }; + let wrong_para_dest = MultiLocation { + parents: 1, + interior: X2( + Parachain(para_id + 1), + AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }, + ), + }; + assert!(!crate::Pallet::::contains(&wrong_relay_dest)); + assert!(!crate::Pallet::::contains(&wrong_para_dest)); - // AccountKey20 based location should work - let eve = [1u8; 20]; // evm based account - let para_dest_with_evm_account = MultiLocation { - parents: 1, - interior: X2( - Parachain(para_id), - AccountKey20 { - network: NetworkId::Any, - key: eve.into(), - }, - ), - }; - assert!(crate::Pallet::::contains( - ¶_dest_with_evm_account - )); - }) + // AccountKey20 based location should work + let eve = [1u8; 20]; // evm based account + let para_dest_with_evm_account = MultiLocation { + parents: 1, + interior: X2( + Parachain(para_id), + AccountKey20 { + network: NetworkId::Any, + key: eve, + }, + ), + }; + assert!(crate::Pallet::::contains( + ¶_dest_with_evm_account + )); + }) } #[test] fn set_min_xcm_fee_should_work() { - let manta_asset_metadata = - create_asset_metadata("Manta", "MANTA", 18, 1u128, None, false, false); - let manta_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( - 1, - X2(Parachain(2015), GeneralKey(b"MANTA".to_vec())), - ))); - new_test_ext().execute_with(|| { - // Register a non native token. - assert_ok!(AssetManager::register_asset( - Origin::root(), - manta_location.clone(), - manta_asset_metadata.clone() - )); + let manta_asset_metadata = + create_asset_metadata("Manta", "MANTA", 18, 1u128, None, false, false); + let manta_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( + 1, + X2(Parachain(2015), GeneralKey(b"MANTA".to_vec())), + ))); + new_test_ext().execute_with(|| { + // Register a non native token. + assert_ok!(AssetManager::register_asset( + Origin::root(), + manta_location.clone(), + manta_asset_metadata.clone() + )); - let manta_asset_id = crate::NextAssetId::::get() - 1; - assert_eq!( - AssetIdLocation::::get(manta_asset_id), - Some(manta_location.clone()) - ); + let manta_asset_id = crate::NextAssetId::::get() - 1; + assert_eq!( + AssetIdLocation::::get(manta_asset_id), + Some(manta_location.clone()) + ); - let min_xcm_fee = 100; - // normal account cannot set min xcm fee. - assert_noop!( - AssetManager::set_min_xcm_fee( - Origin::signed([2u8; 32].into()), - manta_location.clone(), - min_xcm_fee, - ), - BadOrigin - ); + let min_xcm_fee = 100; + // normal account cannot set min xcm fee. + assert_noop!( + AssetManager::set_min_xcm_fee( + Origin::signed([2u8; 32].into()), + manta_location.clone(), + min_xcm_fee, + ), + BadOrigin + ); - // only sudo can set it. - assert_ok!(AssetManager::set_min_xcm_fee( - Origin::root(), - manta_location.clone(), - min_xcm_fee, - )); - assert_eq!( - crate::MinXcmFee::::get(&manta_location), - Some(min_xcm_fee) - ); + // only sudo can set it. + assert_ok!(AssetManager::set_min_xcm_fee( + Origin::root(), + manta_location.clone(), + min_xcm_fee, + )); + assert_eq!( + crate::MinXcmFee::::get(&manta_location), + Some(min_xcm_fee) + ); - // u128::MAX will be returned if min-xcm-fee is not set, - // that means your crosschain transaction will fail due to no one can pay u128::MAX. - let calamari_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( - 1, - X2(Parachain(2084), GeneralKey(b"KMA".to_vec())), - ))); + // u128::MAX will be returned if min-xcm-fee is not set, + // that means your crosschain transaction will fail due to no one can pay u128::MAX. + let calamari_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( + 1, + X2(Parachain(2084), GeneralKey(b"KMA".to_vec())), + ))); - assert_eq!( - crate::Pallet::::get( - &Into::>::into(calamari_location).unwrap() - ), - u128::MAX - ); - }) + assert_eq!( + crate::Pallet::::get( + &Into::>::into(calamari_location).unwrap() + ), + u128::MAX + ); + }) } diff --git a/pallets/asset-manager/src/weights.rs b/pallets/asset-manager/src/weights.rs index f76769d0e..950dc1421 100644 --- a/pallets/asset-manager/src/weights.rs +++ b/pallets/asset-manager/src/weights.rs @@ -1,16 +1,16 @@ // Copyright 2020-2022 Manta Network. // This file is part of Manta. - +// // Manta 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. - +// // Manta 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 Manta. If not, see . @@ -39,124 +39,124 @@ #![allow(unused_parens)] use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, + traits::Get, + weights::{constants::RocksDbWeight, Weight}, }; use sp_std::marker::PhantomData; /// Weight functions needed for pallet_asset_manager. pub trait WeightInfo { - fn register_asset() -> Weight; - fn set_units_per_second() -> Weight; - fn update_asset_location() -> Weight; - fn update_asset_metadata() -> Weight; - fn mint_asset() -> Weight; - fn set_min_xcm_fee() -> Weight; + fn register_asset() -> Weight; + fn set_units_per_second() -> Weight; + fn update_asset_location() -> Weight; + fn update_asset_metadata() -> Weight; + fn mint_asset() -> Weight; + fn set_min_xcm_fee() -> Weight; } /// Weights for pallet_asset_manager using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { - // Storage: AssetManager LocationAssetId (r:1 w:1) - // Storage: AssetManager NextAssetId (r:1 w:1) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Metadata (r:1 w:1) - // Storage: AssetManager AssetIdMetadata (r:0 w:1) - // Storage: AssetManager AssetIdLocation (r:0 w:1) - fn register_asset() -> Weight { - (42_259_000 as Weight) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(6 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: AssetManager UnitsPerSecond (r:0 w:1) - fn set_units_per_second() -> Weight { - (32_982_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:1) - // Storage: AssetManager LocationAssetId (r:1 w:2) - fn update_asset_location() -> Weight { - (42_570_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - // Storage: AssetManager AssetIdMetadata (r:0 w:1) - fn update_asset_metadata() -> Weight { - (44_964_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:1 w:1) - fn mint_asset() -> Weight { - (64_400_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: AssetManager MinXcmFee (r:0 w:1) - fn set_min_xcm_fee() -> Weight { - (31_000_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } + // Storage: AssetManager LocationAssetId (r:1 w:1) + // Storage: AssetManager NextAssetId (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + // Storage: AssetManager AssetIdLocation (r:0 w:1) + fn register_asset() -> Weight { + (42_259_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(6 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: AssetManager UnitsPerSecond (r:0 w:1) + fn set_units_per_second() -> Weight { + (32_982_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:1) + // Storage: AssetManager LocationAssetId (r:1 w:2) + fn update_asset_location() -> Weight { + (42_570_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + fn update_asset_metadata() -> Weight { + (44_964_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + fn mint_asset() -> Weight { + (64_400_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: AssetManager MinXcmFee (r:0 w:1) + fn set_min_xcm_fee() -> Weight { + (31_000_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: AssetManager LocationAssetId (r:1 w:1) - // Storage: AssetManager NextAssetId (r:1 w:1) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Metadata (r:1 w:1) - // Storage: AssetManager AssetIdMetadata (r:0 w:1) - // Storage: AssetManager AssetIdLocation (r:0 w:1) - fn register_asset() -> Weight { - (42_259_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(6 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: AssetManager UnitsPerSecond (r:0 w:1) - fn set_units_per_second() -> Weight { - (32_982_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:1) - // Storage: AssetManager LocationAssetId (r:1 w:2) - fn update_asset_location() -> Weight { - (42_570_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - // Storage: AssetManager AssetIdMetadata (r:0 w:1) - fn update_asset_metadata() -> Weight { - (44_964_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:1 w:1) - fn mint_asset() -> Weight { - (64_400_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: AssetManager MinXcmFee (r:0 w:1) - fn set_min_xcm_fee() -> Weight { - (31_000_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } + // Storage: AssetManager LocationAssetId (r:1 w:1) + // Storage: AssetManager NextAssetId (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + // Storage: AssetManager AssetIdLocation (r:0 w:1) + fn register_asset() -> Weight { + (42_259_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(6 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: AssetManager UnitsPerSecond (r:0 w:1) + fn set_units_per_second() -> Weight { + (32_982_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:1) + // Storage: AssetManager LocationAssetId (r:1 w:2) + fn update_asset_location() -> Weight { + (42_570_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + fn update_asset_metadata() -> Weight { + (44_964_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + fn mint_asset() -> Weight { + (64_400_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: AssetManager MinXcmFee (r:0 w:1) + fn set_min_xcm_fee() -> Weight { + (31_000_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } } diff --git a/pallets/collator-selection/Cargo.toml b/pallets/collator-selection/Cargo.toml index 770ae81d3..850802fbb 100644 --- a/pallets/collator-selection/Cargo.toml +++ b/pallets/collator-selection/Cargo.toml @@ -1,63 +1,63 @@ [package] -authors = ['Manta Network'] +authors = ['Manta Network'] description = 'Simple staking pallet with a fixed stake.' -edition = "2021" -homepage = 'https://manta.network' -license = 'GPL-3.0' -name = 'manta-collator-selection' -readme = 'README.md' -repository = 'https://github.com/Manta-Network/Manta/' -version = '3.2.0' +edition = "2021" +homepage = 'https://manta.network' +license = 'GPL-3.0' +name = 'manta-collator-selection' +readme = 'README.md' +repository = 'https://github.com/Manta-Network/Manta/' +version = '3.2.0' [package.metadata.docs.rs] targets = ['x86_64-unknown-linux-gnu'] [dependencies] -log = { version = "0.4.16", default-features = false } -codec = { version = '3.0.0', default-features = false, features = ['derive'], package = 'parity-scale-codec' } -rand = { version = "0.7.2", default-features = false } -scale-info = { version = "2.0.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.137", default-features = false } +codec = { version = '3.0.0', default-features = false, features = ['derive'], package = 'parity-scale-codec' } +log = { version = "0.4.16", default-features = false } +rand = { version = "0.7.2", default-features = false } +scale-info = { version = "2.0.0", default-features = false, features = ["derive"] } +serde = { version = "1.0.137", default-features = false } -sp-std = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } -sp-runtime = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } -sp-staking = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } -sp-arithmetic = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } -frame-support = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } -frame-system = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } -pallet-authorship = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } -pallet-session = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } +frame-support = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } +frame-system = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } +pallet-authorship = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } +pallet-session = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } +sp-arithmetic = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } +sp-runtime = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } +sp-staking = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } +sp-std = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } frame-benchmarking = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18", optional = true } [dev-dependencies] -sp-core = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } -sp-io = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } -sp-tracing = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } -sp-runtime = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } -pallet-timestamp = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } +pallet-aura = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } +pallet-balances = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } +pallet-timestamp = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sp-consensus-aura = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } -pallet-balances = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } -pallet-aura = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } +sp-core = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } +sp-io = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } +sp-runtime = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } +sp-tracing = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } [features] -default = ['std'] +default = ['std'] runtime-benchmarks = [ - 'frame-benchmarking', - 'frame-support/runtime-benchmarks', - 'frame-system/runtime-benchmarks', + 'frame-benchmarking', + 'frame-support/runtime-benchmarks', + 'frame-system/runtime-benchmarks', ] -std = [ - 'codec/std', - 'log/std', - 'scale-info/std', - 'rand/std', - 'sp-runtime/std', - 'sp-staking/std', - 'sp-std/std', - 'frame-support/std', - 'frame-system/std', - 'frame-benchmarking/std', - 'pallet-authorship/std', - 'pallet-session/std', +std = [ + 'codec/std', + 'log/std', + 'scale-info/std', + 'rand/std', + 'sp-runtime/std', + 'sp-staking/std', + 'sp-std/std', + 'frame-support/std', + 'frame-system/std', + 'frame-benchmarking/std', + 'pallet-authorship/std', + 'pallet-session/std', ] diff --git a/pallets/collator-selection/src/benchmarking.rs b/pallets/collator-selection/src/benchmarking.rs index 276297b49..b831b7936 100644 --- a/pallets/collator-selection/src/benchmarking.rs +++ b/pallets/collator-selection/src/benchmarking.rs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 Manta Network. +// Copyright 2020-2022 Manta Network. // This file is part of Manta. // // Manta is free software: you can redistribute it and/or modify @@ -22,9 +22,9 @@ use super::*; use crate::Pallet as CollatorSelection; use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite, whitelisted_caller}; use frame_support::{ - assert_ok, - codec::Decode, - traits::{Currency, EnsureOrigin, Get}, + assert_ok, + codec::Decode, + traits::{Currency, EnsureOrigin, Get}, }; use frame_system::{EventRecord, RawOrigin}; use pallet_authorship::EventHandler; @@ -33,304 +33,304 @@ use sp_arithmetic::Percent; use sp_std::prelude::*; pub type BalanceOf = - <::Currency as Currency<::AccountId>>::Balance; + <::Currency as Currency<::AccountId>>::Balance; const SEED: u32 = 0; // TODO: remove if this is given in substrate commit. macro_rules! whitelist { - ($acc:ident) => { - frame_benchmarking::benchmarking::add_to_whitelist( - frame_system::Account::::hashed_key_for(&$acc).into(), - ); - }; + ($acc:ident) => { + frame_benchmarking::benchmarking::add_to_whitelist( + frame_system::Account::::hashed_key_for(&$acc).into(), + ); + }; } fn assert_last_event(generic_event: ::Event) { - let events = frame_system::Pallet::::events(); - let system_event: ::Event = generic_event.into(); - // compare to the last event record - let EventRecord { event, .. } = &events[events.len() - 1]; - assert_eq!(event, &system_event); + let events = frame_system::Pallet::::events(); + let system_event: ::Event = generic_event.into(); + // compare to the last event record + let EventRecord { event, .. } = &events[events.len() - 1]; + assert_eq!(event, &system_event); } fn create_funded_user( - string: &'static str, - n: u32, - balance_factor: u32, + string: &'static str, + n: u32, + balance_factor: u32, ) -> T::AccountId { - let user = account(string, n, SEED); - let balance = T::Currency::minimum_balance() * balance_factor.into(); - let _ = T::Currency::make_free_balance_be(&user, balance); - user + let user = account(string, n, SEED); + let balance = T::Currency::minimum_balance() * balance_factor.into(); + let _ = T::Currency::make_free_balance_be(&user, balance); + user } fn keys(c: u32) -> ::Keys { - use rand::{RngCore, SeedableRng}; + use rand::{RngCore, SeedableRng}; - let keys = { - let mut keys = [0u8; 128]; + let keys = { + let mut keys = [0u8; 128]; - if c > 0 { - let mut rng = rand::rngs::StdRng::seed_from_u64(c as u64); - rng.fill_bytes(&mut keys); - } + if c > 0 { + let mut rng = rand::rngs::StdRng::seed_from_u64(c as u64); + rng.fill_bytes(&mut keys); + } - keys - }; + keys + }; - Decode::decode(&mut &keys[..]).unwrap() + Decode::decode(&mut &keys[..]).unwrap() } fn validator(c: u32) -> (T::AccountId, ::Keys) { - (create_funded_user::("candidate", c, 1000), keys::(c)) + (create_funded_user::("candidate", c, 1000), keys::(c)) } fn register_validators(count: u32) { - let validators = (0..count).map(|c| validator::(c)).collect::>(); + let validators = (0..count).map(|c| validator::(c)).collect::>(); - for (who, keys) in validators { - >::set_keys(RawOrigin::Signed(who).into(), keys, Vec::new()).unwrap(); - } + for (who, keys) in validators { + >::set_keys(RawOrigin::Signed(who).into(), keys, Vec::new()).unwrap(); + } } fn register_candidates(count: u32) { - let candidates = (0..count) - .map(|c| account("candidate", c, SEED)) - .collect::>(); - assert!( - >::get() > 0u32.into(), - "Bond cannot be zero!" - ); - - for who in candidates { - T::Currency::make_free_balance_be(&who, >::get() * 2u32.into()); - >::register_as_candidate(RawOrigin::Signed(who).into()).unwrap(); - } + let candidates = (0..count) + .map(|c| account("candidate", c, SEED)) + .collect::>(); + assert!( + >::get() > 0u32.into(), + "Bond cannot be zero!" + ); + + for who in candidates { + T::Currency::make_free_balance_be(&who, >::get() * 2u32.into()); + >::register_as_candidate(RawOrigin::Signed(who).into()).unwrap(); + } } benchmarks! { - where_clause { where T: pallet_authorship::Config + session::Config } - - set_invulnerables { - let b in 1 .. T::MaxInvulnerables::get(); - let new_invulnerables = (0..b).map(|c| account("candidate", c, SEED)).collect::>(); - let origin = T::UpdateOrigin::successful_origin(); - }: { - assert_ok!( - >::set_invulnerables(origin, new_invulnerables.clone()) - ); - } - verify { - assert_last_event::(Event::NewInvulnerables(new_invulnerables).into()); - } - - set_desired_candidates { - let max: u32 = 999; - let origin = T::UpdateOrigin::successful_origin(); - }: { - assert_ok!( - >::set_desired_candidates(origin, max) - ); - } - verify { - assert_last_event::(Event::NewDesiredCandidates(max).into()); - } - - set_candidacy_bond { - let bond: BalanceOf = T::Currency::minimum_balance() * 10u32.into(); - let origin = T::UpdateOrigin::successful_origin(); - }: { - assert_ok!( - >::set_candidacy_bond(origin, bond) - ); - } - verify { - assert_last_event::(Event::NewCandidacyBond(bond).into()); - } - - set_eviction_baseline { - let percentile = Percent::from_percent(80u8); - let origin = T::UpdateOrigin::successful_origin(); - }: { - assert_ok!( - >::set_eviction_baseline(origin, percentile) - ); - } - verify { - assert_last_event::(Event::NewEvictionBaseline(percentile).into()); - } - - set_eviction_tolerance { - let percentage = Percent::from_percent(10u8); - let origin = T::UpdateOrigin::successful_origin(); - }: { - assert_ok!( - >::set_eviction_tolerance(origin, percentage) - ); - } - verify { - assert_last_event::(Event::NewEvictionTolerance(percentage).into()); - } - - // worse case is when we have all the max-candidate slots filled except one, and we fill that - // one. - register_as_candidate { - let c in 1 .. T::MaxCandidates::get(); - - >::put(T::Currency::minimum_balance()); - >::put(c + 1); - - register_validators::(c); - register_candidates::(c); - - let caller: T::AccountId = whitelisted_caller(); - let bond: BalanceOf = T::Currency::minimum_balance() * 2u32.into(); - T::Currency::make_free_balance_be(&caller, bond); - - >::set_keys( - RawOrigin::Signed(caller.clone()).into(), - keys::(c + 1), - Vec::new() - ).unwrap(); - - }: _(RawOrigin::Signed(caller.clone())) - verify { - assert_last_event::(Event::CandidateAdded(caller, bond / 2u32.into()).into()); - } - - // worse case is the last candidate leaving. - leave_intent { - let c in 1 .. T::MaxCandidates::get(); - >::put(T::Currency::minimum_balance()); - >::put(c); - - register_validators::(c); - register_candidates::(c); - - let leaving = >::get().last().unwrap().who.clone(); - whitelist!(leaving); - }: _(RawOrigin::Signed(leaving.clone())) - verify { - assert_last_event::(Event::CandidateRemoved(leaving).into()); - } - - // worse case is the last candidate leaving. - remove_collator { - let c in 1 .. T::MaxCandidates::get(); - >::put(T::Currency::minimum_balance()); - >::put(c); - - register_validators::(c); - register_candidates::(c); - - let leaving = >::get().last().unwrap().who.clone(); - whitelist!(leaving); - let origin = T::UpdateOrigin::successful_origin(); - }: { - assert_ok!( - >::remove_collator(origin, leaving.clone()) - ); - } - verify { - assert_last_event::(Event::CandidateRemoved(leaving).into()); - } - - // worse case is when we have all the max-candidate slots filled except one, and we fill that - // one. - register_candidate { - let c in 1 .. T::MaxCandidates::get(); - - >::put(T::Currency::minimum_balance()); - >::put(c + 1); - - register_validators::(c); - register_candidates::(c); - - let caller: T::AccountId = whitelisted_caller(); - let bond: BalanceOf = T::Currency::minimum_balance() * 2u32.into(); - T::Currency::make_free_balance_be(&caller, bond); - - >::set_keys( - RawOrigin::Signed(caller.clone()).into(), - keys::(c + 1), - Vec::new() - ).unwrap(); - - let origin = T::UpdateOrigin::successful_origin(); - }: { - assert_ok!( - >::register_candidate(origin, caller.clone()) - ); - } - verify { - assert_last_event::(Event::CandidateAdded(caller, bond / 2u32.into()).into()); - } - - // worse case is paying a non-existing candidate account. - note_author { - >::put(T::Currency::minimum_balance()); - T::Currency::make_free_balance_be( - &>::account_id(), - T::Currency::minimum_balance() * 4u32.into(), - ); - let author = account("author", 0, SEED); - let new_block: T::BlockNumber = 10u32.into(); - - frame_system::Pallet::::set_block_number(new_block); - assert!(T::Currency::free_balance(&author) == 0u32.into()); - }: { - as EventHandler<_, _>>::note_author(author.clone()) - } verify { - assert!(T::Currency::free_balance(&author) > 0u32.into()); - assert_eq!(frame_system::Pallet::::block_number(), new_block); - } - - // worst case for new session. - new_session { - let c in 1 .. T::MaxCandidates::get(); - - >::put(T::Currency::minimum_balance()); - >::put(Percent::from_percent(100)); // Consider all collators - >::put(Percent::from_percent(0)); // Kick anyone not at perfect performance - >::put(c); - frame_system::Pallet::::set_block_number(0u32.into()); - - let p = >::eviction_baseline(); - register_validators::(c); - register_candidates::(c); - - let new_block = 1800u32; - let zero_block = 0u32; - let candidates = >::get(); - - let underperformers = &candidates[0..candidates.len()-1]; - let top_performer = &candidates[candidates.len()-1]; - - // worst case: everyone but one collator underperforms and must be removed - for up in underperformers{ - >::insert(up.who.clone(), zero_block); - } - >::insert(top_performer.who.clone(), new_block); - - let pre_length = >::get().len(); - - frame_system::Pallet::::set_block_number(new_block.into()); - - assert!(>::get().len() == c as usize); - }: { - as SessionManager<_>>::new_session(0) - } verify { - if c > 1 { - assert!(>::get().len() < pre_length); - } else { - assert!(>::get().len() == pre_length); - } - } + where_clause { where T: pallet_authorship::Config + session::Config } + + set_invulnerables { + let b in 1 .. T::MaxInvulnerables::get(); + let new_invulnerables = (0..b).map(|c| account("candidate", c, SEED)).collect::>(); + let origin = T::UpdateOrigin::successful_origin(); + }: { + assert_ok!( + >::set_invulnerables(origin, new_invulnerables.clone()) + ); + } + verify { + assert_last_event::(Event::NewInvulnerables(new_invulnerables).into()); + } + + set_desired_candidates { + let max: u32 = 999; + let origin = T::UpdateOrigin::successful_origin(); + }: { + assert_ok!( + >::set_desired_candidates(origin, max) + ); + } + verify { + assert_last_event::(Event::NewDesiredCandidates(max).into()); + } + + set_candidacy_bond { + let bond: BalanceOf = T::Currency::minimum_balance() * 10u32.into(); + let origin = T::UpdateOrigin::successful_origin(); + }: { + assert_ok!( + >::set_candidacy_bond(origin, bond) + ); + } + verify { + assert_last_event::(Event::NewCandidacyBond(bond).into()); + } + + set_eviction_baseline { + let percentile = Percent::from_percent(80u8); + let origin = T::UpdateOrigin::successful_origin(); + }: { + assert_ok!( + >::set_eviction_baseline(origin, percentile) + ); + } + verify { + assert_last_event::(Event::NewEvictionBaseline(percentile).into()); + } + + set_eviction_tolerance { + let percentage = Percent::from_percent(10u8); + let origin = T::UpdateOrigin::successful_origin(); + }: { + assert_ok!( + >::set_eviction_tolerance(origin, percentage) + ); + } + verify { + assert_last_event::(Event::NewEvictionTolerance(percentage).into()); + } + + // worse case is when we have all the max-candidate slots filled except one, and we fill that + // one. + register_as_candidate { + let c in 1 .. T::MaxCandidates::get(); + + >::put(T::Currency::minimum_balance()); + >::put(c + 1); + + register_validators::(c); + register_candidates::(c); + + let caller: T::AccountId = whitelisted_caller(); + let bond: BalanceOf = T::Currency::minimum_balance() * 2u32.into(); + T::Currency::make_free_balance_be(&caller, bond); + + >::set_keys( + RawOrigin::Signed(caller.clone()).into(), + keys::(c + 1), + Vec::new() + ).unwrap(); + + }: _(RawOrigin::Signed(caller.clone())) + verify { + assert_last_event::(Event::CandidateAdded(caller, bond / 2u32.into()).into()); + } + + // worse case is the last candidate leaving. + leave_intent { + let c in 1 .. T::MaxCandidates::get(); + >::put(T::Currency::minimum_balance()); + >::put(c); + + register_validators::(c); + register_candidates::(c); + + let leaving = >::get().last().unwrap().who.clone(); + whitelist!(leaving); + }: _(RawOrigin::Signed(leaving.clone())) + verify { + assert_last_event::(Event::CandidateRemoved(leaving).into()); + } + + // worse case is the last candidate leaving. + remove_collator { + let c in 1 .. T::MaxCandidates::get(); + >::put(T::Currency::minimum_balance()); + >::put(c); + + register_validators::(c); + register_candidates::(c); + + let leaving = >::get().last().unwrap().who.clone(); + whitelist!(leaving); + let origin = T::UpdateOrigin::successful_origin(); + }: { + assert_ok!( + >::remove_collator(origin, leaving.clone()) + ); + } + verify { + assert_last_event::(Event::CandidateRemoved(leaving).into()); + } + + // worse case is when we have all the max-candidate slots filled except one, and we fill that + // one. + register_candidate { + let c in 1 .. T::MaxCandidates::get(); + + >::put(T::Currency::minimum_balance()); + >::put(c + 1); + + register_validators::(c); + register_candidates::(c); + + let caller: T::AccountId = whitelisted_caller(); + let bond: BalanceOf = T::Currency::minimum_balance() * 2u32.into(); + T::Currency::make_free_balance_be(&caller, bond); + + >::set_keys( + RawOrigin::Signed(caller.clone()).into(), + keys::(c + 1), + Vec::new() + ).unwrap(); + + let origin = T::UpdateOrigin::successful_origin(); + }: { + assert_ok!( + >::register_candidate(origin, caller.clone()) + ); + } + verify { + assert_last_event::(Event::CandidateAdded(caller, bond / 2u32.into()).into()); + } + + // worse case is paying a non-existing candidate account. + note_author { + >::put(T::Currency::minimum_balance()); + T::Currency::make_free_balance_be( + &>::account_id(), + T::Currency::minimum_balance() * 4u32.into(), + ); + let author = account("author", 0, SEED); + let new_block: T::BlockNumber = 10u32.into(); + + frame_system::Pallet::::set_block_number(new_block); + assert!(T::Currency::free_balance(&author) == 0u32.into()); + }: { + as EventHandler<_, _>>::note_author(author.clone()) + } verify { + assert!(T::Currency::free_balance(&author) > 0u32.into()); + assert_eq!(frame_system::Pallet::::block_number(), new_block); + } + + // worst case for new session. + new_session { + let c in 1 .. T::MaxCandidates::get(); + + >::put(T::Currency::minimum_balance()); + >::put(Percent::from_percent(100)); // Consider all collators + >::put(Percent::from_percent(0)); // Kick anyone not at perfect performance + >::put(c); + frame_system::Pallet::::set_block_number(0u32.into()); + + let p = >::eviction_baseline(); + register_validators::(c); + register_candidates::(c); + + let new_block = 1800u32; + let zero_block = 0u32; + let candidates = >::get(); + + let underperformers = &candidates[0..candidates.len()-1]; + let top_performer = &candidates[candidates.len()-1]; + + // worst case: everyone but one collator underperforms and must be removed + for up in underperformers{ + >::insert(up.who.clone(), zero_block); + } + >::insert(top_performer.who.clone(), new_block); + + let pre_length = >::get().len(); + + frame_system::Pallet::::set_block_number(new_block.into()); + + assert!(>::get().len() == c as usize); + }: { + as SessionManager<_>>::new_session(0) + } verify { + if c > 1 { + assert!(>::get().len() < pre_length); + } else { + assert!(>::get().len() == pre_length); + } + } } impl_benchmark_test_suite!( - CollatorSelection, - crate::mock::new_test_ext(), - crate::mock::Test, + CollatorSelection, + crate::mock::new_test_ext(), + crate::mock::Test, ); diff --git a/pallets/collator-selection/src/lib.rs b/pallets/collator-selection/src/lib.rs index 3a0e99a3c..61a85e74d 100644 --- a/pallets/collator-selection/src/lib.rs +++ b/pallets/collator-selection/src/lib.rs @@ -77,641 +77,642 @@ pub mod weights; #[frame_support::pallet] pub mod pallet { - pub use crate::weights::WeightInfo; - use core::ops::Div; - use frame_support::{ - dispatch::DispatchResultWithPostInfo, - inherent::Vec, - pallet_prelude::*, - sp_runtime::{ - traits::{AccountIdConversion, CheckedSub, Convert, One, Zero}, - RuntimeDebug, - }, - traits::{ - Currency, EnsureOrigin, ExistenceRequirement::KeepAlive, ReservableCurrency, - StorageVersion, ValidatorRegistration, ValidatorSet, - }, - weights::DispatchClass, - PalletId, - }; - use frame_system::{pallet_prelude::*, Config as SystemConfig}; - use pallet_session::SessionManager; - use sp_arithmetic::Percent; - use sp_staking::SessionIndex; - - type BalanceOf = - <::Currency as Currency<::AccountId>>::Balance; - - /// A convertor from collators id. Since this pallet does not have stash/controller, this is - /// just identity. - pub struct IdentityCollator; - impl sp_runtime::traits::Convert> for IdentityCollator { - fn convert(t: T) -> Option { - Some(t) - } - } - impl sp_runtime::traits::Convert for IdentityCollator { - fn convert(t: T) -> T { - t - } - } - - const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); - - /// Configure the pallet by specifying the parameters and types on which it depends. - #[pallet::config] - pub trait Config: frame_system::Config { - /// Overarching event type. - type Event: From> + IsType<::Event>; - - /// The currency mechanism. - type Currency: ReservableCurrency; - - /// Origin that can dictate updating parameters of this pallet. - type UpdateOrigin: EnsureOrigin; - - /// Account Identifier from which the internal Pot is generated. - type PotId: Get; - - /// Maximum number of candidates that we should have. This is used for benchmarking and is not - /// enforced. - /// - /// This does not take into account the invulnerables. - type MaxCandidates: Get; - - /// Maximum number of invulnerables. - /// - /// Used only for benchmarking. - type MaxInvulnerables: Get; - - /// A stable ID for a validator. - type ValidatorId: Member - + Parameter - + From<>::ValidatorId>; - - /// A conversion from account ID to validator ID. - /// - /// Its cost must be at most one storage read. - type ValidatorIdOf: Convert>; - type AccountIdOf: Convert; - - /// Validate a user is registered - type ValidatorRegistration: ValidatorRegistration - + ValidatorSet; - - /// The weight information of this pallet. - type WeightInfo: WeightInfo; - } - - /// Basic information about a collation candidate. - #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, scale_info::TypeInfo)] - pub struct CandidateInfo { - /// Account identifier. - pub who: AccountId, - /// Reserved deposit. - pub deposit: Balance, - } - - #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] - #[pallet::storage_version(STORAGE_VERSION)] - #[pallet::without_storage_info] - pub struct Pallet(_); - - /// The invulnerable, fixed collators. - #[pallet::storage] - #[pallet::getter(fn invulnerables)] - pub type Invulnerables = StorageValue<_, Vec, ValueQuery>; - - /// The (community, limited) collation candidates. - #[pallet::storage] - #[pallet::getter(fn candidates)] - pub type Candidates = - StorageValue<_, Vec>>, ValueQuery>; - - pub(super) type BlockCount = u32; - #[pallet::type_value] - pub(super) fn StartingBlockCount() -> BlockCount { - Zero::zero() - } - #[pallet::storage] - pub(super) type BlocksPerCollatorThisSession = - StorageMap<_, Blake2_128Concat, T::AccountId, BlockCount, ValueQuery, StartingBlockCount>; - - /// Performance percentile to use as baseline for collator eviction - #[pallet::storage] - #[pallet::getter(fn eviction_baseline)] - pub type EvictionBaseline = StorageValue<_, Percent, ValueQuery>; - - /// Percentage of underperformance to _tolerate_ before evicting a collator - /// - /// i.e. A collator gets evicted if it produced _less_ than x% fewer blocks than the collator at EvictionBaseline - #[pallet::storage] - #[pallet::getter(fn eviction_tolerance)] - pub type EvictionTolerance = StorageValue<_, Percent, ValueQuery>; - - /// Desired number of candidates. - /// - /// This should ideally always be less than [`Config::MaxCandidates`] for weights to be correct. - #[pallet::storage] - #[pallet::getter(fn desired_candidates)] - pub type DesiredCandidates = StorageValue<_, u32, ValueQuery>; - - /// Fixed deposit bond for each candidate. - #[pallet::storage] - #[pallet::getter(fn candidacy_bond)] - pub type CandidacyBond = StorageValue<_, BalanceOf, ValueQuery>; - - #[pallet::genesis_config] - pub struct GenesisConfig { - pub invulnerables: Vec, - pub candidacy_bond: BalanceOf, - pub eviction_baseline: Percent, - pub eviction_tolerance: Percent, - pub desired_candidates: u32, - } - - #[cfg(feature = "std")] - impl Default for GenesisConfig { - fn default() -> Self { - Self { - invulnerables: Default::default(), - candidacy_bond: Default::default(), - eviction_baseline: Percent::zero(), // Note: eviction disabled by default - eviction_tolerance: Percent::one(), // Note: eviction disabled by default - desired_candidates: Default::default(), - } - } - } - - #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { - fn build(&self) { - let duplicate_invulnerables = self - .invulnerables - .iter() - .collect::>(); - assert!( - duplicate_invulnerables.len() == self.invulnerables.len(), - "duplicate invulnerables in genesis." - ); - - assert!( - T::MaxInvulnerables::get() >= (self.invulnerables.len() as u32), - "genesis invulnerables are more than T::MaxInvulnerables", - ); - assert!( - T::MaxCandidates::get() >= self.desired_candidates, - "genesis desired_candidates are more than T::MaxCandidates", - ); - assert!( - self.eviction_baseline <= Percent::one(), - "Eviction baseline must be given as a percentile - number between 0 and 100", - ); - assert!( - self.eviction_tolerance <= Percent::one(), - "Eviction tolerance must be given as a percentage - number between 0 and 100", - ); - >::put(&self.desired_candidates); - >::put(&self.candidacy_bond); - >::put(&self.eviction_baseline); - >::put(&self.eviction_tolerance); - >::put(&self.invulnerables); - } - } - - #[pallet::event] - #[pallet::generate_deposit(pub(super) fn deposit_event)] - pub enum Event { - NewInvulnerables(Vec), - NewDesiredCandidates(u32), - NewCandidacyBond(BalanceOf), - CandidateAdded(T::AccountId, BalanceOf), - CandidateRemoved(T::AccountId), - NewEvictionBaseline(Percent), - NewEvictionTolerance(Percent), - } - - // Errors inform users that something went wrong. - #[pallet::error] - pub enum Error { - /// Too many candidates - TooManyCandidates, - /// Unknown error - Unknown, - /// Permission issue - Permission, - /// User is already a candidate - AlreadyCandidate, - /// User is not a candidate - NotCandidate, - /// User is already an Invulnerable - AlreadyInvulnerable, - /// Account has no associated validator ID - NoAssociatedValidatorId, - /// Validator ID is not yet registered - ValidatorNotRegistered, - /// Removing invulnerable collators is not allowed - NotAllowRemoveInvulnerable, - } - - #[pallet::hooks] - impl Hooks> for Pallet {} - - #[pallet::call] - impl Pallet { - /// Set candidate collator as invulnerable. - /// - /// `new`: candidate collator. - #[pallet::weight(T::WeightInfo::set_invulnerables(new.len() as u32))] - pub fn set_invulnerables( - origin: OriginFor, - new: Vec, - ) -> DispatchResultWithPostInfo { - T::UpdateOrigin::ensure_origin(origin)?; - // we trust origin calls, this is just a for more accurate benchmarking - if (new.len() as u32) > T::MaxInvulnerables::get() { - log::warn!( - "invulnerables > T::MaxInvulnerables; you might need to run benchmarks again" - ); - } - >::put(&new); - Self::deposit_event(Event::NewInvulnerables(new)); - Ok(().into()) - } - - /// Set how many candidate collator are allowed. - /// - /// `max`: The max number of candidates. - #[pallet::weight(T::WeightInfo::set_desired_candidates())] - pub fn set_desired_candidates( - origin: OriginFor, - max: u32, - ) -> DispatchResultWithPostInfo { - T::UpdateOrigin::ensure_origin(origin)?; - // we trust origin calls, this is just a for more accurate benchmarking - if max > T::MaxCandidates::get() { - log::warn!("max > T::MaxCandidates; you might need to run benchmarks again"); - } - >::put(&max); - Self::deposit_event(Event::NewDesiredCandidates(max)); - Ok(().into()) - } - - /// Set the amount held on reserved for candidate collator. - /// - /// `bond`: The amount held on reserved. - #[pallet::weight(T::WeightInfo::set_candidacy_bond())] - pub fn set_candidacy_bond( - origin: OriginFor, - bond: BalanceOf, - ) -> DispatchResultWithPostInfo { - T::UpdateOrigin::ensure_origin(origin)?; - >::put(&bond); - Self::deposit_event(Event::NewCandidacyBond(bond)); - Ok(().into()) - } - - /// Register as candidate collator. - #[pallet::weight(T::WeightInfo::register_as_candidate(T::MaxCandidates::get()))] - pub fn register_as_candidate(origin: OriginFor) -> DispatchResultWithPostInfo { - let who = ensure_signed(origin)?; - - // ensure we are below limit. - let length = >::decode_len().unwrap_or_default(); - ensure!( - (length as u32) < Self::desired_candidates(), - Error::::TooManyCandidates - ); - ensure!( - !Self::invulnerables().contains(&who), - Error::::AlreadyInvulnerable - ); - - let validator_key = T::ValidatorIdOf::convert(who.clone()) - .ok_or(Error::::NoAssociatedValidatorId)?; - ensure!( - T::ValidatorRegistration::is_registered(&validator_key), - Error::::ValidatorNotRegistered - ); - - let deposit = Self::candidacy_bond(); - // First authored block is current block plus kick threshold to handle session delay - let incoming = CandidateInfo { - who: who.clone(), - deposit, - }; - - let current_count = - >::try_mutate(|candidates| -> Result { - if candidates.iter_mut().any(|candidate| candidate.who == who) { - Err(Error::::AlreadyCandidate.into()) - } else { - T::Currency::reserve(&who, deposit)?; - candidates.push(incoming); - Ok(candidates.len()) - } - })?; - - Self::deposit_event(Event::CandidateAdded(who, deposit)); - Ok(Some(T::WeightInfo::register_as_candidate(current_count as u32)).into()) - } - - /// Register an specified candidate as collator. - /// - /// - `new_candidate`: Who is going to be collator. - #[pallet::weight(T::WeightInfo::register_candidate(T::MaxCandidates::get()))] - pub fn register_candidate( - origin: OriginFor, - new_candidate: T::AccountId, - ) -> DispatchResultWithPostInfo { - T::UpdateOrigin::ensure_origin(origin)?; - - // ensure we are below limit. - let length = >::decode_len().unwrap_or_default(); - ensure!( - (length as u32) < Self::desired_candidates(), - Error::::TooManyCandidates - ); - ensure!( - !Self::invulnerables().contains(&new_candidate), - Error::::AlreadyInvulnerable - ); - - let validator_key = T::ValidatorIdOf::convert(new_candidate.clone()) - .ok_or(Error::::NoAssociatedValidatorId)?; - ensure!( - T::ValidatorRegistration::is_registered(&validator_key), - Error::::ValidatorNotRegistered - ); - - let deposit = Self::candidacy_bond(); - let incoming = CandidateInfo { - who: new_candidate.clone(), - deposit, - }; - - let current_count = - >::try_mutate(|candidates| -> Result { - if candidates - .iter_mut() - .any(|candidate| candidate.who == new_candidate) - { - Err(Error::::AlreadyCandidate.into()) - } else { - T::Currency::reserve(&new_candidate, deposit)?; - candidates.push(incoming); - Ok(candidates.len()) - } - })?; - - Self::deposit_event(Event::CandidateAdded(new_candidate, deposit)); - Ok(Some(T::WeightInfo::register_candidate(current_count as u32)).into()) - } - - /// Leave from collator set. - #[pallet::weight(T::WeightInfo::leave_intent(T::MaxCandidates::get()))] - pub fn leave_intent(origin: OriginFor) -> DispatchResultWithPostInfo { - let who = ensure_signed(origin)?; - let current_count = Self::try_remove_candidate(&who)?; - - Ok(Some(T::WeightInfo::leave_intent(current_count as u32)).into()) - } - - /// Remove an specified collator. - /// - /// - `collator`: Who is going to be remove from collators set. - #[pallet::weight(T::WeightInfo::remove_collator(T::MaxCandidates::get()))] - pub fn remove_collator( - origin: OriginFor, - collator: T::AccountId, - ) -> DispatchResultWithPostInfo { - T::UpdateOrigin::ensure_origin(origin)?; - - // not allow to remove invulnerables - ensure!( - !>::get().contains(&collator), - Error::::NotAllowRemoveInvulnerable - ); - - let current_count = Self::try_remove_candidate(&collator)?; - - Ok(Some(T::WeightInfo::remove_collator(current_count as u32)).into()) - } - - /// Set the collator performance percentile used as baseline for eviction - /// - /// `percentile`: x-th percentile of collator performance to use as eviction baseline - #[pallet::weight(T::WeightInfo::set_eviction_baseline())] - pub fn set_eviction_baseline( - origin: OriginFor, - percentile: Percent, - ) -> DispatchResultWithPostInfo { - T::UpdateOrigin::ensure_origin(origin)?; - >::put(percentile); // NOTE: from_percent saturates at 100 - Self::deposit_event(Event::NewEvictionBaseline(percentile)); - Ok(().into()) - } - - /// Set the tolerated underperformance percentage before evicting - /// - /// `percentage`: x% of missed blocks under eviction_baseline to tolerate - #[pallet::weight(T::WeightInfo::set_eviction_tolerance())] - pub fn set_eviction_tolerance( - origin: OriginFor, - percentage: Percent, - ) -> DispatchResultWithPostInfo { - T::UpdateOrigin::ensure_origin(origin)?; - >::put(percentage); // NOTE: from_percent saturates at 100 - Self::deposit_event(Event::NewEvictionTolerance(percentage)); - Ok(().into()) - } - } - - impl Pallet { - /// Get a unique, inaccessible account id from the `PotId`. - pub fn account_id() -> T::AccountId { - T::PotId::get().into_account() - } - - /// Removes a candidate if they exist and sends them back their deposit - fn try_remove_candidate(who: &T::AccountId) -> Result { - let current_count = - >::try_mutate(|candidates| -> Result { - let index = candidates - .iter() - .position(|candidate| candidate.who == *who) - .ok_or(Error::::NotCandidate)?; - T::Currency::unreserve(who, candidates[index].deposit); - candidates.remove(index); - Ok(candidates.len()) - })?; - Self::deposit_event(Event::CandidateRemoved(who.clone())); - Ok(current_count) - } - - /// Assemble the current set of candidates and invulnerables into the next collator set. - /// - /// This is done on the fly, as frequent as we are told to do so, as the session manager. - pub fn assemble_collators(candidates: Vec) -> Vec { - let mut collators = Self::invulnerables(); - collators.extend(candidates.into_iter().collect::>()); - collators - } - - /// Removes collators with unsatisfactory performance - /// Returns the removed AccountIds - pub fn evict_bad_collators( - candidates: Vec>>, - ) -> Vec { - use sp_runtime::PerThing; - - // 0. Storage reads and precondition checks - if candidates.is_empty() { - return Vec::new(); // No candidates means we're running invulnerables only - } - let percentile_for_kick = Self::eviction_baseline(); - if percentile_for_kick == Percent::zero() { - return Vec::new(); // Selecting 0-th percentile disables kicking. Upper bound check in fn build() - } - let underperformance_tolerated = Self::eviction_tolerance(); - if underperformance_tolerated == Percent::one() { - return Vec::new(); // tolerating 100% underperformance disables kicking - } - let mut collator_perf_this_session = - >::iter().collect::>(); - if collator_perf_this_session.is_empty() { - return Vec::new(); // no validator performance recorded ( should not happen ) - } - - // 1. Ascending sort of collator performance list by number of produced blocks - collator_perf_this_session.sort_unstable_by_key(|k| k.1); - let collator_count = collator_perf_this_session.len(); - - // 2. get percentile by _exclusive_ nearest rank method https://en.wikipedia.org/wiki/Percentile#The_nearest-rank_method (rust percentile API is feature gated and unstable) - let ordinal_rank = percentile_for_kick.mul_ceil(collator_count); - let index_at_ordinal_rank = ordinal_rank.saturating_sub(One::one()); // -1 to accomodate 0-index counting, should not saturate due to precondition check and round up multiplication - - // 3. Block number at rank is the percentile and our kick performance benchmark - let blocks_created_at_baseline: BlockCount = - collator_perf_this_session[index_at_ordinal_rank].1; - - // 4. We kick if a collator produced fewer than (EvictionTolerance * EvictionBaseline rounded up) blocks than the percentile - let evict_below_blocks = (underperformance_tolerated - .left_from_one() - .mul_ceil(blocks_created_at_baseline)) as BlockCount; - log::trace!( - "Session Performance stats: {}-th percentile: {:?} blocks. Evicting collators who produced less than {} blocks", - percentile_for_kick.mul_ceil(100u8), - blocks_created_at_baseline, - evict_below_blocks - ); - - // 5. Walk the percentile slice, call try_remove_candidate if a collator is under threshold - let kick_candidates = &collator_perf_this_session[..index_at_ordinal_rank]; // ordinal-rank exclusive, the collator at percentile is safe - let mut removed_account_ids: Vec = - Vec::with_capacity(kick_candidates.len()); - kick_candidates.iter().for_each(|(acc_id, my_blocks_this_session)| { - if *my_blocks_this_session < evict_below_blocks { - // If our validator is not also a candidate we're invulnerable or already kicked - if candidates.iter().any(|x| x.who == *acc_id) { - Self::try_remove_candidate(acc_id) - .and_then(|_| { - removed_account_ids.push(acc_id.clone()); - log::info!("Removed collator of account {:?} as it only produced {} blocks this session which is below acceptable threshold of {}", &acc_id, my_blocks_this_session,evict_below_blocks); - Ok(()) - }) - .unwrap_or_else(|why| { - log::warn!("Failed to remove candidate due to underperformance {:?}", why); - debug_assert!(false, "failed to remove candidate {:?}", why); - }); - } - } - }); - removed_account_ids.shrink_to_fit(); - removed_account_ids - } - - /// Reset the performance map to the currently active validators at 0 blocks - pub fn reset_collator_performance() { - >::remove_all(None); - let validators = T::ValidatorRegistration::validators(); - for validator_id in validators { - let account_id = T::AccountIdOf::convert(validator_id.clone().into()); - >::insert(account_id.clone(), 0u32); - } - } - } - - /// Keep track of number of authored blocks per authority, uncles are counted as well since - /// they're a valid proof of being online. - impl - pallet_authorship::EventHandler for Pallet - { - fn note_author(author: T::AccountId) { - let pot = Self::account_id(); - // assumes an ED will be sent to pot. - let reward = T::Currency::free_balance(&pot) - .checked_sub(&T::Currency::minimum_balance()) - .unwrap_or_else(Zero::zero) - .div(2u32.into()); - // `reward` is half of pot account minus ED, this should never fail. - let _success = T::Currency::transfer(&pot, &author, reward, KeepAlive); - debug_assert!(_success.is_ok()); - - // increment blocks this node authored - >::mutate(&author, |blocks| { - *blocks = blocks.saturating_add(One::one()); - }); - - frame_system::Pallet::::register_extra_weight_unchecked( - T::WeightInfo::note_author(), - DispatchClass::Mandatory, - ); - } - - fn note_uncle(_author: T::AccountId, _age: T::BlockNumber) { - //TODO can we ignore this? - } - } - - /// Play the role of the session manager. - impl SessionManager for Pallet { - fn new_session(index: SessionIndex) -> Option> { - log::info!( - "assembling new collators for new session {} at #{:?}", - index, - >::block_number(), - ); - - let candidates = Self::candidates(); - let candidates_len_before = candidates.len(); - let removed_candidate_ids = Self::evict_bad_collators(candidates.clone()); - let active_candidate_ids = candidates - .iter() - .filter_map(|x| { - if removed_candidate_ids.contains(&x.who) { - None - } else { - Some(x.who.clone()) - } - }) - .collect::>(); - let result = Self::assemble_collators(active_candidate_ids); - - frame_system::Pallet::::register_extra_weight_unchecked( - T::WeightInfo::new_session(candidates_len_before as u32), - DispatchClass::Mandatory, - ); - - Self::reset_collator_performance(); // Reset performance map for the now starting session's active validatorset - Some(result) - } - fn start_session(_: SessionIndex) { - // we don't care. - } - fn end_session(_: SessionIndex) { - // we don't care. - } - } + pub use crate::weights::WeightInfo; + use core::ops::Div; + use frame_support::{ + dispatch::DispatchResultWithPostInfo, + inherent::Vec, + pallet_prelude::*, + sp_runtime::{ + traits::{AccountIdConversion, CheckedSub, Convert, One, Zero}, + RuntimeDebug, + }, + traits::{ + Currency, EnsureOrigin, ExistenceRequirement::KeepAlive, ReservableCurrency, + StorageVersion, ValidatorRegistration, ValidatorSet, + }, + weights::DispatchClass, + PalletId, + }; + use frame_system::{pallet_prelude::*, Config as SystemConfig}; + use pallet_session::SessionManager; + use sp_arithmetic::Percent; + use sp_staking::SessionIndex; + + type BalanceOf = + <::Currency as Currency<::AccountId>>::Balance; + + /// A convertor from collators id. Since this pallet does not have stash/controller, this is + /// just identity. + pub struct IdentityCollator; + impl sp_runtime::traits::Convert> for IdentityCollator { + fn convert(t: T) -> Option { + Some(t) + } + } + impl sp_runtime::traits::Convert for IdentityCollator { + fn convert(t: T) -> T { + t + } + } + + const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); + + /// Configure the pallet by specifying the parameters and types on which it depends. + #[pallet::config] + pub trait Config: frame_system::Config { + /// Overarching event type. + type Event: From> + IsType<::Event>; + + /// The currency mechanism. + type Currency: ReservableCurrency; + + /// Origin that can dictate updating parameters of this pallet. + type UpdateOrigin: EnsureOrigin; + + /// Account Identifier from which the internal Pot is generated. + type PotId: Get; + + /// Maximum number of candidates that we should have. This is used for benchmarking and is not + /// enforced. + /// + /// This does not take into account the invulnerables. + type MaxCandidates: Get; + + /// Maximum number of invulnerables. + /// + /// Used only for benchmarking. + type MaxInvulnerables: Get; + + /// A stable ID for a validator. + type ValidatorId: Member + + Parameter + + From<>::ValidatorId>; + + /// A conversion from account ID to validator ID. + /// + /// Its cost must be at most one storage read. + type ValidatorIdOf: Convert>; + type AccountIdOf: Convert; + + /// Validate a user is registered + type ValidatorRegistration: ValidatorRegistration + + ValidatorSet; + + /// The weight information of this pallet. + type WeightInfo: WeightInfo; + } + + /// Basic information about a collation candidate. + #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, scale_info::TypeInfo)] + pub struct CandidateInfo { + /// Account identifier. + pub who: AccountId, + /// Reserved deposit. + pub deposit: Balance, + } + + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + #[pallet::storage_version(STORAGE_VERSION)] + #[pallet::without_storage_info] + pub struct Pallet(_); + + /// The invulnerable, fixed collators. + #[pallet::storage] + #[pallet::getter(fn invulnerables)] + pub type Invulnerables = StorageValue<_, Vec, ValueQuery>; + + /// The (community, limited) collation candidates. + #[pallet::storage] + #[pallet::getter(fn candidates)] + pub type Candidates = + StorageValue<_, Vec>>, ValueQuery>; + + pub(super) type BlockCount = u32; + #[pallet::type_value] + pub(super) fn StartingBlockCount() -> BlockCount { + Zero::zero() + } + #[pallet::storage] + pub(super) type BlocksPerCollatorThisSession = + StorageMap<_, Blake2_128Concat, T::AccountId, BlockCount, ValueQuery, StartingBlockCount>; + + /// Performance percentile to use as baseline for collator eviction + #[pallet::storage] + #[pallet::getter(fn eviction_baseline)] + pub type EvictionBaseline = StorageValue<_, Percent, ValueQuery>; + + /// Percentage of underperformance to _tolerate_ before evicting a collator + /// + /// i.e. A collator gets evicted if it produced _less_ than x% fewer blocks than the collator at EvictionBaseline + #[pallet::storage] + #[pallet::getter(fn eviction_tolerance)] + pub type EvictionTolerance = StorageValue<_, Percent, ValueQuery>; + + /// Desired number of candidates. + /// + /// This should ideally always be less than [`Config::MaxCandidates`] for weights to be correct. + #[pallet::storage] + #[pallet::getter(fn desired_candidates)] + pub type DesiredCandidates = StorageValue<_, u32, ValueQuery>; + + /// Fixed deposit bond for each candidate. + #[pallet::storage] + #[pallet::getter(fn candidacy_bond)] + pub type CandidacyBond = StorageValue<_, BalanceOf, ValueQuery>; + + #[pallet::genesis_config] + pub struct GenesisConfig { + pub invulnerables: Vec, + pub candidacy_bond: BalanceOf, + pub eviction_baseline: Percent, + pub eviction_tolerance: Percent, + pub desired_candidates: u32, + } + + #[cfg(feature = "std")] + impl Default for GenesisConfig { + fn default() -> Self { + Self { + invulnerables: Default::default(), + candidacy_bond: Default::default(), + eviction_baseline: Percent::zero(), // Note: eviction disabled by default + eviction_tolerance: Percent::one(), // Note: eviction disabled by default + desired_candidates: Default::default(), + } + } + } + + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) { + let duplicate_invulnerables = self + .invulnerables + .iter() + .collect::>(); + assert!( + duplicate_invulnerables.len() == self.invulnerables.len(), + "duplicate invulnerables in genesis." + ); + + assert!( + T::MaxInvulnerables::get() >= (self.invulnerables.len() as u32), + "genesis invulnerables are more than T::MaxInvulnerables", + ); + assert!( + T::MaxCandidates::get() >= self.desired_candidates, + "genesis desired_candidates are more than T::MaxCandidates", + ); + assert!( + self.eviction_baseline <= Percent::one(), + "Eviction baseline must be given as a percentile - number between 0 and 100", + ); + assert!( + self.eviction_tolerance <= Percent::one(), + "Eviction tolerance must be given as a percentage - number between 0 and 100", + ); + >::put(&self.desired_candidates); + >::put(&self.candidacy_bond); + >::put(&self.eviction_baseline); + >::put(&self.eviction_tolerance); + >::put(&self.invulnerables); + } + } + + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { + NewInvulnerables(Vec), + NewDesiredCandidates(u32), + NewCandidacyBond(BalanceOf), + CandidateAdded(T::AccountId, BalanceOf), + CandidateRemoved(T::AccountId), + NewEvictionBaseline(Percent), + NewEvictionTolerance(Percent), + } + + // Errors inform users that something went wrong. + #[pallet::error] + pub enum Error { + /// Too many candidates + TooManyCandidates, + /// Unknown error + Unknown, + /// Permission issue + Permission, + /// User is already a candidate + AlreadyCandidate, + /// User is not a candidate + NotCandidate, + /// User is already an Invulnerable + AlreadyInvulnerable, + /// Account has no associated validator ID + NoAssociatedValidatorId, + /// Validator ID is not yet registered + ValidatorNotRegistered, + /// Removing invulnerable collators is not allowed + NotAllowRemoveInvulnerable, + } + + #[pallet::hooks] + impl Hooks> for Pallet {} + + #[pallet::call] + impl Pallet { + /// Set candidate collator as invulnerable. + /// + /// `new`: candidate collator. + #[pallet::weight(T::WeightInfo::set_invulnerables(new.len() as u32))] + pub fn set_invulnerables( + origin: OriginFor, + new: Vec, + ) -> DispatchResultWithPostInfo { + T::UpdateOrigin::ensure_origin(origin)?; + // we trust origin calls, this is just a for more accurate benchmarking + if (new.len() as u32) > T::MaxInvulnerables::get() { + log::warn!( + "invulnerables > T::MaxInvulnerables; you might need to run benchmarks again" + ); + } + >::put(&new); + Self::deposit_event(Event::NewInvulnerables(new)); + Ok(().into()) + } + + /// Set how many candidate collator are allowed. + /// + /// `max`: The max number of candidates. + #[pallet::weight(T::WeightInfo::set_desired_candidates())] + pub fn set_desired_candidates( + origin: OriginFor, + max: u32, + ) -> DispatchResultWithPostInfo { + T::UpdateOrigin::ensure_origin(origin)?; + // we trust origin calls, this is just a for more accurate benchmarking + if max > T::MaxCandidates::get() { + log::warn!("max > T::MaxCandidates; you might need to run benchmarks again"); + } + >::put(&max); + Self::deposit_event(Event::NewDesiredCandidates(max)); + Ok(().into()) + } + + /// Set the amount held on reserved for candidate collator. + /// + /// `bond`: The amount held on reserved. + #[pallet::weight(T::WeightInfo::set_candidacy_bond())] + pub fn set_candidacy_bond( + origin: OriginFor, + bond: BalanceOf, + ) -> DispatchResultWithPostInfo { + T::UpdateOrigin::ensure_origin(origin)?; + >::put(&bond); + Self::deposit_event(Event::NewCandidacyBond(bond)); + Ok(().into()) + } + + /// Register as candidate collator. + #[pallet::weight(T::WeightInfo::register_as_candidate(T::MaxCandidates::get()))] + pub fn register_as_candidate(origin: OriginFor) -> DispatchResultWithPostInfo { + let who = ensure_signed(origin)?; + + // ensure we are below limit. + let length = >::decode_len().unwrap_or_default(); + ensure!( + (length as u32) < Self::desired_candidates(), + Error::::TooManyCandidates + ); + ensure!( + !Self::invulnerables().contains(&who), + Error::::AlreadyInvulnerable + ); + + let validator_key = T::ValidatorIdOf::convert(who.clone()) + .ok_or(Error::::NoAssociatedValidatorId)?; + ensure!( + T::ValidatorRegistration::is_registered(&validator_key), + Error::::ValidatorNotRegistered + ); + + let deposit = Self::candidacy_bond(); + // First authored block is current block plus kick threshold to handle session delay + let incoming = CandidateInfo { + who: who.clone(), + deposit, + }; + + let current_count = + >::try_mutate(|candidates| -> Result { + if candidates.iter_mut().any(|candidate| candidate.who == who) { + Err(Error::::AlreadyCandidate.into()) + } else { + T::Currency::reserve(&who, deposit)?; + candidates.push(incoming); + Ok(candidates.len()) + } + })?; + + Self::deposit_event(Event::CandidateAdded(who, deposit)); + Ok(Some(T::WeightInfo::register_as_candidate(current_count as u32)).into()) + } + + /// Register an specified candidate as collator. + /// + /// - `new_candidate`: Who is going to be collator. + #[pallet::weight(T::WeightInfo::register_candidate(T::MaxCandidates::get()))] + pub fn register_candidate( + origin: OriginFor, + new_candidate: T::AccountId, + ) -> DispatchResultWithPostInfo { + T::UpdateOrigin::ensure_origin(origin)?; + + // ensure we are below limit. + let length = >::decode_len().unwrap_or_default(); + ensure!( + (length as u32) < Self::desired_candidates(), + Error::::TooManyCandidates + ); + ensure!( + !Self::invulnerables().contains(&new_candidate), + Error::::AlreadyInvulnerable + ); + + let validator_key = T::ValidatorIdOf::convert(new_candidate.clone()) + .ok_or(Error::::NoAssociatedValidatorId)?; + ensure!( + T::ValidatorRegistration::is_registered(&validator_key), + Error::::ValidatorNotRegistered + ); + + let deposit = Self::candidacy_bond(); + let incoming = CandidateInfo { + who: new_candidate.clone(), + deposit, + }; + + let current_count = + >::try_mutate(|candidates| -> Result { + if candidates + .iter_mut() + .any(|candidate| candidate.who == new_candidate) + { + Err(Error::::AlreadyCandidate.into()) + } else { + T::Currency::reserve(&new_candidate, deposit)?; + candidates.push(incoming); + Ok(candidates.len()) + } + })?; + + Self::deposit_event(Event::CandidateAdded(new_candidate, deposit)); + Ok(Some(T::WeightInfo::register_candidate(current_count as u32)).into()) + } + + /// Leave from collator set. + #[pallet::weight(T::WeightInfo::leave_intent(T::MaxCandidates::get()))] + pub fn leave_intent(origin: OriginFor) -> DispatchResultWithPostInfo { + let who = ensure_signed(origin)?; + let current_count = Self::try_remove_candidate(&who)?; + + Ok(Some(T::WeightInfo::leave_intent(current_count as u32)).into()) + } + + /// Remove an specified collator. + /// + /// - `collator`: Who is going to be remove from collators set. + #[pallet::weight(T::WeightInfo::remove_collator(T::MaxCandidates::get()))] + pub fn remove_collator( + origin: OriginFor, + collator: T::AccountId, + ) -> DispatchResultWithPostInfo { + T::UpdateOrigin::ensure_origin(origin)?; + + // not allow to remove invulnerables + ensure!( + !>::get().contains(&collator), + Error::::NotAllowRemoveInvulnerable + ); + + let current_count = Self::try_remove_candidate(&collator)?; + + Ok(Some(T::WeightInfo::remove_collator(current_count as u32)).into()) + } + + /// Set the collator performance percentile used as baseline for eviction + /// + /// `percentile`: x-th percentile of collator performance to use as eviction baseline + #[pallet::weight(T::WeightInfo::set_eviction_baseline())] + pub fn set_eviction_baseline( + origin: OriginFor, + percentile: Percent, + ) -> DispatchResultWithPostInfo { + T::UpdateOrigin::ensure_origin(origin)?; + >::put(percentile); // NOTE: from_percent saturates at 100 + Self::deposit_event(Event::NewEvictionBaseline(percentile)); + Ok(().into()) + } + + /// Set the tolerated underperformance percentage before evicting + /// + /// `percentage`: x% of missed blocks under eviction_baseline to tolerate + #[pallet::weight(T::WeightInfo::set_eviction_tolerance())] + pub fn set_eviction_tolerance( + origin: OriginFor, + percentage: Percent, + ) -> DispatchResultWithPostInfo { + T::UpdateOrigin::ensure_origin(origin)?; + >::put(percentage); // NOTE: from_percent saturates at 100 + Self::deposit_event(Event::NewEvictionTolerance(percentage)); + Ok(().into()) + } + } + + impl Pallet { + /// Get a unique, inaccessible account id from the `PotId`. + pub fn account_id() -> T::AccountId { + T::PotId::get().into_account() + } + + /// Removes a candidate if they exist and sends them back their deposit + fn try_remove_candidate(who: &T::AccountId) -> Result { + let current_count = + >::try_mutate(|candidates| -> Result { + let index = candidates + .iter() + .position(|candidate| candidate.who == *who) + .ok_or(Error::::NotCandidate)?; + T::Currency::unreserve(who, candidates[index].deposit); + candidates.remove(index); + Ok(candidates.len()) + })?; + Self::deposit_event(Event::CandidateRemoved(who.clone())); + Ok(current_count) + } + + /// Assemble the current set of candidates and invulnerables into the next collator set. + /// + /// This is done on the fly, as frequent as we are told to do so, as the session manager. + pub fn assemble_collators(candidates: Vec) -> Vec { + let mut collators = Self::invulnerables(); + collators.extend(candidates.into_iter().collect::>()); + collators + } + + /// Removes collators with unsatisfactory performance + /// Returns the removed AccountIds + pub fn evict_bad_collators( + candidates: Vec>>, + ) -> Vec { + use sp_runtime::PerThing; + + // 0. Storage reads and precondition checks + if candidates.is_empty() { + return Vec::new(); // No candidates means we're running invulnerables only + } + let percentile_for_kick = Self::eviction_baseline(); + if percentile_for_kick == Percent::zero() { + return Vec::new(); // Selecting 0-th percentile disables kicking. Upper bound check in fn build() + } + let underperformance_tolerated = Self::eviction_tolerance(); + if underperformance_tolerated == Percent::one() { + return Vec::new(); // tolerating 100% underperformance disables kicking + } + let mut collator_perf_this_session = + >::iter().collect::>(); + if collator_perf_this_session.is_empty() { + return Vec::new(); // no validator performance recorded ( should not happen ) + } + + // 1. Ascending sort of collator performance list by number of produced blocks + collator_perf_this_session.sort_unstable_by_key(|k| k.1); + let collator_count = collator_perf_this_session.len(); + + // 2. get percentile by _exclusive_ nearest rank method https://en.wikipedia.org/wiki/Percentile#The_nearest-rank_method (rust percentile API is feature gated and unstable) + let ordinal_rank = percentile_for_kick.mul_ceil(collator_count); + let index_at_ordinal_rank = ordinal_rank.saturating_sub(One::one()); // -1 to accomodate 0-index counting, should not saturate due to precondition check and round up multiplication + + // 3. Block number at rank is the percentile and our kick performance benchmark + let blocks_created_at_baseline: BlockCount = + collator_perf_this_session[index_at_ordinal_rank].1; + + // 4. We kick if a collator produced fewer than (EvictionTolerance * EvictionBaseline rounded up) blocks than the percentile + let evict_below_blocks = (underperformance_tolerated + .left_from_one() + .mul_ceil(blocks_created_at_baseline)) + as BlockCount; + log::trace!( + "Session Performance stats: {}-th percentile: {:?} blocks. Evicting collators who produced less than {} blocks", + percentile_for_kick.mul_ceil(100u8), + blocks_created_at_baseline, + evict_below_blocks + ); + + // 5. Walk the percentile slice, call try_remove_candidate if a collator is under threshold + let kick_candidates = &collator_perf_this_session[..index_at_ordinal_rank]; // ordinal-rank exclusive, the collator at percentile is safe + let mut removed_account_ids: Vec = + Vec::with_capacity(kick_candidates.len()); + kick_candidates.iter().for_each(|(acc_id, my_blocks_this_session)| { + if *my_blocks_this_session < evict_below_blocks { + // If our validator is not also a candidate we're invulnerable or already kicked + if candidates.iter().any(|x| x.who == *acc_id) { + #[allow(clippy::bind_instead_of_map)] Self::try_remove_candidate(acc_id) + .and_then(|_| { + removed_account_ids.push(acc_id.clone()); + log::info!("Removed collator of account {:?} as it only produced {} blocks this session which is below acceptable threshold of {}", &acc_id, my_blocks_this_session,evict_below_blocks); + Ok(()) + }) + .unwrap_or_else(|why| { + log::warn!("Failed to remove candidate due to underperformance {:?}", why); + debug_assert!(false, "failed to remove candidate {:?}", why); + }); + } + } + }); + removed_account_ids.shrink_to_fit(); + removed_account_ids + } + + /// Reset the performance map to the currently active validators at 0 blocks + pub fn reset_collator_performance() { + >::remove_all(None); + let validators = T::ValidatorRegistration::validators(); + for validator_id in validators { + let account_id = T::AccountIdOf::convert(validator_id.clone().into()); + >::insert(account_id.clone(), 0u32); + } + } + } + + /// Keep track of number of authored blocks per authority, uncles are counted as well since + /// they're a valid proof of being online. + impl + pallet_authorship::EventHandler for Pallet + { + fn note_author(author: T::AccountId) { + let pot = Self::account_id(); + // assumes an ED will be sent to pot. + let reward = T::Currency::free_balance(&pot) + .checked_sub(&T::Currency::minimum_balance()) + .unwrap_or_else(Zero::zero) + .div(2u32.into()); + // `reward` is half of pot account minus ED, this should never fail. + let _success = T::Currency::transfer(&pot, &author, reward, KeepAlive); + debug_assert!(_success.is_ok()); + + // increment blocks this node authored + >::mutate(&author, |blocks| { + *blocks = blocks.saturating_add(One::one()); + }); + + frame_system::Pallet::::register_extra_weight_unchecked( + T::WeightInfo::note_author(), + DispatchClass::Mandatory, + ); + } + + fn note_uncle(_author: T::AccountId, _age: T::BlockNumber) { + //TODO can we ignore this? + } + } + + /// Play the role of the session manager. + impl SessionManager for Pallet { + fn new_session(index: SessionIndex) -> Option> { + log::info!( + "assembling new collators for new session {} at #{:?}", + index, + >::block_number(), + ); + + let candidates = Self::candidates(); + let candidates_len_before = candidates.len(); + let removed_candidate_ids = Self::evict_bad_collators(candidates.clone()); + let active_candidate_ids = candidates + .iter() + .filter_map(|x| { + if removed_candidate_ids.contains(&x.who) { + None + } else { + Some(x.who.clone()) + } + }) + .collect::>(); + let result = Self::assemble_collators(active_candidate_ids); + + frame_system::Pallet::::register_extra_weight_unchecked( + T::WeightInfo::new_session(candidates_len_before as u32), + DispatchClass::Mandatory, + ); + + Self::reset_collator_performance(); // Reset performance map for the now starting session's active validatorset + Some(result) + } + fn start_session(_: SessionIndex) { + // we don't care. + } + fn end_session(_: SessionIndex) { + // we don't care. + } + } } diff --git a/pallets/collator-selection/src/migrations.rs b/pallets/collator-selection/src/migrations.rs index 3f4460c67..5a8f5b0dc 100644 --- a/pallets/collator-selection/src/migrations.rs +++ b/pallets/collator-selection/src/migrations.rs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 Manta Network. +// Copyright 2020-2022 Manta Network. // This file is part of Manta. // // Manta is free software: you can redistribute it and/or modify @@ -18,90 +18,92 @@ use super::*; use frame_support::{ - dispatch::GetStorageVersion, - pallet_prelude::Weight, - traits::{Get, PalletInfoAccess, StorageVersion}, - Twox64Concat, + dispatch::GetStorageVersion, + pallet_prelude::Weight, + traits::{Get, PalletInfoAccess, StorageVersion}, + Twox64Concat, }; /// This migrates the pallet from the standard version by parity to our modified storage. impl Pallet { - pub fn migrate_v0_to_v1() -> frame_support::weights::Weight { - use frame_support::migration::{ - have_storage_value, remove_storage_prefix, storage_key_iter, - }; - // Storage migrations should use storage versions for safety. - if Self::on_chain_storage_version() < 1 { - log::info!("Executing collator-selection V0->V1 migration!"); + pub fn migrate_v0_to_v1() -> frame_support::weights::Weight { + use frame_support::migration::{ + have_storage_value, remove_storage_prefix, storage_key_iter, + }; + // Storage migrations should use storage versions for safety. + if Self::on_chain_storage_version() < 1 { + log::info!("Executing collator-selection V0->V1 migration!"); - // Drain all keys from the old (now unused) map - let iter_map = storage_key_iter::( - Self::name().as_bytes(), - b"LastAuthoredBlock", - ) - .drain(); - let mut dropcount = 0; - for _ in iter_map { - dropcount += 1; - } - log::info!(" >>> Cleaned {} keys from LastAuthoredBlock", dropcount); - remove_storage_prefix(Self::name().as_bytes(), b"LastAuthoredBlock", &[]); - log::info!(" >>> Removed LastAuthoredBlock from storage"); + // Drain all keys from the old (now unused) map + let iter_map = storage_key_iter::( + Self::name().as_bytes(), + b"LastAuthoredBlock", + ) + .drain(); + let mut dropcount = 0; + for _ in iter_map { + dropcount += 1; + } + log::info!(" >>> Cleaned {} keys from LastAuthoredBlock", dropcount); + remove_storage_prefix(Self::name().as_bytes(), b"LastAuthoredBlock", &[]); + log::info!(" >>> Removed LastAuthoredBlock from storage"); - // Update storage version. - StorageVersion::new(1).put::(); + // Update storage version. + StorageVersion::new(1).put::(); - // Remove KickThreshold if customized - if have_storage_value(Self::name().as_bytes(), b"KickThreshold", &[]) { - remove_storage_prefix(Self::name().as_bytes(), b"KickThreshold", &[]); - log::info!(" >>> Removed KickThreshold"); - } else { - log::warn!(" !!! Chain did not have KickThreshold in storage. This is uenexpected but is possible if the genesis config was never changed"); - } + // Remove KickThreshold if customized + if have_storage_value(Self::name().as_bytes(), b"KickThreshold", &[]) { + remove_storage_prefix(Self::name().as_bytes(), b"KickThreshold", &[]); + log::info!(" >>> Removed KickThreshold"); + } else { + log::warn!(" !!! Chain did not have KickThreshold in storage. This is uenexpected but is possible if the genesis config was never changed"); + } - // Return the weight consumed by the migration. - T::DbWeight::get().reads_writes(1, dropcount as Weight + 1) - } else { - log::debug!("collator-selection V0->V1 migration not needed!"); - 0 - } - } - pub fn pre_migrate_v0_to_v1() -> Result<(), &'static str> { - use frame_support::migration::{have_storage_value, storage_key_iter}; - let chainver = Self::on_chain_storage_version(); - if chainver >= 1 { - return Err("Migration to V1 does not apply"); - } - if !have_storage_value(Self::name().as_bytes(), b"KickThreshold", &[]) { - log::warn!("Precheck: KickThreshold does not exist"); - } - if storage_key_iter::( - Self::name().as_bytes(), - b"LastAuthoredBlock", - ) - .count() == 0 - { - return Err("LastAuthoredBlock does not exist"); - } - Ok(()) - } + // Return the weight consumed by the migration. + T::DbWeight::get().reads_writes(1, dropcount as Weight + 1) + } else { + log::debug!("collator-selection V0->V1 migration not needed!"); + 0 + } + } + pub fn pre_migrate_v0_to_v1() -> Result<(), &'static str> { + use frame_support::migration::{have_storage_value, storage_key_iter}; + let chainver = Self::on_chain_storage_version(); + if chainver >= 1 { + return Err("Migration to V1 does not apply"); + } + if !have_storage_value(Self::name().as_bytes(), b"KickThreshold", &[]) { + log::warn!("Precheck: KickThreshold does not exist"); + } + if storage_key_iter::( + Self::name().as_bytes(), + b"LastAuthoredBlock", + ) + .count() + == 0 + { + return Err("LastAuthoredBlock does not exist"); + } + Ok(()) + } - pub fn post_migrate_v0_to_v1() -> Result<(), &'static str> { - use frame_support::migration::{have_storage_value, storage_key_iter}; - if Self::on_chain_storage_version() != 1 { - return Err("storage version not upgraded"); - } - if have_storage_value(Self::name().as_bytes(), b"KickThreshold", &[]) { - return Err("KickThreshold wasn't removed"); - } - if storage_key_iter::( - Self::name().as_bytes(), - b"LastAuthoredBlock", - ) - .count() > 0 - { - return Err("LastAuthoredBlock wasn't removed"); - } - Ok(()) - } + pub fn post_migrate_v0_to_v1() -> Result<(), &'static str> { + use frame_support::migration::{have_storage_value, storage_key_iter}; + if Self::on_chain_storage_version() != 1 { + return Err("storage version not upgraded"); + } + if have_storage_value(Self::name().as_bytes(), b"KickThreshold", &[]) { + return Err("KickThreshold wasn't removed"); + } + if storage_key_iter::( + Self::name().as_bytes(), + b"LastAuthoredBlock", + ) + .count() + > 0 + { + return Err("LastAuthoredBlock wasn't removed"); + } + Ok(()) + } } diff --git a/pallets/collator-selection/src/mock.rs b/pallets/collator-selection/src/mock.rs index b11a2aaf9..351f8ab59 100644 --- a/pallets/collator-selection/src/mock.rs +++ b/pallets/collator-selection/src/mock.rs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 Manta Network. +// Copyright 2020-2022 Manta Network. // This file is part of Manta. // // Manta is free software: you can redistribute it and/or modify @@ -17,20 +17,20 @@ use super::*; use crate as collator_selection; use frame_support::{ - ord_parameter_types, parameter_types, - traits::{ - ConstU16, ConstU32, ConstU64, FindAuthor, GenesisBuild, ValidatorRegistration, ValidatorSet, - }, - PalletId, + ord_parameter_types, parameter_types, + traits::{ + ConstU16, ConstU32, ConstU64, FindAuthor, GenesisBuild, ValidatorRegistration, ValidatorSet, + }, + PalletId, }; use frame_system::EnsureSignedBy; use sp_arithmetic::Percent; use sp_core::H256; use sp_runtime::{ - testing::{Header, UintAuthorityId}, - traits::{BlakeTwo256, IdentityLookup, OpaqueKeys}, - RuntimeAppPublic, + testing::{Header, UintAuthorityId}, + traits::{BlakeTwo256, IdentityLookup, OpaqueKeys}, + RuntimeAppPublic, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; @@ -38,225 +38,221 @@ type Block = frame_system::mocking::MockBlock; // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - System: frame_system::{Pallet, Call, Config, Storage, Event}, - Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, - Authorship: pallet_authorship::{Pallet, Call, Storage, Inherent}, - Session: pallet_session::{Pallet, Call, Storage, Event, Config}, - CollatorSelection: collator_selection::{Pallet, Call, Storage, Event}, - Aura: pallet_aura::{Pallet, Storage, Config}, - Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - } + pub enum Test where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Config, Storage, Event}, + Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, + Authorship: pallet_authorship::{Pallet, Call, Storage, Inherent}, + Session: pallet_session::{Pallet, Call, Storage, Event, Config}, + CollatorSelection: collator_selection::{Pallet, Call, Storage, Event}, + Aura: pallet_aura::{Pallet, Storage, Config}, + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, + } ); impl frame_system::Config for Test { - type BaseCallFilter = frame_support::traits::Everything; - type BlockWeights = (); - type BlockLength = (); - type DbWeight = (); - type Origin = Origin; - type Call = Call; - type Index = u64; - type BlockNumber = u64; - type Hash = H256; - type Hashing = BlakeTwo256; - type AccountId = u64; - type Lookup = IdentityLookup; - type Header = Header; - type Event = Event; - type BlockHashCount = ConstU64<250>; - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = ConstU16<78>; - type OnSetCode = (); - type MaxConsumers = frame_support::traits::ConstU32<16>; + type BaseCallFilter = frame_support::traits::Everything; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type Origin = Origin; + type Call = Call; + type Index = u64; + type BlockNumber = u64; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = u64; + type Lookup = IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = ConstU64<250>; + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = ConstU16<78>; + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; } impl pallet_balances::Config for Test { - type Balance = u64; - type Event = Event; - type DustRemoval = (); - type ExistentialDeposit = ConstU64<5>; - type AccountStore = System; - type WeightInfo = (); - type MaxLocks = (); - type MaxReserves = ConstU32<50>; - type ReserveIdentifier = [u8; 8]; + type Balance = u64; + type Event = Event; + type DustRemoval = (); + type ExistentialDeposit = ConstU64<5>; + type AccountStore = System; + type WeightInfo = (); + type MaxLocks = (); + type MaxReserves = ConstU32<50>; + type ReserveIdentifier = [u8; 8]; } pub struct Author4; impl FindAuthor for Author4 { - fn find_author<'a, I>(_digests: I) -> Option - where - I: 'a + IntoIterator, - { - Some(4) - } + fn find_author<'a, I>(_digests: I) -> Option + where + I: 'a + IntoIterator, + { + Some(4) + } } impl pallet_authorship::Config for Test { - type FindAuthor = Author4; - type UncleGenerations = (); - type FilterUncle = (); - type EventHandler = CollatorSelection; + type FindAuthor = Author4; + type UncleGenerations = (); + type FilterUncle = (); + type EventHandler = CollatorSelection; } impl pallet_timestamp::Config for Test { - type Moment = u64; - type OnTimestampSet = Aura; - type MinimumPeriod = ConstU64<1>; - type WeightInfo = (); + type Moment = u64; + type OnTimestampSet = Aura; + type MinimumPeriod = ConstU64<1>; + type WeightInfo = (); } impl pallet_aura::Config for Test { - type AuthorityId = sp_consensus_aura::sr25519::AuthorityId; - type MaxAuthorities = ConstU32<100_000>; - type DisabledValidators = (); + type AuthorityId = sp_consensus_aura::sr25519::AuthorityId; + type MaxAuthorities = ConstU32<100_000>; + type DisabledValidators = (); } sp_runtime::impl_opaque_keys! { - pub struct MockSessionKeys { - // a key for aura authoring - pub aura: UintAuthorityId, - } + pub struct MockSessionKeys { + // a key for aura authoring + pub aura: UintAuthorityId, + } } impl From for MockSessionKeys { - fn from(aura: sp_runtime::testing::UintAuthorityId) -> Self { - Self { aura } - } + fn from(aura: sp_runtime::testing::UintAuthorityId) -> Self { + Self { aura } + } } parameter_types! { - pub static SessionHandlerCollators: Vec = Vec::new(); - pub static SessionChangeBlock: u64 = 0; + pub static SessionHandlerCollators: Vec = Vec::new(); + pub static SessionChangeBlock: u64 = 0; } pub struct TestSessionHandler; impl pallet_session::SessionHandler for TestSessionHandler { - const KEY_TYPE_IDS: &'static [sp_runtime::KeyTypeId] = &[UintAuthorityId::ID]; - fn on_genesis_session(keys: &[(u64, Ks)]) { - SessionHandlerCollators::set(keys.into_iter().map(|(a, _)| *a).collect::>()) - } - fn on_new_session(_: bool, keys: &[(u64, Ks)], _: &[(u64, Ks)]) { - SessionChangeBlock::set(System::block_number()); - SessionHandlerCollators::set(keys.into_iter().map(|(a, _)| *a).collect::>()) - } - fn on_before_session_ending() {} - fn on_disabled(_: u32) {} + const KEY_TYPE_IDS: &'static [sp_runtime::KeyTypeId] = &[UintAuthorityId::ID]; + fn on_genesis_session(keys: &[(u64, Ks)]) { + SessionHandlerCollators::set(keys.iter().map(|(a, _)| *a).collect::>()) + } + fn on_new_session(_: bool, keys: &[(u64, Ks)], _: &[(u64, Ks)]) { + SessionChangeBlock::set(System::block_number()); + SessionHandlerCollators::set(keys.iter().map(|(a, _)| *a).collect::>()) + } + fn on_before_session_ending() {} + fn on_disabled(_: u32) {} } parameter_types! { - pub const Offset: u64 = 0; - pub const Period: u64 = 10; + pub const Offset: u64 = 0; + pub const Period: u64 = 10; } impl pallet_session::Config for Test { - type Event = Event; - type ValidatorId = ::AccountId; - // we don't have stash and controller, thus we don't need the convert as well. - type ValidatorIdOf = IdentityCollator; - type ShouldEndSession = pallet_session::PeriodicSessions; - type NextSessionRotation = pallet_session::PeriodicSessions; - type SessionManager = CollatorSelection; - type SessionHandler = TestSessionHandler; - type Keys = MockSessionKeys; - type WeightInfo = (); + type Event = Event; + type ValidatorId = ::AccountId; + // we don't have stash and controller, thus we don't need the convert as well. + type ValidatorIdOf = IdentityCollator; + type ShouldEndSession = pallet_session::PeriodicSessions; + type NextSessionRotation = pallet_session::PeriodicSessions; + type SessionManager = CollatorSelection; + type SessionHandler = TestSessionHandler; + type Keys = MockSessionKeys; + type WeightInfo = (); } ord_parameter_types! { - pub const RootAccount: u64 = 777; + pub const RootAccount: u64 = 777; } parameter_types! { - pub const PotId: PalletId = PalletId(*b"PotStake"); + pub const PotId: PalletId = PalletId(*b"PotStake"); } pub struct IsRegistered; impl ValidatorRegistration for IsRegistered { - fn is_registered(id: &u64) -> bool { - if *id == 7u64 { - false - } else { - true - } - } + fn is_registered(id: &u64) -> bool { + *id != 7u64 + } } impl ValidatorSet for IsRegistered { - type ValidatorId = u64; - type ValidatorIdOf = IdentityCollator; - fn session_index() -> sp_staking::SessionIndex { - Session::current_index() - } - fn validators() -> Vec { - Session::validators() - } + type ValidatorId = u64; + type ValidatorIdOf = IdentityCollator; + fn session_index() -> sp_staking::SessionIndex { + Session::current_index() + } + fn validators() -> Vec { + Session::validators() + } } impl Config for Test { - type Event = Event; - type Currency = Balances; - type UpdateOrigin = EnsureSignedBy; - type PotId = PotId; - type MaxCandidates = ConstU32<20>; - type MaxInvulnerables = ConstU32<20>; - type ValidatorId = ::AccountId; - type ValidatorIdOf = IdentityCollator; - type AccountIdOf = IdentityCollator; - type ValidatorRegistration = IsRegistered; - type WeightInfo = (); + type Event = Event; + type Currency = Balances; + type UpdateOrigin = EnsureSignedBy; + type PotId = PotId; + type MaxCandidates = ConstU32<20>; + type MaxInvulnerables = ConstU32<20>; + type ValidatorId = ::AccountId; + type ValidatorIdOf = IdentityCollator; + type AccountIdOf = IdentityCollator; + type ValidatorRegistration = IsRegistered; + type WeightInfo = (); } pub fn new_test_ext() -> sp_io::TestExternalities { - sp_tracing::try_init_simple(); - let mut t = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); - let invulnerables = vec![1, 2]; - let keys = invulnerables - .iter() - .map(|i| { - ( - *i, - *i, - MockSessionKeys { - aura: UintAuthorityId(*i), - }, - ) - }) - .collect::>(); + sp_tracing::try_init_simple(); + let mut t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); + let invulnerables = vec![1, 2]; + let keys = invulnerables + .iter() + .map(|i| { + ( + *i, + *i, + MockSessionKeys { + aura: UintAuthorityId(*i), + }, + ) + }) + .collect::>(); - let balances = pallet_balances::GenesisConfig:: { - balances: vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100)], - }; - let collator_selection = collator_selection::GenesisConfig:: { - desired_candidates: 2, - candidacy_bond: 10, - eviction_baseline: Percent::from_percent(80), - eviction_tolerance: Percent::from_percent(10), - invulnerables, - }; - let session = pallet_session::GenesisConfig:: { keys }; - balances.assimilate_storage(&mut t).unwrap(); - // collator selection must be initialized before session. - collator_selection.assimilate_storage(&mut t).unwrap(); - session.assimilate_storage(&mut t).unwrap(); + let balances = pallet_balances::GenesisConfig:: { + balances: vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100)], + }; + let collator_selection = collator_selection::GenesisConfig:: { + desired_candidates: 2, + candidacy_bond: 10, + eviction_baseline: Percent::from_percent(80), + eviction_tolerance: Percent::from_percent(10), + invulnerables, + }; + let session = pallet_session::GenesisConfig:: { keys }; + balances.assimilate_storage(&mut t).unwrap(); + // collator selection must be initialized before session. + collator_selection.assimilate_storage(&mut t).unwrap(); + session.assimilate_storage(&mut t).unwrap(); - t.into() + t.into() } pub fn initialize_to_block(n: u64) { - for i in System::block_number() + 1..=n { - System::set_block_number(i); - >::on_initialize(i); - } + for i in System::block_number() + 1..=n { + System::set_block_number(i); + >::on_initialize(i); + } } diff --git a/pallets/collator-selection/src/tests.rs b/pallets/collator-selection/src/tests.rs index d842cbd72..e55cf939f 100644 --- a/pallets/collator-selection/src/tests.rs +++ b/pallets/collator-selection/src/tests.rs @@ -1,4 +1,4 @@ -// Copyright 2020-2021 Manta Network. +// Copyright 2020-2022 Manta Network. // This file is part of Manta. // // Manta is free software: you can redistribute it and/or modify @@ -16,12 +16,12 @@ use crate as collator_selection; use crate::{ - mock::*, BlocksPerCollatorThisSession, CandidateInfo, Error, EvictionBaseline, - EvictionTolerance, + mock::*, BlocksPerCollatorThisSession, CandidateInfo, Error, EvictionBaseline, + EvictionTolerance, }; use frame_support::{ - assert_noop, assert_ok, - traits::{Currency, GenesisBuild, OnInitialize, ReservableCurrency}, + assert_noop, assert_ok, + traits::{Currency, GenesisBuild, OnInitialize, ReservableCurrency}, }; use pallet_balances::Error as BalancesError; use sp_arithmetic::Percent; @@ -34,869 +34,868 @@ const DAVE: u64 = 4; // NOTE: As defined in mock, dave will author all blocks const EVE: u64 = 5; fn candidate_ids() -> Vec { - let ret = CollatorSelection::candidates() - .iter() - .map(|c| c.who.clone()) - .collect::>(); - return ret; + CollatorSelection::candidates() + .iter() + .map(|c| c.who) + .collect::>() } fn set_all_validator_perf_to(n: u32) { - for v in Session::validators() { - BlocksPerCollatorThisSession::::insert(v, n); - } + for v in Session::validators() { + BlocksPerCollatorThisSession::::insert(v, n); + } } fn setup_3_candidates() { - assert_ok!(CollatorSelection::set_desired_candidates( - Origin::signed(RootAccount::get()), - 3 - )); - assert_ok!(CollatorSelection::register_as_candidate(Origin::signed( - CHAD - ))); - assert_ok!(Session::set_keys( - Origin::signed(CHAD), - UintAuthorityId(CHAD).into(), - vec![] - )); - assert_ok!(CollatorSelection::register_as_candidate(Origin::signed( - DAVE - ))); - assert_ok!(Session::set_keys( - Origin::signed(DAVE), - UintAuthorityId(DAVE).into(), - vec![] - )); - assert_ok!(CollatorSelection::register_as_candidate(Origin::signed( - EVE - ))); - assert_ok!(Session::set_keys( - Origin::signed(EVE), - UintAuthorityId(EVE).into(), - vec![] - )); + assert_ok!(CollatorSelection::set_desired_candidates( + Origin::signed(RootAccount::get()), + 3 + )); + assert_ok!(CollatorSelection::register_as_candidate(Origin::signed( + CHAD + ))); + assert_ok!(Session::set_keys( + Origin::signed(CHAD), + UintAuthorityId(CHAD).into(), + vec![] + )); + assert_ok!(CollatorSelection::register_as_candidate(Origin::signed( + DAVE + ))); + assert_ok!(Session::set_keys( + Origin::signed(DAVE), + UintAuthorityId(DAVE).into(), + vec![] + )); + assert_ok!(CollatorSelection::register_as_candidate(Origin::signed( + EVE + ))); + assert_ok!(Session::set_keys( + Origin::signed(EVE), + UintAuthorityId(EVE).into(), + vec![] + )); } #[test] fn basic_setup_works() { - new_test_ext().execute_with(|| { - assert_eq!(CollatorSelection::desired_candidates(), 2); - assert_eq!(CollatorSelection::candidacy_bond(), 10); + new_test_ext().execute_with(|| { + assert_eq!(CollatorSelection::desired_candidates(), 2); + assert_eq!(CollatorSelection::candidacy_bond(), 10); - assert!(CollatorSelection::candidates().is_empty()); - assert_eq!(CollatorSelection::invulnerables(), vec![1, 2]); - }); + assert!(CollatorSelection::candidates().is_empty()); + assert_eq!(CollatorSelection::invulnerables(), vec![1, 2]); + }); } #[test] fn it_should_set_invulnerables() { - new_test_ext().execute_with(|| { - let new_set = vec![1, 2, 3, 4]; - assert_ok!(CollatorSelection::set_invulnerables( - Origin::signed(RootAccount::get()), - new_set.clone() - )); - assert_eq!(CollatorSelection::invulnerables(), new_set); - - // cannot set with non-root. - assert_noop!( - CollatorSelection::set_invulnerables(Origin::signed(1), new_set.clone()), - BadOrigin - ); - }); + new_test_ext().execute_with(|| { + let new_set = vec![1, 2, 3, 4]; + assert_ok!(CollatorSelection::set_invulnerables( + Origin::signed(RootAccount::get()), + new_set.clone() + )); + assert_eq!(CollatorSelection::invulnerables(), new_set); + + // cannot set with non-root. + assert_noop!( + CollatorSelection::set_invulnerables(Origin::signed(1), new_set), + BadOrigin + ); + }); } #[test] fn set_desired_candidates_works() { - new_test_ext().execute_with(|| { - // given - assert_eq!(CollatorSelection::desired_candidates(), 2); + new_test_ext().execute_with(|| { + // given + assert_eq!(CollatorSelection::desired_candidates(), 2); - // can set - assert_ok!(CollatorSelection::set_desired_candidates( - Origin::signed(RootAccount::get()), - 7 - )); - assert_eq!(CollatorSelection::desired_candidates(), 7); + // can set + assert_ok!(CollatorSelection::set_desired_candidates( + Origin::signed(RootAccount::get()), + 7 + )); + assert_eq!(CollatorSelection::desired_candidates(), 7); - // rejects bad origin - assert_noop!( - CollatorSelection::set_desired_candidates(Origin::signed(1), 8), - BadOrigin - ); - }); + // rejects bad origin + assert_noop!( + CollatorSelection::set_desired_candidates(Origin::signed(1), 8), + BadOrigin + ); + }); } #[test] fn set_candidacy_bond() { - new_test_ext().execute_with(|| { - // given - assert_eq!(CollatorSelection::candidacy_bond(), 10); + new_test_ext().execute_with(|| { + // given + assert_eq!(CollatorSelection::candidacy_bond(), 10); - // can set - assert_ok!(CollatorSelection::set_candidacy_bond( - Origin::signed(RootAccount::get()), - 7 - )); - assert_eq!(CollatorSelection::candidacy_bond(), 7); + // can set + assert_ok!(CollatorSelection::set_candidacy_bond( + Origin::signed(RootAccount::get()), + 7 + )); + assert_eq!(CollatorSelection::candidacy_bond(), 7); - // rejects bad origin. - assert_noop!( - CollatorSelection::set_candidacy_bond(Origin::signed(1), 8), - BadOrigin - ); - }); + // rejects bad origin. + assert_noop!( + CollatorSelection::set_candidacy_bond(Origin::signed(1), 8), + BadOrigin + ); + }); } #[test] fn set_eviction_baseline() { - new_test_ext().execute_with(|| { - // given - assert_eq!( - CollatorSelection::eviction_baseline(), - Percent::from_percent(80) - ); - - // can set - assert_ok!(CollatorSelection::set_eviction_baseline( - Origin::signed(RootAccount::get()), - Percent::from_percent(100) - )); - assert_eq!( - CollatorSelection::eviction_baseline(), - Percent::from_percent(100) - ); - - // saturates to 100 - assert_ok!(CollatorSelection::set_eviction_baseline( - Origin::signed(RootAccount::get()), - Percent::from_percent(101) - )); - assert_eq!( - CollatorSelection::eviction_baseline(), - Percent::from_percent(100) - ); - - // rejects bad origin. - assert_noop!( - CollatorSelection::set_eviction_baseline(Origin::signed(1), Percent::from_percent(8)), - BadOrigin - ); - }); + new_test_ext().execute_with(|| { + // given + assert_eq!( + CollatorSelection::eviction_baseline(), + Percent::from_percent(80) + ); + + // can set + assert_ok!(CollatorSelection::set_eviction_baseline( + Origin::signed(RootAccount::get()), + Percent::from_percent(100) + )); + assert_eq!( + CollatorSelection::eviction_baseline(), + Percent::from_percent(100) + ); + + // saturates to 100 + assert_ok!(CollatorSelection::set_eviction_baseline( + Origin::signed(RootAccount::get()), + Percent::from_percent(101) + )); + assert_eq!( + CollatorSelection::eviction_baseline(), + Percent::from_percent(100) + ); + + // rejects bad origin. + assert_noop!( + CollatorSelection::set_eviction_baseline(Origin::signed(1), Percent::from_percent(8)), + BadOrigin + ); + }); } #[test] fn set_eviction_tolerance() { - new_test_ext().execute_with(|| { - // given - assert_eq!( - CollatorSelection::eviction_tolerance(), - Percent::from_percent(10) - ); - - // can set - assert_ok!(CollatorSelection::set_eviction_tolerance( - Origin::signed(RootAccount::get()), - Percent::from_percent(5) - )); - assert_eq!( - CollatorSelection::eviction_tolerance(), - Percent::from_percent(5) - ); - - // saturates to 100 - assert_ok!(CollatorSelection::set_eviction_tolerance( - Origin::signed(RootAccount::get()), - Percent::from_percent(101) - )); - assert_eq!( - CollatorSelection::eviction_tolerance(), - Percent::from_percent(100) - ); - - // rejects bad origin. - assert_noop!( - CollatorSelection::set_eviction_tolerance(Origin::signed(1), Percent::from_percent(8)), - BadOrigin - ); - }); + new_test_ext().execute_with(|| { + // given + assert_eq!( + CollatorSelection::eviction_tolerance(), + Percent::from_percent(10) + ); + + // can set + assert_ok!(CollatorSelection::set_eviction_tolerance( + Origin::signed(RootAccount::get()), + Percent::from_percent(5) + )); + assert_eq!( + CollatorSelection::eviction_tolerance(), + Percent::from_percent(5) + ); + + // saturates to 100 + assert_ok!(CollatorSelection::set_eviction_tolerance( + Origin::signed(RootAccount::get()), + Percent::from_percent(101) + )); + assert_eq!( + CollatorSelection::eviction_tolerance(), + Percent::from_percent(100) + ); + + // rejects bad origin. + assert_noop!( + CollatorSelection::set_eviction_tolerance(Origin::signed(1), Percent::from_percent(8)), + BadOrigin + ); + }); } #[test] fn cannot_register_candidate_if_too_many() { - new_test_ext().execute_with(|| { - // reset desired candidates: - >::put(0); + new_test_ext().execute_with(|| { + // reset desired candidates: + >::put(0); - // can't accept anyone anymore. - assert_noop!( - CollatorSelection::register_as_candidate(Origin::signed(3)), - Error::::TooManyCandidates, - ); + // can't accept anyone anymore. + assert_noop!( + CollatorSelection::register_as_candidate(Origin::signed(3)), + Error::::TooManyCandidates, + ); - // reset desired candidates: - >::put(1); - assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(4))); + // reset desired candidates: + >::put(1); + assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(4))); - // but no more - assert_noop!( - CollatorSelection::register_as_candidate(Origin::signed(5)), - Error::::TooManyCandidates, - ); - }) + // but no more + assert_noop!( + CollatorSelection::register_as_candidate(Origin::signed(5)), + Error::::TooManyCandidates, + ); + }) } #[test] fn cannot_register_as_candidate_if_invulnerable() { - new_test_ext().execute_with(|| { - assert_eq!(CollatorSelection::invulnerables(), vec![1, 2]); + new_test_ext().execute_with(|| { + assert_eq!(CollatorSelection::invulnerables(), vec![1, 2]); - // can't 1 because it is invulnerable. - assert_noop!( - CollatorSelection::register_as_candidate(Origin::signed(1)), - Error::::AlreadyInvulnerable, - ); - }) + // can't 1 because it is invulnerable. + assert_noop!( + CollatorSelection::register_as_candidate(Origin::signed(1)), + Error::::AlreadyInvulnerable, + ); + }) } #[test] fn cannot_register_as_candidate_if_keys_not_registered() { - new_test_ext().execute_with(|| { - // can't 7 because keys not registered. - assert_noop!( - CollatorSelection::register_as_candidate(Origin::signed(7)), - Error::::ValidatorNotRegistered - ); - }) + new_test_ext().execute_with(|| { + // can't 7 because keys not registered. + assert_noop!( + CollatorSelection::register_as_candidate(Origin::signed(7)), + Error::::ValidatorNotRegistered + ); + }) } #[test] fn cannot_register_dupe_candidate() { - new_test_ext().execute_with(|| { - // can add 3 as candidate - assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(3))); - let addition = CandidateInfo { - who: 3, - deposit: 10, - }; - assert_eq!(CollatorSelection::candidates(), vec![addition]); - assert_eq!(Balances::free_balance(3), 90); - - // but no more - assert_noop!( - CollatorSelection::register_as_candidate(Origin::signed(3)), - Error::::AlreadyCandidate, - ); - }) + new_test_ext().execute_with(|| { + // can add 3 as candidate + assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(3))); + let addition = CandidateInfo { + who: 3, + deposit: 10, + }; + assert_eq!(CollatorSelection::candidates(), vec![addition]); + assert_eq!(Balances::free_balance(3), 90); + + // but no more + assert_noop!( + CollatorSelection::register_as_candidate(Origin::signed(3)), + Error::::AlreadyCandidate, + ); + }) } #[test] fn cannot_register_as_candidate_if_poor() { - new_test_ext().execute_with(|| { - assert_eq!(Balances::free_balance(&3), 100); - assert_eq!(Balances::free_balance(&33), 0); + new_test_ext().execute_with(|| { + assert_eq!(Balances::free_balance(&3), 100); + assert_eq!(Balances::free_balance(&33), 0); - // works - assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(3))); + // works + assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(3))); - // poor - assert_noop!( - CollatorSelection::register_as_candidate(Origin::signed(33)), - BalancesError::::InsufficientBalance, - ); - }); + // poor + assert_noop!( + CollatorSelection::register_as_candidate(Origin::signed(33)), + BalancesError::::InsufficientBalance, + ); + }); } #[test] fn register_as_candidate_works() { - new_test_ext().execute_with(|| { - // given - assert_eq!(CollatorSelection::desired_candidates(), 2); - assert_eq!(CollatorSelection::candidacy_bond(), 10); - assert_eq!(CollatorSelection::candidates(), Vec::new()); - assert_eq!(CollatorSelection::invulnerables(), vec![1, 2]); + new_test_ext().execute_with(|| { + // given + assert_eq!(CollatorSelection::desired_candidates(), 2); + assert_eq!(CollatorSelection::candidacy_bond(), 10); + assert_eq!(CollatorSelection::candidates(), Vec::new()); + assert_eq!(CollatorSelection::invulnerables(), vec![1, 2]); - // take two endowed, non-invulnerables accounts. - assert_eq!(Balances::free_balance(&3), 100); - assert_eq!(Balances::free_balance(&4), 100); + // take two endowed, non-invulnerables accounts. + assert_eq!(Balances::free_balance(&3), 100); + assert_eq!(Balances::free_balance(&4), 100); - assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(3))); - assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(4))); + assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(3))); + assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(4))); - assert_eq!(Balances::free_balance(&3), 90); - assert_eq!(Balances::free_balance(&4), 90); + assert_eq!(Balances::free_balance(&3), 90); + assert_eq!(Balances::free_balance(&4), 90); - assert_eq!(CollatorSelection::candidates().len(), 2); - }); + assert_eq!(CollatorSelection::candidates().len(), 2); + }); } #[test] fn leave_intent() { - new_test_ext().execute_with(|| { - // register a candidate. - assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(3))); - assert_eq!(Balances::free_balance(3), 90); + new_test_ext().execute_with(|| { + // register a candidate. + assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(3))); + assert_eq!(Balances::free_balance(3), 90); - // register too so can leave above min candidates - assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(5))); - assert_eq!(Balances::free_balance(5), 90); + // register too so can leave above min candidates + assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(5))); + assert_eq!(Balances::free_balance(5), 90); - // cannot leave if not candidate. - assert_noop!( - CollatorSelection::leave_intent(Origin::signed(4)), - Error::::NotCandidate - ); + // cannot leave if not candidate. + assert_noop!( + CollatorSelection::leave_intent(Origin::signed(4)), + Error::::NotCandidate + ); - // bond is returned - assert_ok!(CollatorSelection::leave_intent(Origin::signed(3))); - assert_eq!(Balances::free_balance(3), 100); - }); + // bond is returned + assert_ok!(CollatorSelection::leave_intent(Origin::signed(3))); + assert_eq!(Balances::free_balance(3), 100); + }); } #[test] fn authorship_event_handler() { - new_test_ext().execute_with(|| { - // put 100 in the pot + 5 for ED - Balances::make_free_balance_be(&CollatorSelection::account_id(), 105); + new_test_ext().execute_with(|| { + // put 100 in the pot + 5 for ED + Balances::make_free_balance_be(&CollatorSelection::account_id(), 105); - // 4 is the default author. - assert_eq!(Balances::free_balance(4), 100); - assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(4))); - // triggers `note_author` - Authorship::on_initialize(1); + // 4 is the default author. + assert_eq!(Balances::free_balance(4), 100); + assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(4))); + // triggers `note_author` + Authorship::on_initialize(1); - let collator = CandidateInfo { - who: 4, - deposit: 10, - }; + let collator = CandidateInfo { + who: 4, + deposit: 10, + }; - assert_eq!(CollatorSelection::candidates(), vec![collator]); + assert_eq!(CollatorSelection::candidates(), vec![collator]); - // half of the pot goes to the collator who's the author (4 in tests). - assert_eq!(Balances::free_balance(4), 140); - // half + ED stays. - assert_eq!(Balances::free_balance(CollatorSelection::account_id()), 55); - }); + // half of the pot goes to the collator who's the author (4 in tests). + assert_eq!(Balances::free_balance(4), 140); + // half + ED stays. + assert_eq!(Balances::free_balance(CollatorSelection::account_id()), 55); + }); } #[test] fn fees_edgecases() { - new_test_ext().execute_with(|| { - // Nothing panics, no reward when no ED in balance - Authorship::on_initialize(1); - // put some money into the pot at ED - Balances::make_free_balance_be(&CollatorSelection::account_id(), 5); - // 4 is the default author. - assert_eq!(Balances::free_balance(4), 100); - assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(4))); - // triggers `note_author` - Authorship::on_initialize(1); - - let collator = CandidateInfo { - who: 4, - deposit: 10, - }; - - assert_eq!(CollatorSelection::candidates(), vec![collator]); - // Nothing received - assert_eq!(Balances::free_balance(4), 90); - // all fee stays - assert_eq!(Balances::free_balance(CollatorSelection::account_id()), 5); - }); + new_test_ext().execute_with(|| { + // Nothing panics, no reward when no ED in balance + Authorship::on_initialize(1); + // put some money into the pot at ED + Balances::make_free_balance_be(&CollatorSelection::account_id(), 5); + // 4 is the default author. + assert_eq!(Balances::free_balance(4), 100); + assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(4))); + // triggers `note_author` + Authorship::on_initialize(1); + + let collator = CandidateInfo { + who: 4, + deposit: 10, + }; + + assert_eq!(CollatorSelection::candidates(), vec![collator]); + // Nothing received + assert_eq!(Balances::free_balance(4), 90); + // all fee stays + assert_eq!(Balances::free_balance(CollatorSelection::account_id()), 5); + }); } #[test] fn session_management_works() { - new_test_ext().execute_with(|| { - initialize_to_block(1); - - assert_eq!(SessionChangeBlock::get(), 0); - assert_eq!(SessionHandlerCollators::get(), vec![1, 2]); - - initialize_to_block(4); - - assert_eq!(SessionChangeBlock::get(), 0); - assert_eq!(SessionHandlerCollators::get(), vec![1, 2]); - - // add a new collator - assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(3))); - assert_ok!(Session::set_keys( - Origin::signed(3), - UintAuthorityId(3).into(), - vec![] - )); - // session won't see this. - assert_eq!(SessionHandlerCollators::get(), vec![1, 2]); - // but we have a new candidate. - assert_eq!(CollatorSelection::candidates().len(), 1); - - initialize_to_block(10); - assert_eq!(SessionChangeBlock::get(), 10); - // pallet-session has 1 session delay; current validators are the same. - assert_eq!(Session::validators(), vec![1, 2]); - // queued ones are changed, and now we have 3. - assert_eq!(Session::queued_keys().len(), 3); - // session handlers (aura, et. al.) cannot see this yet. - assert_eq!(SessionHandlerCollators::get(), vec![1, 2]); - - initialize_to_block(20); - assert_eq!(SessionChangeBlock::get(), 20); - // changed are now reflected to session handlers. - assert_eq!(SessionHandlerCollators::get(), vec![1, 2, 3]); - }); + new_test_ext().execute_with(|| { + initialize_to_block(1); + + assert_eq!(SessionChangeBlock::get(), 0); + assert_eq!(SessionHandlerCollators::get(), vec![1, 2]); + + initialize_to_block(4); + + assert_eq!(SessionChangeBlock::get(), 0); + assert_eq!(SessionHandlerCollators::get(), vec![1, 2]); + + // add a new collator + assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(3))); + assert_ok!(Session::set_keys( + Origin::signed(3), + UintAuthorityId(3).into(), + vec![] + )); + // session won't see this. + assert_eq!(SessionHandlerCollators::get(), vec![1, 2]); + // but we have a new candidate. + assert_eq!(CollatorSelection::candidates().len(), 1); + + initialize_to_block(10); + assert_eq!(SessionChangeBlock::get(), 10); + // pallet-session has 1 session delay; current validators are the same. + assert_eq!(Session::validators(), vec![1, 2]); + // queued ones are changed, and now we have 3. + assert_eq!(Session::queued_keys().len(), 3); + // session handlers (aura, et. al.) cannot see this yet. + assert_eq!(SessionHandlerCollators::get(), vec![1, 2]); + + initialize_to_block(20); + assert_eq!(SessionChangeBlock::get(), 20); + // changed are now reflected to session handlers. + assert_eq!(SessionHandlerCollators::get(), vec![1, 2, 3]); + }); } #[test] fn kick_mechanism_parity() { - new_test_ext().execute_with(|| { - assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(3))); - assert_ok!(Session::set_keys( - Origin::signed(3), - UintAuthorityId(3).into(), - vec![] - )); - assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(4))); - assert_ok!(Session::set_keys( - Origin::signed(4), - UintAuthorityId(4).into(), - vec![] - )); - initialize_to_block(10); - assert_eq!(CollatorSelection::candidates().len(), 2); - initialize_to_block(20); - assert_eq!(SessionChangeBlock::get(), 20); - assert_eq!(CollatorSelection::candidates().len(), 2); - assert_eq!(Session::validators().len(), 4); // all candidates active - initialize_to_block(30); - // 4 authored all blocks in this the past session, gets to stay 3 was kicked on session change - assert_eq!(CollatorSelection::candidates().len(), 1); - // 3 will be kicked after 1 session delay - assert_eq!(SessionHandlerCollators::get(), vec![1, 2, 3, 4]); - let collator = CandidateInfo { - who: 4, - deposit: 10, - }; - assert_eq!(CollatorSelection::candidates(), vec![collator]); - // assert_eq!(CollatorSelection::last_authored_block(4), 20); // NOTE: not used in manta fork - initialize_to_block(40); - // 3 gets kicked after 1 session delay - assert_eq!(SessionHandlerCollators::get(), vec![1, 2, 4]); - // kicked collator gets funds back - assert_eq!(Balances::free_balance(3), 100); - }); + new_test_ext().execute_with(|| { + assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(3))); + assert_ok!(Session::set_keys( + Origin::signed(3), + UintAuthorityId(3).into(), + vec![] + )); + assert_ok!(CollatorSelection::register_as_candidate(Origin::signed(4))); + assert_ok!(Session::set_keys( + Origin::signed(4), + UintAuthorityId(4).into(), + vec![] + )); + initialize_to_block(10); + assert_eq!(CollatorSelection::candidates().len(), 2); + initialize_to_block(20); + assert_eq!(SessionChangeBlock::get(), 20); + assert_eq!(CollatorSelection::candidates().len(), 2); + assert_eq!(Session::validators().len(), 4); // all candidates active + initialize_to_block(30); + // 4 authored all blocks in this the past session, gets to stay 3 was kicked on session change + assert_eq!(CollatorSelection::candidates().len(), 1); + // 3 will be kicked after 1 session delay + assert_eq!(SessionHandlerCollators::get(), vec![1, 2, 3, 4]); + let collator = CandidateInfo { + who: 4, + deposit: 10, + }; + assert_eq!(CollatorSelection::candidates(), vec![collator]); + // assert_eq!(CollatorSelection::last_authored_block(4), 20); // NOTE: not used in manta fork + initialize_to_block(40); + // 3 gets kicked after 1 session delay + assert_eq!(SessionHandlerCollators::get(), vec![1, 2, 4]); + // kicked collator gets funds back + assert_eq!(Balances::free_balance(3), 100); + }); } #[test] fn manta_kick_algorithm_normal_operation() { - new_test_ext().execute_with(|| { - // add collator candidates - setup_3_candidates(); - assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); - - // 80th percentile = 10, kick *below* 9, remove CHAD,EVE - BlocksPerCollatorThisSession::::insert(ALICE, 10); - BlocksPerCollatorThisSession::::insert(BOB, 10); - BlocksPerCollatorThisSession::::insert(CHAD, 4); - BlocksPerCollatorThisSession::::insert(DAVE, 9); - BlocksPerCollatorThisSession::::insert(EVE, 0); - assert_eq!( - CollatorSelection::evict_bad_collators(CollatorSelection::candidates()), - vec![EVE, CHAD] - ); - - // readd them - assert_ok!(CollatorSelection::register_as_candidate(Origin::signed( - CHAD - ))); - assert_ok!(CollatorSelection::register_as_candidate(Origin::signed( - EVE - ))); - - // Don't try kicking invulnerables ( ALICE and BOB ), percentile = 9, threshold is 8.1 => kick 8 and below - BlocksPerCollatorThisSession::::insert(ALICE, 0); - BlocksPerCollatorThisSession::::insert(BOB, 10); - BlocksPerCollatorThisSession::::insert(CHAD, 4); - BlocksPerCollatorThisSession::::insert(DAVE, 9); - BlocksPerCollatorThisSession::::insert(EVE, 0); - assert_eq!( - CollatorSelection::evict_bad_collators(CollatorSelection::candidates()), - vec![EVE, CHAD] - ); - }); + new_test_ext().execute_with(|| { + // add collator candidates + setup_3_candidates(); + assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); + + // 80th percentile = 10, kick *below* 9, remove CHAD,EVE + BlocksPerCollatorThisSession::::insert(ALICE, 10); + BlocksPerCollatorThisSession::::insert(BOB, 10); + BlocksPerCollatorThisSession::::insert(CHAD, 4); + BlocksPerCollatorThisSession::::insert(DAVE, 9); + BlocksPerCollatorThisSession::::insert(EVE, 0); + assert_eq!( + CollatorSelection::evict_bad_collators(CollatorSelection::candidates()), + vec![EVE, CHAD] + ); + + // readd them + assert_ok!(CollatorSelection::register_as_candidate(Origin::signed( + CHAD + ))); + assert_ok!(CollatorSelection::register_as_candidate(Origin::signed( + EVE + ))); + + // Don't try kicking invulnerables ( ALICE and BOB ), percentile = 9, threshold is 8.1 => kick 8 and below + BlocksPerCollatorThisSession::::insert(ALICE, 0); + BlocksPerCollatorThisSession::::insert(BOB, 10); + BlocksPerCollatorThisSession::::insert(CHAD, 4); + BlocksPerCollatorThisSession::::insert(DAVE, 9); + BlocksPerCollatorThisSession::::insert(EVE, 0); + assert_eq!( + CollatorSelection::evict_bad_collators(CollatorSelection::candidates()), + vec![EVE, CHAD] + ); + }); } #[test] fn manta_kick_algorithm_boundaries() { - new_test_ext().execute_with(|| { - // add collator candidates - setup_3_candidates(); - assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); - - let empty_vec = Vec::<::AccountId>::new(); - // Kick anyone not at perfect performance - EvictionBaseline::::put(Percent::from_percent(100)); - EvictionTolerance::::put(Percent::from_percent(0)); - - BlocksPerCollatorThisSession::::insert(CHAD, 9); - BlocksPerCollatorThisSession::::insert(DAVE, 11); - BlocksPerCollatorThisSession::::insert(EVE, 10); - assert_eq!( - CollatorSelection::evict_bad_collators(CollatorSelection::candidates()), - vec![CHAD, EVE] - ); - assert_ok!(CollatorSelection::register_as_candidate(Origin::signed( - CHAD - ))); - // Allow any underperformance => eviction disabled - EvictionTolerance::::put(Percent::from_percent(100)); - assert_eq!( - CollatorSelection::evict_bad_collators(CollatorSelection::candidates()), - empty_vec - ); - // 0-th percentile = use worst collator as benchmark => eviction disabled - EvictionBaseline::::put(Percent::from_percent(0)); - EvictionTolerance::::put(Percent::from_percent(0)); - assert_eq!( - CollatorSelection::evict_bad_collators(CollatorSelection::candidates()), - empty_vec - ); - // Same performance => no kick - EvictionBaseline::::put(Percent::from_percent(100)); - EvictionTolerance::::put(Percent::from_percent(0)); - BlocksPerCollatorThisSession::::insert(CHAD, 10); - BlocksPerCollatorThisSession::::insert(DAVE, 10); - assert_eq!( - CollatorSelection::evict_bad_collators(CollatorSelection::candidates()), - empty_vec - ); - // Exactly on threshold => no kick - EvictionBaseline::::put(Percent::from_percent(100)); - EvictionTolerance::::put(Percent::from_percent(10)); - BlocksPerCollatorThisSession::::insert(CHAD, 10); - BlocksPerCollatorThisSession::::insert(DAVE, 9); - assert_eq!( - CollatorSelection::evict_bad_collators(CollatorSelection::candidates()), - empty_vec - ); - // Rational threshold = 8.1, kick 8 and below - EvictionBaseline::::put(Percent::from_percent(100)); - EvictionTolerance::::put(Percent::from_percent(10)); - BlocksPerCollatorThisSession::::insert(CHAD, 8); - BlocksPerCollatorThisSession::::insert(DAVE, 10); - assert_eq!( - CollatorSelection::evict_bad_collators(CollatorSelection::candidates()), - vec![CHAD] - ); - }); + new_test_ext().execute_with(|| { + // add collator candidates + setup_3_candidates(); + assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); + + let empty_vec = Vec::<::AccountId>::new(); + // Kick anyone not at perfect performance + EvictionBaseline::::put(Percent::from_percent(100)); + EvictionTolerance::::put(Percent::from_percent(0)); + + BlocksPerCollatorThisSession::::insert(CHAD, 9); + BlocksPerCollatorThisSession::::insert(DAVE, 11); + BlocksPerCollatorThisSession::::insert(EVE, 10); + assert_eq!( + CollatorSelection::evict_bad_collators(CollatorSelection::candidates()), + vec![CHAD, EVE] + ); + assert_ok!(CollatorSelection::register_as_candidate(Origin::signed( + CHAD + ))); + // Allow any underperformance => eviction disabled + EvictionTolerance::::put(Percent::from_percent(100)); + assert_eq!( + CollatorSelection::evict_bad_collators(CollatorSelection::candidates()), + empty_vec + ); + // 0-th percentile = use worst collator as benchmark => eviction disabled + EvictionBaseline::::put(Percent::from_percent(0)); + EvictionTolerance::::put(Percent::from_percent(0)); + assert_eq!( + CollatorSelection::evict_bad_collators(CollatorSelection::candidates()), + empty_vec + ); + // Same performance => no kick + EvictionBaseline::::put(Percent::from_percent(100)); + EvictionTolerance::::put(Percent::from_percent(0)); + BlocksPerCollatorThisSession::::insert(CHAD, 10); + BlocksPerCollatorThisSession::::insert(DAVE, 10); + assert_eq!( + CollatorSelection::evict_bad_collators(CollatorSelection::candidates()), + empty_vec + ); + // Exactly on threshold => no kick + EvictionBaseline::::put(Percent::from_percent(100)); + EvictionTolerance::::put(Percent::from_percent(10)); + BlocksPerCollatorThisSession::::insert(CHAD, 10); + BlocksPerCollatorThisSession::::insert(DAVE, 9); + assert_eq!( + CollatorSelection::evict_bad_collators(CollatorSelection::candidates()), + empty_vec + ); + // Rational threshold = 8.1, kick 8 and below + EvictionBaseline::::put(Percent::from_percent(100)); + EvictionTolerance::::put(Percent::from_percent(10)); + BlocksPerCollatorThisSession::::insert(CHAD, 8); + BlocksPerCollatorThisSession::::insert(DAVE, 10); + assert_eq!( + CollatorSelection::evict_bad_collators(CollatorSelection::candidates()), + vec![CHAD] + ); + }); } #[test] fn manta_collator_onboarding_sequence() { - new_test_ext().execute_with(|| { - // add new collator candidates, they will become validators next session - // Sessions rotate every 10 blocks, so we kick on each x0-th block - setup_3_candidates(); - assert_eq!(Session::validators(), vec![ALICE, BOB]); - assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); + new_test_ext().execute_with(|| { + // add new collator candidates, they will become validators next session + // Sessions rotate every 10 blocks, so we kick on each x0-th block + setup_3_candidates(); + assert_eq!(Session::validators(), vec![ALICE, BOB]); + assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); - // RAD: mock.rs specifies DAVE as author of all blocks in find_author, DAVE will produce all 10 blocks in a session - // RAD: other tests like authorship_event_handler depend on DAVE producing blocks - initialize_to_block(10); - assert_eq!(Session::validators(), vec![ALICE, BOB]); // collators ALICE and BOB must not have been kicked, invulnerable - assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); // collators CHAD,DAVE,EVE are not yet active + // RAD: mock.rs specifies DAVE as author of all blocks in find_author, DAVE will produce all 10 blocks in a session + // RAD: other tests like authorship_event_handler depend on DAVE producing blocks + initialize_to_block(10); + assert_eq!(Session::validators(), vec![ALICE, BOB]); // collators ALICE and BOB must not have been kicked, invulnerable + assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); // collators CHAD,DAVE,EVE are not yet active - initialize_to_block(20); - assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); // all collators online - }); + initialize_to_block(20); + assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); // all collators online + }); } #[test] fn manta_dont_kick_invulnerables() { - new_test_ext().execute_with(|| { - setup_3_candidates(); - initialize_to_block(20); - assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); + new_test_ext().execute_with(|| { + setup_3_candidates(); + initialize_to_block(20); + assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); - initialize_to_block(29); - set_all_validator_perf_to(10); // NOTE: Validator DAVE produces 10 blocks each session in testing - BlocksPerCollatorThisSession::::insert(1u64, 0); - BlocksPerCollatorThisSession::::insert(2u64, 0); - assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); - assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); - }); + initialize_to_block(29); + set_all_validator_perf_to(10); // NOTE: Validator DAVE produces 10 blocks each session in testing + BlocksPerCollatorThisSession::::insert(1u64, 0); + BlocksPerCollatorThisSession::::insert(2u64, 0); + assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); + assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); + }); } #[test] fn manta_remove_underperformer_even_if_it_recovers() { - new_test_ext().execute_with(|| { - setup_3_candidates(); - initialize_to_block(20); - assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); - - initialize_to_block(29); - set_all_validator_perf_to(10); - BlocksPerCollatorThisSession::::insert(EVE, 5); - assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); - assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); - initialize_to_block(39); - set_all_validator_perf_to(10); - assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); - assert_eq!(candidate_ids(), vec![CHAD, DAVE]); // EVE got removed from candidates - initialize_to_block(49); - set_all_validator_perf_to(10); - assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE]); // and from validators - assert_eq!(candidate_ids(), vec![CHAD, DAVE]); - }); + new_test_ext().execute_with(|| { + setup_3_candidates(); + initialize_to_block(20); + assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); + + initialize_to_block(29); + set_all_validator_perf_to(10); + BlocksPerCollatorThisSession::::insert(EVE, 5); + assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); + assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); + initialize_to_block(39); + set_all_validator_perf_to(10); + assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); + assert_eq!(candidate_ids(), vec![CHAD, DAVE]); // EVE got removed from candidates + initialize_to_block(49); + set_all_validator_perf_to(10); + assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE]); // and from validators + assert_eq!(candidate_ids(), vec![CHAD, DAVE]); + }); } #[test] fn manta_remove_underperformer_even_if_it_is_immediately_readded_as_candidate() { - // TC3: EVE underperforms for one session, is kicked and immediately readded - loses one session then onboards again - new_test_ext().execute_with(|| { - setup_3_candidates(); - initialize_to_block(20); - assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); - - initialize_to_block(29); - set_all_validator_perf_to(10); - BlocksPerCollatorThisSession::::insert(EVE, 0); - initialize_to_block(30); - assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); - assert_eq!(candidate_ids(), vec![CHAD, DAVE]); // EVE got kicked - assert_ok!(CollatorSelection::register_as_candidate(Origin::signed( - EVE - ))); // and is immediately readded - assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); - initialize_to_block(39); - set_all_validator_perf_to(10); - initialize_to_block(40); - assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE]); // is removed from validators - assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); // but not from candiadates - initialize_to_block(49); - set_all_validator_perf_to(10); - initialize_to_block(50); - assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); // and onboards again one session later - assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); - }) + // TC3: EVE underperforms for one session, is kicked and immediately readded - loses one session then onboards again + new_test_ext().execute_with(|| { + setup_3_candidates(); + initialize_to_block(20); + assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); + + initialize_to_block(29); + set_all_validator_perf_to(10); + BlocksPerCollatorThisSession::::insert(EVE, 0); + initialize_to_block(30); + assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); + assert_eq!(candidate_ids(), vec![CHAD, DAVE]); // EVE got kicked + assert_ok!(CollatorSelection::register_as_candidate(Origin::signed( + EVE + ))); // and is immediately readded + assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); + initialize_to_block(39); + set_all_validator_perf_to(10); + initialize_to_block(40); + assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE]); // is removed from validators + assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); // but not from candiadates + initialize_to_block(49); + set_all_validator_perf_to(10); + initialize_to_block(50); + assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); // and onboards again one session later + assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); + }) } #[test] fn manta_dont_kick_uniform_underperformance() { - // TC4: Everybody underperforms (algorithm knows no target number, just relative performance), nobody gets kicked - new_test_ext().execute_with(|| { - setup_3_candidates(); - initialize_to_block(20); - assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); + // TC4: Everybody underperforms (algorithm knows no target number, just relative performance), nobody gets kicked + new_test_ext().execute_with(|| { + setup_3_candidates(); + initialize_to_block(20); + assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); - set_all_validator_perf_to(6); - initialize_to_block(30); - assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); - assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); - }) + set_all_validator_perf_to(6); + initialize_to_block(30); + assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); + assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); + }) } #[test] fn manta_dont_kick_collator_at_tolerance() { - // TC5: EVE is on threshold, don't kick ( at 5 nodes, the 80th percentile is the second highest value of the set = 100, 10% threshold is 10 ) - new_test_ext().execute_with(|| { - setup_3_candidates(); - initialize_to_block(20); - assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); - - initialize_to_block(29); - set_all_validator_perf_to(100); - BlocksPerCollatorThisSession::::insert(EVE, 90); - initialize_to_block(39); - set_all_validator_perf_to(100); - assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); - }) + // TC5: EVE is on threshold, don't kick ( at 5 nodes, the 80th percentile is the second highest value of the set = 100, 10% threshold is 10 ) + new_test_ext().execute_with(|| { + setup_3_candidates(); + initialize_to_block(20); + assert_eq!(Session::validators(), vec![ALICE, BOB, CHAD, DAVE, EVE]); + + initialize_to_block(29); + set_all_validator_perf_to(100); + BlocksPerCollatorThisSession::::insert(EVE, 90); + initialize_to_block(39); + set_all_validator_perf_to(100); + assert_eq!(candidate_ids(), vec![CHAD, DAVE, EVE]); + }) } #[test] #[should_panic = "duplicate invulnerables in genesis."] fn cannot_set_genesis_value_twice() { - sp_tracing::try_init_simple(); - let mut t = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); - let invulnerables = vec![1, 1]; - - let collator_selection = collator_selection::GenesisConfig:: { - desired_candidates: 2, - eviction_baseline: Percent::from_percent(80), - eviction_tolerance: Percent::from_percent(10), - candidacy_bond: 10, - invulnerables, - }; - // collator selection must be initialized before session. - collator_selection.assimilate_storage(&mut t).unwrap(); + sp_tracing::try_init_simple(); + let mut t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); + let invulnerables = vec![1, 1]; + + let collator_selection = collator_selection::GenesisConfig:: { + desired_candidates: 2, + eviction_baseline: Percent::from_percent(80), + eviction_tolerance: Percent::from_percent(10), + candidacy_bond: 10, + invulnerables, + }; + // collator selection must be initialized before session. + collator_selection.assimilate_storage(&mut t).unwrap(); } #[test] fn register_candidate_should_work() { - new_test_ext().execute_with(|| { - // add collator by root should work - let candidate = 3; - assert_ok!(CollatorSelection::register_candidate( - Origin::signed(RootAccount::get()), - candidate - )); - - // cannot add the same collator twice - assert_noop!( - CollatorSelection::register_candidate(Origin::signed(RootAccount::get()), candidate), - Error::::AlreadyCandidate - ); - - let collator = CandidateInfo { - who: candidate, - deposit: 10, - }; - assert_eq!(CollatorSelection::candidates(), vec![collator]); - - // normal user cannot add collator - assert_noop!( - CollatorSelection::register_candidate(Origin::signed(5), 4), - BadOrigin, - ); - - // Cannot add collator if it reaches desired candidate - // Now it should be 2 candidates. - assert_ok!(CollatorSelection::register_candidate( - Origin::signed(RootAccount::get()), - 4 - )); - assert_eq!(CollatorSelection::candidates().len(), 2); - assert_noop!( - CollatorSelection::register_candidate(Origin::signed(RootAccount::get()), 5), - Error::::TooManyCandidates - ); - }); + new_test_ext().execute_with(|| { + // add collator by root should work + let candidate = 3; + assert_ok!(CollatorSelection::register_candidate( + Origin::signed(RootAccount::get()), + candidate + )); + + // cannot add the same collator twice + assert_noop!( + CollatorSelection::register_candidate(Origin::signed(RootAccount::get()), candidate), + Error::::AlreadyCandidate + ); + + let collator = CandidateInfo { + who: candidate, + deposit: 10, + }; + assert_eq!(CollatorSelection::candidates(), vec![collator]); + + // normal user cannot add collator + assert_noop!( + CollatorSelection::register_candidate(Origin::signed(5), 4), + BadOrigin, + ); + + // Cannot add collator if it reaches desired candidate + // Now it should be 2 candidates. + assert_ok!(CollatorSelection::register_candidate( + Origin::signed(RootAccount::get()), + 4 + )); + assert_eq!(CollatorSelection::candidates().len(), 2); + assert_noop!( + CollatorSelection::register_candidate(Origin::signed(RootAccount::get()), 5), + Error::::TooManyCandidates + ); + }); } #[test] fn remove_collator_should_work() { - new_test_ext().execute_with(|| { - // add collator by root should work - let candidate = 3; - assert_ok!(CollatorSelection::register_candidate( - Origin::signed(RootAccount::get()), - candidate - )); - - // normal user cannot remove specified collator - assert_noop!( - CollatorSelection::remove_collator(Origin::signed(5), candidate), - BadOrigin - ); - - // remove collator should work - assert_ok!(CollatorSelection::remove_collator( - Origin::signed(RootAccount::get()), - candidate - )); - - // cannot remove a unregistered collator - assert_noop!( - CollatorSelection::remove_collator(Origin::signed(RootAccount::get()), candidate), - Error::::NotCandidate - ); - - // Cannot remove invulnerables - let invulnerable = 2; - assert_noop!( - CollatorSelection::remove_collator(Origin::signed(RootAccount::get()), invulnerable), - Error::::NotAllowRemoveInvulnerable - ); - }); + new_test_ext().execute_with(|| { + // add collator by root should work + let candidate = 3; + assert_ok!(CollatorSelection::register_candidate( + Origin::signed(RootAccount::get()), + candidate + )); + + // normal user cannot remove specified collator + assert_noop!( + CollatorSelection::remove_collator(Origin::signed(5), candidate), + BadOrigin + ); + + // remove collator should work + assert_ok!(CollatorSelection::remove_collator( + Origin::signed(RootAccount::get()), + candidate + )); + + // cannot remove a unregistered collator + assert_noop!( + CollatorSelection::remove_collator(Origin::signed(RootAccount::get()), candidate), + Error::::NotCandidate + ); + + // Cannot remove invulnerables + let invulnerable = 2; + assert_noop!( + CollatorSelection::remove_collator(Origin::signed(RootAccount::get()), invulnerable), + Error::::NotAllowRemoveInvulnerable + ); + }); } #[test] fn increase_bond_after_register_candidate() { - // It's a corner case: - // 1. Set orignal bond as 10KMA. - // 2. Register candidate. - // 3. Increase bond to 15KMA. - // 3. Unregister candidate. - // 4. The owner should get 10KMA back instead of 15KMA. - // Increasing bond should not affect previous candidates. - new_test_ext().execute_with(|| { - // add candidate_1 by root - let candidate_1 = 3; - - // reserve some tokens first - let locked_amount = 50; - assert_ok!(::Currency::reserve( - &candidate_1, - locked_amount - )); - - // get free balances after first reserve - let candidate_1_balances_before_registration = Balances::free_balance(candidate_1); - - assert_ok!(CollatorSelection::register_candidate( - Origin::signed(RootAccount::get()), - candidate_1 - )); - - // check candidate_1's reserved balance - let prev_bond = CollatorSelection::candidacy_bond(); - // candidate_1 should be reserved prev_bond KMA - assert_eq!( - prev_bond + locked_amount, - Balances::reserved_balance(candidate_1) - ); - - // increase bond - let new_bond = prev_bond + 5; - assert_ok!(CollatorSelection::set_candidacy_bond( - Origin::signed(RootAccount::get()), - new_bond - )); - - // register new candidate after increase bond - let candidate_2 = 4; - - let locked_amount_2 = 55; - assert_ok!(::Currency::reserve( - &candidate_2, - locked_amount_2 - )); - - // get free balances after first reserve - let candidate_2_balances_before_registration = Balances::free_balance(candidate_2); - - assert_ok!(CollatorSelection::register_candidate( - Origin::signed(RootAccount::get()), - candidate_2 - )); - // check new bond - assert_eq!(new_bond, CollatorSelection::candidacy_bond()); - // candidate_2 should be reserved new_bond KMA - assert_eq!( - new_bond + locked_amount_2, - Balances::reserved_balance(candidate_2) - ); - - // remove candidate_1 - assert_ok!(CollatorSelection::remove_collator( - Origin::signed(RootAccount::get()), - candidate_1 - )); - // check candidate_1 - assert_eq!(locked_amount, Balances::reserved_balance(candidate_1)); - assert_eq!( - candidate_1_balances_before_registration, - Balances::free_balance(candidate_1) - ); - - // remove candidate_2 - assert_ok!(CollatorSelection::remove_collator( - Origin::signed(RootAccount::get()), - candidate_2 - )); - // check candidate_2 - assert_eq!(locked_amount_2, Balances::reserved_balance(candidate_2)); - assert_eq!( - candidate_2_balances_before_registration, - Balances::free_balance(candidate_2) - ); - }); + // It's a corner case: + // 1. Set orignal bond as 10KMA. + // 2. Register candidate. + // 3. Increase bond to 15KMA. + // 3. Unregister candidate. + // 4. The owner should get 10KMA back instead of 15KMA. + // Increasing bond should not affect previous candidates. + new_test_ext().execute_with(|| { + // add candidate_1 by root + let candidate_1 = 3; + + // reserve some tokens first + let locked_amount = 50; + assert_ok!(::Currency::reserve( + &candidate_1, + locked_amount + )); + + // get free balances after first reserve + let candidate_1_balances_before_registration = Balances::free_balance(candidate_1); + + assert_ok!(CollatorSelection::register_candidate( + Origin::signed(RootAccount::get()), + candidate_1 + )); + + // check candidate_1's reserved balance + let prev_bond = CollatorSelection::candidacy_bond(); + // candidate_1 should be reserved prev_bond KMA + assert_eq!( + prev_bond + locked_amount, + Balances::reserved_balance(candidate_1) + ); + + // increase bond + let new_bond = prev_bond + 5; + assert_ok!(CollatorSelection::set_candidacy_bond( + Origin::signed(RootAccount::get()), + new_bond + )); + + // register new candidate after increase bond + let candidate_2 = 4; + + let locked_amount_2 = 55; + assert_ok!(::Currency::reserve( + &candidate_2, + locked_amount_2 + )); + + // get free balances after first reserve + let candidate_2_balances_before_registration = Balances::free_balance(candidate_2); + + assert_ok!(CollatorSelection::register_candidate( + Origin::signed(RootAccount::get()), + candidate_2 + )); + // check new bond + assert_eq!(new_bond, CollatorSelection::candidacy_bond()); + // candidate_2 should be reserved new_bond KMA + assert_eq!( + new_bond + locked_amount_2, + Balances::reserved_balance(candidate_2) + ); + + // remove candidate_1 + assert_ok!(CollatorSelection::remove_collator( + Origin::signed(RootAccount::get()), + candidate_1 + )); + // check candidate_1 + assert_eq!(locked_amount, Balances::reserved_balance(candidate_1)); + assert_eq!( + candidate_1_balances_before_registration, + Balances::free_balance(candidate_1) + ); + + // remove candidate_2 + assert_ok!(CollatorSelection::remove_collator( + Origin::signed(RootAccount::get()), + candidate_2 + )); + // check candidate_2 + assert_eq!(locked_amount_2, Balances::reserved_balance(candidate_2)); + assert_eq!( + candidate_2_balances_before_registration, + Balances::free_balance(candidate_2) + ); + }); } diff --git a/pallets/collator-selection/src/weights.rs b/pallets/collator-selection/src/weights.rs index 3f75613ad..e59850fb6 100644 --- a/pallets/collator-selection/src/weights.rs +++ b/pallets/collator-selection/src/weights.rs @@ -43,210 +43,210 @@ use sp_std::marker::PhantomData; /// Weight functions needed for manta_collator_selection. pub trait WeightInfo { - fn set_invulnerables(b: u32, ) -> Weight; - fn set_desired_candidates() -> Weight; - fn set_candidacy_bond() -> Weight; - fn set_eviction_baseline() -> Weight; - fn set_eviction_tolerance() -> Weight; - fn register_as_candidate(c: u32, ) -> Weight; - fn leave_intent(c: u32, ) -> Weight; - fn remove_collator(c: u32, ) -> Weight; - fn register_candidate(c: u32, ) -> Weight; - fn note_author() -> Weight; - fn new_session(c: u32, ) -> Weight; + fn set_invulnerables(b: u32, ) -> Weight; + fn set_desired_candidates() -> Weight; + fn set_candidacy_bond() -> Weight; + fn set_eviction_baseline() -> Weight; + fn set_eviction_tolerance() -> Weight; + fn register_as_candidate(c: u32, ) -> Weight; + fn leave_intent(c: u32, ) -> Weight; + fn remove_collator(c: u32, ) -> Weight; + fn register_candidate(c: u32, ) -> Weight; + fn note_author() -> Weight; + fn new_session(c: u32, ) -> Weight; } /// Weights for manta_collator_selection using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { - // Storage: CollatorSelection Invulnerables (r:0 w:1) - fn set_invulnerables(b: u32, ) -> Weight { - (10_961_000 as Weight) - // Standard Error: 11_000 - .saturating_add((117_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection DesiredCandidates (r:0 w:1) - fn set_desired_candidates() -> Weight { - (12_362_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection CandidacyBond (r:0 w:1) - fn set_candidacy_bond() -> Weight { - (10_528_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection EvictionBaseline (r:0 w:1) - fn set_eviction_baseline() -> Weight { - (10_057_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection EvictionTolerance (r:0 w:1) - fn set_eviction_tolerance() -> Weight { - (9_979_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:1) - // Storage: CollatorSelection DesiredCandidates (r:1 w:0) - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: Session NextKeys (r:1 w:0) - // Storage: CollatorSelection CandidacyBond (r:1 w:0) - fn register_as_candidate(c: u32, ) -> Weight { - (48_923_000 as Weight) - // Standard Error: 14_000 - .saturating_add((449_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:1) - fn leave_intent(c: u32, ) -> Weight { - (32_970_000 as Weight) - // Standard Error: 5_000 - .saturating_add((389_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: CollatorSelection Candidates (r:1 w:1) - fn remove_collator(c: u32, ) -> Weight { - (36_220_000 as Weight) - // Standard Error: 5_000 - .saturating_add((360_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:1) - // Storage: CollatorSelection DesiredCandidates (r:1 w:0) - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: Session NextKeys (r:1 w:0) - // Storage: CollatorSelection CandidacyBond (r:1 w:0) - fn register_candidate(c: u32, ) -> Weight { - (47_774_000 as Weight) - // Standard Error: 6_000 - .saturating_add((421_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:2 w:2) - // Storage: CollatorSelection BlocksPerCollatorThisSession (r:1 w:1) - // Storage: System BlockWeight (r:1 w:1) - fn note_author() -> Weight { - (44_201_000 as Weight) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:0) - // Storage: CollatorSelection EvictionBaseline (r:1 w:0) - // Storage: CollatorSelection EvictionTolerance (r:1 w:0) - // Storage: CollatorSelection BlocksPerCollatorThisSession (r:2 w:2) - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: System BlockWeight (r:1 w:1) - // Storage: Session Validators (r:1 w:0) - // Storage: System Account (r:1 w:1) - fn new_session(c: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 163_000 - .saturating_add((33_635_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads(6 as Weight)) - .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) - } + // Storage: CollatorSelection Invulnerables (r:0 w:1) + fn set_invulnerables(b: u32, ) -> Weight { + (10_961_000 as Weight) + // Standard Error: 11_000 + .saturating_add((117_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection DesiredCandidates (r:0 w:1) + fn set_desired_candidates() -> Weight { + (12_362_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection CandidacyBond (r:0 w:1) + fn set_candidacy_bond() -> Weight { + (10_528_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection EvictionBaseline (r:0 w:1) + fn set_eviction_baseline() -> Weight { + (10_057_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection EvictionTolerance (r:0 w:1) + fn set_eviction_tolerance() -> Weight { + (9_979_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:1) + // Storage: CollatorSelection DesiredCandidates (r:1 w:0) + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: Session NextKeys (r:1 w:0) + // Storage: CollatorSelection CandidacyBond (r:1 w:0) + fn register_as_candidate(c: u32, ) -> Weight { + (48_923_000 as Weight) + // Standard Error: 14_000 + .saturating_add((449_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:1) + fn leave_intent(c: u32, ) -> Weight { + (32_970_000 as Weight) + // Standard Error: 5_000 + .saturating_add((389_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: CollatorSelection Candidates (r:1 w:1) + fn remove_collator(c: u32, ) -> Weight { + (36_220_000 as Weight) + // Standard Error: 5_000 + .saturating_add((360_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:1) + // Storage: CollatorSelection DesiredCandidates (r:1 w:0) + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: Session NextKeys (r:1 w:0) + // Storage: CollatorSelection CandidacyBond (r:1 w:0) + fn register_candidate(c: u32, ) -> Weight { + (47_774_000 as Weight) + // Standard Error: 6_000 + .saturating_add((421_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:2 w:2) + // Storage: CollatorSelection BlocksPerCollatorThisSession (r:1 w:1) + // Storage: System BlockWeight (r:1 w:1) + fn note_author() -> Weight { + (44_201_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:0) + // Storage: CollatorSelection EvictionBaseline (r:1 w:0) + // Storage: CollatorSelection EvictionTolerance (r:1 w:0) + // Storage: CollatorSelection BlocksPerCollatorThisSession (r:2 w:2) + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: System BlockWeight (r:1 w:1) + // Storage: Session Validators (r:1 w:0) + // Storage: System Account (r:1 w:1) + fn new_session(c: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 163_000 + .saturating_add((33_635_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(6 as Weight)) + .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: CollatorSelection Invulnerables (r:0 w:1) - fn set_invulnerables(b: u32, ) -> Weight { - (10_961_000 as Weight) - // Standard Error: 11_000 - .saturating_add((117_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection DesiredCandidates (r:0 w:1) - fn set_desired_candidates() -> Weight { - (12_362_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection CandidacyBond (r:0 w:1) - fn set_candidacy_bond() -> Weight { - (10_528_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection EvictionBaseline (r:0 w:1) - fn set_eviction_baseline() -> Weight { - (10_057_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection EvictionTolerance (r:0 w:1) - fn set_eviction_tolerance() -> Weight { - (9_979_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:1) - // Storage: CollatorSelection DesiredCandidates (r:1 w:0) - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: Session NextKeys (r:1 w:0) - // Storage: CollatorSelection CandidacyBond (r:1 w:0) - fn register_as_candidate(c: u32, ) -> Weight { - (48_923_000 as Weight) - // Standard Error: 14_000 - .saturating_add((449_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:1) - fn leave_intent(c: u32, ) -> Weight { - (32_970_000 as Weight) - // Standard Error: 5_000 - .saturating_add((389_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: CollatorSelection Candidates (r:1 w:1) - fn remove_collator(c: u32, ) -> Weight { - (36_220_000 as Weight) - // Standard Error: 5_000 - .saturating_add((360_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:1) - // Storage: CollatorSelection DesiredCandidates (r:1 w:0) - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: Session NextKeys (r:1 w:0) - // Storage: CollatorSelection CandidacyBond (r:1 w:0) - fn register_candidate(c: u32, ) -> Weight { - (47_774_000 as Weight) - // Standard Error: 6_000 - .saturating_add((421_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:2 w:2) - // Storage: CollatorSelection BlocksPerCollatorThisSession (r:1 w:1) - // Storage: System BlockWeight (r:1 w:1) - fn note_author() -> Weight { - (44_201_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:0) - // Storage: CollatorSelection EvictionBaseline (r:1 w:0) - // Storage: CollatorSelection EvictionTolerance (r:1 w:0) - // Storage: CollatorSelection BlocksPerCollatorThisSession (r:2 w:2) - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: System BlockWeight (r:1 w:1) - // Storage: Session Validators (r:1 w:0) - // Storage: System Account (r:1 w:1) - fn new_session(c: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 163_000 - .saturating_add((33_635_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(RocksDbWeight::get().reads(6 as Weight)) - .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) - } + // Storage: CollatorSelection Invulnerables (r:0 w:1) + fn set_invulnerables(b: u32, ) -> Weight { + (10_961_000 as Weight) + // Standard Error: 11_000 + .saturating_add((117_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection DesiredCandidates (r:0 w:1) + fn set_desired_candidates() -> Weight { + (12_362_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection CandidacyBond (r:0 w:1) + fn set_candidacy_bond() -> Weight { + (10_528_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection EvictionBaseline (r:0 w:1) + fn set_eviction_baseline() -> Weight { + (10_057_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection EvictionTolerance (r:0 w:1) + fn set_eviction_tolerance() -> Weight { + (9_979_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:1) + // Storage: CollatorSelection DesiredCandidates (r:1 w:0) + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: Session NextKeys (r:1 w:0) + // Storage: CollatorSelection CandidacyBond (r:1 w:0) + fn register_as_candidate(c: u32, ) -> Weight { + (48_923_000 as Weight) + // Standard Error: 14_000 + .saturating_add((449_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:1) + fn leave_intent(c: u32, ) -> Weight { + (32_970_000 as Weight) + // Standard Error: 5_000 + .saturating_add((389_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: CollatorSelection Candidates (r:1 w:1) + fn remove_collator(c: u32, ) -> Weight { + (36_220_000 as Weight) + // Standard Error: 5_000 + .saturating_add((360_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:1) + // Storage: CollatorSelection DesiredCandidates (r:1 w:0) + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: Session NextKeys (r:1 w:0) + // Storage: CollatorSelection CandidacyBond (r:1 w:0) + fn register_candidate(c: u32, ) -> Weight { + (47_774_000 as Weight) + // Standard Error: 6_000 + .saturating_add((421_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:2 w:2) + // Storage: CollatorSelection BlocksPerCollatorThisSession (r:1 w:1) + // Storage: System BlockWeight (r:1 w:1) + fn note_author() -> Weight { + (44_201_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:0) + // Storage: CollatorSelection EvictionBaseline (r:1 w:0) + // Storage: CollatorSelection EvictionTolerance (r:1 w:0) + // Storage: CollatorSelection BlocksPerCollatorThisSession (r:2 w:2) + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: System BlockWeight (r:1 w:1) + // Storage: Session Validators (r:1 w:0) + // Storage: System Account (r:1 w:1) + fn new_session(c: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 163_000 + .saturating_add((33_635_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(RocksDbWeight::get().reads(6 as Weight)) + .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) + } } diff --git a/pallets/manta-pay/Cargo.toml b/pallets/manta-pay/Cargo.toml index 354d1a16f..9a216f6d5 100644 --- a/pallets/manta-pay/Cargo.toml +++ b/pallets/manta-pay/Cargo.toml @@ -1,13 +1,13 @@ [package] -authors = ['Manta Network'] +authors = ['Manta Network'] description = 'Pallet implementing the MantaPay protocol.' -edition = "2021" -homepage = 'https://manta.network' -license = 'GPL-3.0' -name = 'pallet-manta-pay' -readme = 'README.md' -repository = 'https://github.com/Manta-Network/Manta/' -version = '0.4.0' +edition = "2021" +homepage = 'https://manta.network' +license = 'GPL-3.0' +name = 'pallet-manta-pay' +readme = 'README.md' +repository = 'https://github.com/Manta-Network/Manta/' +version = '0.4.0' [package.metadata.docs.rs] # To build locally: @@ -25,12 +25,12 @@ default = ["std"] # RPC Interface rpc = [ - "jsonrpc-core", - "jsonrpc-core-client", - "jsonrpc-derive", - "serde", - "sp-api", - "sp-blockchain", + "jsonrpc-core", + "jsonrpc-core-client", + "jsonrpc-derive", + "serde", + "sp-api", + "sp-blockchain", ] # Runtime API @@ -38,37 +38,37 @@ runtime = ["sp-api"] # Runtime Benchmarks runtime-benchmarks = [ - "frame-benchmarking", - "frame-support/runtime-benchmarks", - "frame-system/runtime-benchmarks", - "manta-primitives/runtime-benchmarks", + "frame-benchmarking", + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "manta-primitives/runtime-benchmarks", ] # Serde Serialization serde = [ - "manta-pay/serde", - "manta-util/serde", - "manta-util/serde_with", + "manta-pay/serde", + "manta-util/serde", + "manta-util/serde_with", ] # Standard Library std = [ - "frame-benchmarking/std", - "frame-system/std", - "sp-runtime/std", - "sp-std/std", - "manta-primitives/std", + "frame-benchmarking/std", + "frame-system/std", + "sp-runtime/std", + "sp-std/std", + "manta-primitives/std", ] # Precompute Benchmark Transactions precompute-coins = [ - "anyhow", - "indoc", - "manta-accounting/test", - "manta-sdk/download", - "manta-util/std", - "rand", - "tempfile", + "anyhow", + "indoc", + "manta-accounting/test", + "manta-sdk/download", + "manta-util/std", + "rand", + "tempfile", ] [dependencies] @@ -82,10 +82,10 @@ tempfile = { version = "3.3.0", optional = true } frame-benchmarking = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18", default-features = false, optional = true } frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18", default-features = false } frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18", default-features = false } -sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18", default-features = false } -sp-std = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18", default-features = false } scale-codec = { package = "parity-scale-codec", version = '3.0.0', default-features = false, features = ["derive", "max-encoded-len"] } scale-info = { version = "2.0.0", default-features = false, features = ["derive"] } +sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18", default-features = false } +sp-std = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18", default-features = false } sp-api = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18", optional = true, default-features = false } sp-blockchain = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18", optional = true, default-features = false } @@ -99,22 +99,22 @@ jsonrpc-derive = { version = "18.0.0", optional = true, default-features = false manta-accounting = { git = "https://github.com/manta-network/manta-rs.git", tag = "v0.5.0", default-features = false } manta-crypto = { git = "https://github.com/manta-network/manta-rs.git", tag = "v0.5.0", default-features = false } manta-pay = { git = "https://github.com/manta-network/manta-rs.git", tag = "v0.5.0", default-features = false, features = ["groth16", "scale"] } +manta-primitives = { path = "../../primitives", default-features = false } manta-sdk = { git = "https://github.com/manta-network/sdk.git", default-features = false } manta-util = { git = "https://github.com/manta-network/manta-rs.git", tag = "v0.5.0", default-features = false } -manta-primitives = { path = "../../primitives", default-features = false } [dev-dependencies] bencher = "0.1.5" criterion = "0.3.4" lazy_static = "1.4.0" manta-accounting = { git = "https://github.com/manta-network/manta-rs.git", tag = "v0.5.0", features = ["test"] } -sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18"} -sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18"} -pallet-balances = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } -pallet-assets = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } -pallet-asset-manager = { path = "../asset-manager"} manta-sdk = { git = "https://github.com/manta-network/sdk.git", features = ["download"] } +manta-util = { git = "https://github.com/manta-network/manta-rs.git", tag = "v0.5.0", features = ["std"] } +pallet-asset-manager = { path = "../asset-manager" } +pallet-assets = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } +pallet-balances = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } rand = "0.8.4" +sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18" } +sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18" } tempfile = "3.3.0" xcm = { git = 'https://github.com/paritytech/polkadot.git', branch = "release-v0.9.18" } -manta-util = { git = "https://github.com/manta-network/manta-rs.git", tag = "v0.5.0", features = ["std"] } diff --git a/pallets/manta-pay/src/benchmark/mod.rs b/pallets/manta-pay/src/benchmark/mod.rs index 4b817f3dc..45e5919fb 100644 --- a/pallets/manta-pay/src/benchmark/mod.rs +++ b/pallets/manta-pay/src/benchmark/mod.rs @@ -1,31 +1,31 @@ -// Copyright 2019-2022 Manta Network. -// This file is part of pallet-manta-pay. +// Copyright 2020-2022 Manta Network. +// This file is part of Manta. // -// pallet-manta-pay is free software: you can redistribute it and/or modify +// Manta 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. // -// pallet-manta-pay is distributed in the hope that it will be useful, +// Manta 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 pallet-manta-pay. If not, see . +// along with Manta. If not, see . use crate::{ - benchmark::precomputed_coins::{ - MINT, PRIVATE_TRANSFER, PRIVATE_TRANSFER_INPUT, RECLAIM, RECLAIM_INPUT, - }, - Asset, Call, Config, Event, Pallet, TransferPost, + benchmark::precomputed_coins::{ + MINT, PRIVATE_TRANSFER, PRIVATE_TRANSFER_INPUT, RECLAIM, RECLAIM_INPUT, + }, + Asset, Call, Config, Event, Pallet, TransferPost, }; use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller}; use frame_system::RawOrigin; use manta_primitives::{ - assets::{AssetConfig, AssetRegistrar, FungibleLedger}, - constants::DEFAULT_ASSET_ED, - types::{AssetId, Balance}, + assets::{AssetConfig, AssetRegistrar, FungibleLedger}, + constants::DEFAULT_ASSET_ED, + types::{AssetId, Balance}, }; use scale_codec::Decode; @@ -35,101 +35,101 @@ mod precomputed_coins; #[inline] pub fn assert_last_event(event: E) where - T: Config, - E: Into<::Event>, + T: Config, + E: Into<::Event>, { - let events = frame_system::Pallet::::events(); - assert_eq!(events[events.len() - 1].event, event.into().into()); + let events = frame_system::Pallet::::events(); + assert_eq!(events[events.len() - 1].event, event.into().into()); } /// Init assets for manta-pay #[inline] pub fn init_asset(owner: &T::AccountId, id: AssetId, value: Balance) where - T: Config, + T: Config, { - let metadata = >::AssetRegistrarMetadata::default(); - let storage_metadata: >::StorageMetadata = metadata.into(); - >::AssetRegistrar::create_asset( - id, - DEFAULT_ASSET_ED, - storage_metadata, - true, - ) - .expect("Unable to create asset."); - let pallet_account: T::AccountId = Pallet::::account_id(); - >::FungibleLedger::mint(id, owner, value + DEFAULT_ASSET_ED) - .expect("Unable to mint asset to its new owner."); - >::FungibleLedger::mint(id, &pallet_account, DEFAULT_ASSET_ED) - .expect("Unable to mint existential deposit to pallet account."); + let metadata = >::AssetRegistrarMetadata::default(); + let storage_metadata: >::StorageMetadata = metadata.into(); + >::AssetRegistrar::create_asset( + id, + DEFAULT_ASSET_ED, + storage_metadata, + true, + ) + .expect("Unable to create asset."); + let pallet_account: T::AccountId = Pallet::::account_id(); + >::FungibleLedger::mint(id, owner, value + DEFAULT_ASSET_ED) + .expect("Unable to mint asset to its new owner."); + >::FungibleLedger::mint(id, &pallet_account, DEFAULT_ASSET_ED) + .expect("Unable to mint existential deposit to pallet account."); } benchmarks! { - to_private { - let caller: T::AccountId = whitelisted_caller(); - let origin = T::Origin::from(RawOrigin::Signed(caller.clone())); - init_asset::(&caller, 8u32, 1_000_000u128); - let mint_post = TransferPost::decode(&mut &*MINT).unwrap(); - let asset = Asset::new(mint_post.asset_id.unwrap(), mint_post.sources[0]); - }: to_private ( - RawOrigin::Signed(caller.clone()), - mint_post - ) verify { - // FIXME: add balance checking - assert_last_event::(Event::ToPrivate { asset, source: caller }); - } + to_private { + let caller: T::AccountId = whitelisted_caller(); + let origin = T::Origin::from(RawOrigin::Signed(caller.clone())); + init_asset::(&caller, 8u32, 1_000_000u128); + let mint_post = TransferPost::decode(&mut &*MINT).unwrap(); + let asset = Asset::new(mint_post.asset_id.unwrap(), mint_post.sources[0]); + }: to_private ( + RawOrigin::Signed(caller.clone()), + mint_post + ) verify { + // FIXME: add balance checking + assert_last_event::(Event::ToPrivate { asset, source: caller }); + } - to_public { - let caller: T::AccountId = whitelisted_caller(); - let origin = T::Origin::from(RawOrigin::Signed(caller.clone())); - init_asset::(&caller, 8u32, 1_000_000u128); - for coin in RECLAIM_INPUT { - Pallet::::to_private( - origin.clone(), - TransferPost::decode(&mut &**coin).unwrap() - ).unwrap(); - } - let reclaim_post = TransferPost::decode(&mut &*RECLAIM).unwrap(); - }: to_public ( - RawOrigin::Signed(caller.clone()), - reclaim_post - ) verify { - // FIXME: add balance checking - assert_last_event::(Event::ToPublic { asset: Asset::new(8, 10_000), sink: caller }); - } + to_public { + let caller: T::AccountId = whitelisted_caller(); + let origin = T::Origin::from(RawOrigin::Signed(caller.clone())); + init_asset::(&caller, 8u32, 1_000_000u128); + for coin in RECLAIM_INPUT { + Pallet::::to_private( + origin.clone(), + TransferPost::decode(&mut &**coin).unwrap() + ).unwrap(); + } + let reclaim_post = TransferPost::decode(&mut &*RECLAIM).unwrap(); + }: to_public ( + RawOrigin::Signed(caller.clone()), + reclaim_post + ) verify { + // FIXME: add balance checking + assert_last_event::(Event::ToPublic { asset: Asset::new(8, 10_000), sink: caller }); + } - private_transfer { - let caller: T::AccountId = whitelisted_caller(); - let origin = T::Origin::from(RawOrigin::Signed(caller.clone())); - init_asset::(&caller, 8u32, 1_000_000u128); - for coin in PRIVATE_TRANSFER_INPUT { - Pallet::::to_private( - origin.clone(), - TransferPost::decode(&mut &**coin).unwrap(), - ).unwrap(); - } - let private_transfer_post = TransferPost::decode(&mut &*PRIVATE_TRANSFER).unwrap(); - }: private_transfer ( - RawOrigin::Signed(caller.clone()), - private_transfer_post - ) verify { - assert_last_event::(Event::PrivateTransfer { origin: caller }); - } + private_transfer { + let caller: T::AccountId = whitelisted_caller(); + let origin = T::Origin::from(RawOrigin::Signed(caller.clone())); + init_asset::(&caller, 8u32, 1_000_000u128); + for coin in PRIVATE_TRANSFER_INPUT { + Pallet::::to_private( + origin.clone(), + TransferPost::decode(&mut &**coin).unwrap(), + ).unwrap(); + } + let private_transfer_post = TransferPost::decode(&mut &*PRIVATE_TRANSFER).unwrap(); + }: private_transfer ( + RawOrigin::Signed(caller.clone()), + private_transfer_post + ) verify { + assert_last_event::(Event::PrivateTransfer { origin: caller }); + } - public_transfer { - let caller: T::AccountId = whitelisted_caller(); - let origin = T::Origin::from(RawOrigin::Signed(caller.clone())); - init_asset::(&caller, 8u32, 1_000_000u128); - let asset = Asset::new(8, 100); - let sink = Pallet::::account_id(); - }: public_transfer ( - RawOrigin::Signed(caller.clone()), - asset, - sink.clone() - ) verify { - // FIXME: add balance checking - assert_last_event::(Event::Transfer { asset, source: caller.clone(), sink, }); - } + public_transfer { + let caller: T::AccountId = whitelisted_caller(); + let origin = T::Origin::from(RawOrigin::Signed(caller.clone())); + init_asset::(&caller, 8u32, 1_000_000u128); + let asset = Asset::new(8, 100); + let sink = Pallet::::account_id(); + }: public_transfer ( + RawOrigin::Signed(caller.clone()), + asset, + sink.clone() + ) verify { + // FIXME: add balance checking + assert_last_event::(Event::Transfer { asset, source: caller.clone(), sink, }); + } } impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::Test); diff --git a/pallets/manta-pay/src/benchmark/precomputed_coins.rs b/pallets/manta-pay/src/benchmark/precomputed_coins.rs index a8c63cd16..e307b1ccc 100644 --- a/pallets/manta-pay/src/benchmark/precomputed_coins.rs +++ b/pallets/manta-pay/src/benchmark/precomputed_coins.rs @@ -1,183 +1,183 @@ -// Copyright 2019-2022 Manta Network. -// This file is part of pallet-manta-pay. +// Copyright 2020-2022 Manta Network. +// This file is part of Manta. // -// pallet-manta-pay is free software: you can redistribute it and/or modify +// Manta 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. // -// pallet-manta-pay is distributed in the hope that it will be useful, +// Manta 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 pallet-manta-pay. If not, see . +// along with Manta. If not, see . //! Precomputed Coins //! //! THIS FILE IS AUTOMATICALLY GENERATED by `src/bin/precompute_coins.rs`. DO NOT EDIT. pub(crate) const MINT: &[u8] = &[ - 1, 8, 0, 0, 0, 4, 160, 134, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 185, 130, 170, 226, - 74, 3, 155, 160, 10, 150, 100, 122, 158, 234, 185, 254, 254, 22, 148, 171, 108, 233, 38, 4, - 117, 199, 26, 13, 29, 95, 16, 115, 99, 137, 11, 192, 60, 50, 107, 90, 4, 216, 26, 108, 148, 78, - 74, 119, 51, 235, 0, 121, 30, 226, 237, 150, 188, 28, 40, 241, 6, 138, 206, 0, 168, 178, 43, - 249, 209, 80, 199, 27, 16, 48, 93, 211, 121, 143, 211, 130, 134, 243, 241, 35, 93, 244, 129, - 203, 47, 239, 17, 167, 25, 126, 228, 39, 150, 132, 241, 224, 120, 149, 172, 211, 104, 132, 134, - 161, 105, 203, 47, 104, 166, 114, 145, 113, 154, 45, 189, 49, 244, 177, 157, 58, 14, 227, 8, - 158, 75, 151, 10, 162, 0, 78, 14, 164, 138, 22, 55, 47, 29, 164, 51, 66, 235, 0, 104, 1, 129, - 5, 166, 140, 253, 76, 210, 102, 48, 148, 250, 150, 187, 210, 19, 63, 211, 24, 209, 35, 84, 96, - 222, 85, 21, 11, 211, 87, 118, 215, 226, 65, 17, 241, 237, 15, 255, 229, 67, 89, 247, 186, 219, - 96, 65, 180, 192, 239, 239, 189, 128, 51, 12, 53, 67, 55, 53, 114, 145, 13, 92, 105, 240, 111, - 48, 97, 7, 141, 216, 12, 107, 176, 119, 139, 158, 132, 240, 200, 100, 166, 8, 111, 37, 5, 237, - 114, 142, 220, 136, 156, 16, 62, 89, 146, 225, 28, 187, 82, 209, 155, 123, 250, 216, 97, 226, - 15, 252, 197, 166, 94, 178, 119, 210, 233, 102, 149, 59, 189, 96, 116, 64, 55, 163, 126, 230, - 172, 115, 180, 145, 70, 66, 161, 177, 75, 224, 135, 8, 63, 192, 121, 117, 47, 123, 90, 38, 34, - 141, 118, 204, 232, 174, 6, 76, 245, 246, 111, 190, 186, 134, 167, 143, 13, 23, 86, 119, 224, - 82, 74, 107, 83, 45, 141, 232, 32, 248, 44, 22, + 1, 8, 0, 0, 0, 4, 160, 134, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 185, 130, 170, 226, + 74, 3, 155, 160, 10, 150, 100, 122, 158, 234, 185, 254, 254, 22, 148, 171, 108, 233, 38, 4, + 117, 199, 26, 13, 29, 95, 16, 115, 99, 137, 11, 192, 60, 50, 107, 90, 4, 216, 26, 108, 148, 78, + 74, 119, 51, 235, 0, 121, 30, 226, 237, 150, 188, 28, 40, 241, 6, 138, 206, 0, 168, 178, 43, + 249, 209, 80, 199, 27, 16, 48, 93, 211, 121, 143, 211, 130, 134, 243, 241, 35, 93, 244, 129, + 203, 47, 239, 17, 167, 25, 126, 228, 39, 150, 132, 241, 224, 120, 149, 172, 211, 104, 132, 134, + 161, 105, 203, 47, 104, 166, 114, 145, 113, 154, 45, 189, 49, 244, 177, 157, 58, 14, 227, 8, + 158, 75, 151, 10, 162, 0, 78, 14, 164, 138, 22, 55, 47, 29, 164, 51, 66, 235, 0, 104, 1, 129, + 5, 166, 140, 253, 76, 210, 102, 48, 148, 250, 150, 187, 210, 19, 63, 211, 24, 209, 35, 84, 96, + 222, 85, 21, 11, 211, 87, 118, 215, 226, 65, 17, 241, 237, 15, 255, 229, 67, 89, 247, 186, 219, + 96, 65, 180, 192, 239, 239, 189, 128, 51, 12, 53, 67, 55, 53, 114, 145, 13, 92, 105, 240, 111, + 48, 97, 7, 141, 216, 12, 107, 176, 119, 139, 158, 132, 240, 200, 100, 166, 8, 111, 37, 5, 237, + 114, 142, 220, 136, 156, 16, 62, 89, 146, 225, 28, 187, 82, 209, 155, 123, 250, 216, 97, 226, + 15, 252, 197, 166, 94, 178, 119, 210, 233, 102, 149, 59, 189, 96, 116, 64, 55, 163, 126, 230, + 172, 115, 180, 145, 70, 66, 161, 177, 75, 224, 135, 8, 63, 192, 121, 117, 47, 123, 90, 38, 34, + 141, 118, 204, 232, 174, 6, 76, 245, 246, 111, 190, 186, 134, 167, 143, 13, 23, 86, 119, 224, + 82, 74, 107, 83, 45, 141, 232, 32, 248, 44, 22, ]; pub(crate) const PRIVATE_TRANSFER_INPUT: &[&[u8]] = &[ - &[ - 1, 8, 0, 0, 0, 4, 16, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 159, 183, 12, 98, - 199, 240, 56, 6, 200, 34, 41, 208, 78, 149, 130, 227, 140, 123, 124, 122, 188, 250, 81, 65, - 224, 129, 130, 168, 181, 177, 136, 109, 158, 177, 96, 191, 29, 242, 152, 67, 3, 223, 72, - 144, 7, 164, 232, 217, 215, 221, 139, 19, 96, 181, 123, 76, 186, 51, 78, 160, 42, 15, 21, - 136, 169, 76, 221, 100, 252, 37, 252, 227, 88, 193, 172, 43, 43, 178, 40, 215, 127, 224, - 57, 131, 191, 215, 85, 128, 186, 225, 32, 48, 60, 68, 66, 8, 92, 224, 228, 39, 149, 70, - 179, 100, 41, 142, 25, 69, 84, 239, 130, 248, 189, 146, 55, 193, 171, 243, 199, 90, 155, - 245, 79, 252, 178, 55, 98, 141, 33, 96, 102, 124, 0, 246, 238, 181, 127, 117, 231, 138, 69, - 72, 145, 216, 121, 112, 195, 34, 110, 162, 49, 175, 149, 161, 138, 117, 23, 44, 17, 149, - 48, 236, 31, 74, 100, 24, 57, 66, 142, 174, 19, 227, 107, 115, 160, 205, 252, 188, 117, - 176, 4, 187, 184, 55, 235, 204, 214, 161, 147, 178, 217, 127, 147, 160, 161, 199, 32, 49, - 84, 164, 204, 23, 46, 15, 51, 107, 12, 142, 47, 85, 231, 61, 164, 171, 229, 8, 48, 52, 65, - 82, 129, 55, 102, 159, 23, 112, 193, 197, 24, 137, 8, 21, 56, 157, 151, 145, 240, 159, 62, - 179, 177, 160, 204, 245, 239, 13, 217, 249, 44, 20, 236, 85, 225, 122, 159, 177, 140, 84, - 14, 85, 176, 76, 144, 114, 211, 7, 96, 243, 146, 19, 102, 85, 22, 0, 22, 104, 9, 190, 60, - 210, 155, 247, 14, 6, 183, 61, 106, 59, 241, 33, 136, 232, 253, 135, 116, 246, 210, 171, - 25, 89, 165, 252, 192, 24, 133, 133, 166, 22, 216, 44, 149, 170, 8, 152, 112, 194, 119, - 197, 215, 168, 0, 214, 186, 195, 149, - ], - &[ - 1, 8, 0, 0, 0, 4, 32, 78, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 228, 93, 36, 120, - 190, 129, 158, 45, 131, 179, 188, 51, 129, 45, 172, 168, 73, 134, 167, 213, 65, 251, 45, - 114, 107, 197, 210, 72, 184, 86, 8, 7, 155, 124, 155, 44, 6, 238, 213, 99, 70, 42, 72, 11, - 244, 59, 220, 192, 125, 5, 73, 186, 69, 68, 103, 89, 81, 20, 116, 214, 212, 205, 173, 141, - 202, 9, 125, 131, 47, 222, 172, 218, 56, 165, 226, 29, 233, 79, 222, 253, 243, 125, 162, - 192, 27, 214, 9, 202, 164, 251, 223, 16, 57, 175, 180, 15, 11, 157, 66, 130, 186, 132, 142, - 111, 149, 40, 82, 10, 19, 41, 247, 105, 4, 224, 85, 89, 175, 235, 13, 187, 62, 74, 245, - 239, 136, 100, 132, 73, 224, 131, 93, 159, 0, 241, 22, 119, 69, 39, 101, 223, 1, 180, 214, - 134, 3, 125, 82, 221, 14, 94, 86, 227, 145, 152, 253, 195, 89, 60, 30, 107, 156, 176, 201, - 50, 136, 152, 84, 156, 188, 159, 233, 152, 95, 168, 7, 138, 46, 24, 229, 239, 140, 70, 92, - 179, 0, 227, 41, 114, 42, 209, 176, 238, 30, 206, 214, 172, 30, 99, 65, 98, 170, 34, 168, - 119, 204, 194, 127, 198, 133, 190, 237, 18, 124, 231, 172, 70, 63, 167, 189, 231, 90, 166, - 228, 61, 160, 222, 160, 111, 8, 168, 237, 209, 230, 199, 216, 82, 21, 235, 205, 109, 29, 9, - 45, 209, 158, 62, 208, 30, 46, 242, 151, 22, 155, 230, 18, 139, 145, 210, 41, 46, 209, 37, - 0, 159, 77, 147, 4, 76, 58, 31, 74, 39, 175, 64, 140, 51, 140, 90, 97, 247, 67, 32, 115, - 135, 5, 209, 33, 175, 207, 81, 25, 86, 133, 6, 125, 118, 206, 129, 244, 196, 244, 155, 38, - 138, 222, 16, 201, 229, 120, 134, 66, 18, 104, 230, 21, 188, 144, 205, 140, 30, 127, 14, - 202, 61, 3, - ], + &[ + 1, 8, 0, 0, 0, 4, 16, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 159, 183, 12, 98, + 199, 240, 56, 6, 200, 34, 41, 208, 78, 149, 130, 227, 140, 123, 124, 122, 188, 250, 81, 65, + 224, 129, 130, 168, 181, 177, 136, 109, 158, 177, 96, 191, 29, 242, 152, 67, 3, 223, 72, + 144, 7, 164, 232, 217, 215, 221, 139, 19, 96, 181, 123, 76, 186, 51, 78, 160, 42, 15, 21, + 136, 169, 76, 221, 100, 252, 37, 252, 227, 88, 193, 172, 43, 43, 178, 40, 215, 127, 224, + 57, 131, 191, 215, 85, 128, 186, 225, 32, 48, 60, 68, 66, 8, 92, 224, 228, 39, 149, 70, + 179, 100, 41, 142, 25, 69, 84, 239, 130, 248, 189, 146, 55, 193, 171, 243, 199, 90, 155, + 245, 79, 252, 178, 55, 98, 141, 33, 96, 102, 124, 0, 246, 238, 181, 127, 117, 231, 138, 69, + 72, 145, 216, 121, 112, 195, 34, 110, 162, 49, 175, 149, 161, 138, 117, 23, 44, 17, 149, + 48, 236, 31, 74, 100, 24, 57, 66, 142, 174, 19, 227, 107, 115, 160, 205, 252, 188, 117, + 176, 4, 187, 184, 55, 235, 204, 214, 161, 147, 178, 217, 127, 147, 160, 161, 199, 32, 49, + 84, 164, 204, 23, 46, 15, 51, 107, 12, 142, 47, 85, 231, 61, 164, 171, 229, 8, 48, 52, 65, + 82, 129, 55, 102, 159, 23, 112, 193, 197, 24, 137, 8, 21, 56, 157, 151, 145, 240, 159, 62, + 179, 177, 160, 204, 245, 239, 13, 217, 249, 44, 20, 236, 85, 225, 122, 159, 177, 140, 84, + 14, 85, 176, 76, 144, 114, 211, 7, 96, 243, 146, 19, 102, 85, 22, 0, 22, 104, 9, 190, 60, + 210, 155, 247, 14, 6, 183, 61, 106, 59, 241, 33, 136, 232, 253, 135, 116, 246, 210, 171, + 25, 89, 165, 252, 192, 24, 133, 133, 166, 22, 216, 44, 149, 170, 8, 152, 112, 194, 119, + 197, 215, 168, 0, 214, 186, 195, 149, + ], + &[ + 1, 8, 0, 0, 0, 4, 32, 78, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 228, 93, 36, 120, + 190, 129, 158, 45, 131, 179, 188, 51, 129, 45, 172, 168, 73, 134, 167, 213, 65, 251, 45, + 114, 107, 197, 210, 72, 184, 86, 8, 7, 155, 124, 155, 44, 6, 238, 213, 99, 70, 42, 72, 11, + 244, 59, 220, 192, 125, 5, 73, 186, 69, 68, 103, 89, 81, 20, 116, 214, 212, 205, 173, 141, + 202, 9, 125, 131, 47, 222, 172, 218, 56, 165, 226, 29, 233, 79, 222, 253, 243, 125, 162, + 192, 27, 214, 9, 202, 164, 251, 223, 16, 57, 175, 180, 15, 11, 157, 66, 130, 186, 132, 142, + 111, 149, 40, 82, 10, 19, 41, 247, 105, 4, 224, 85, 89, 175, 235, 13, 187, 62, 74, 245, + 239, 136, 100, 132, 73, 224, 131, 93, 159, 0, 241, 22, 119, 69, 39, 101, 223, 1, 180, 214, + 134, 3, 125, 82, 221, 14, 94, 86, 227, 145, 152, 253, 195, 89, 60, 30, 107, 156, 176, 201, + 50, 136, 152, 84, 156, 188, 159, 233, 152, 95, 168, 7, 138, 46, 24, 229, 239, 140, 70, 92, + 179, 0, 227, 41, 114, 42, 209, 176, 238, 30, 206, 214, 172, 30, 99, 65, 98, 170, 34, 168, + 119, 204, 194, 127, 198, 133, 190, 237, 18, 124, 231, 172, 70, 63, 167, 189, 231, 90, 166, + 228, 61, 160, 222, 160, 111, 8, 168, 237, 209, 230, 199, 216, 82, 21, 235, 205, 109, 29, 9, + 45, 209, 158, 62, 208, 30, 46, 242, 151, 22, 155, 230, 18, 139, 145, 210, 41, 46, 209, 37, + 0, 159, 77, 147, 4, 76, 58, 31, 74, 39, 175, 64, 140, 51, 140, 90, 97, 247, 67, 32, 115, + 135, 5, 209, 33, 175, 207, 81, 25, 86, 133, 6, 125, 118, 206, 129, 244, 196, 244, 155, 38, + 138, 222, 16, 201, 229, 120, 134, 66, 18, 104, 230, 21, 188, 144, 205, 140, 30, 127, 14, + 202, 61, 3, + ], ]; pub(crate) const PRIVATE_TRANSFER: &[u8] = &[ - 0, 0, 8, 149, 141, 24, 70, 56, 223, 63, 113, 225, 101, 247, 12, 53, 81, 2, 70, 98, 80, 224, - 108, 149, 149, 192, 180, 26, 52, 0, 10, 55, 12, 1, 36, 94, 47, 214, 59, 108, 233, 220, 81, 254, - 195, 216, 28, 72, 243, 66, 14, 140, 195, 139, 107, 119, 249, 218, 203, 158, 91, 2, 96, 92, 193, - 195, 72, 9, 127, 98, 5, 100, 128, 65, 63, 29, 54, 2, 32, 102, 47, 67, 168, 14, 130, 164, 77, - 36, 8, 119, 47, 224, 151, 89, 114, 19, 99, 90, 2, 225, 5, 75, 74, 168, 89, 181, 108, 217, 220, - 97, 98, 241, 221, 57, 51, 101, 94, 137, 141, 106, 255, 224, 191, 63, 189, 144, 21, 55, 105, 79, - 111, 8, 136, 46, 143, 144, 67, 219, 201, 243, 48, 94, 10, 180, 33, 50, 215, 146, 189, 68, 7, - 211, 147, 22, 89, 22, 61, 45, 77, 188, 71, 127, 7, 2, 181, 243, 203, 34, 220, 73, 195, 125, - 164, 123, 216, 200, 132, 74, 158, 47, 218, 127, 224, 255, 224, 170, 86, 2, 243, 138, 211, 23, - 88, 236, 24, 8, 240, 193, 214, 10, 138, 88, 57, 21, 228, 25, 123, 169, 233, 4, 141, 161, 169, - 47, 129, 136, 181, 67, 198, 246, 75, 232, 97, 14, 241, 109, 42, 166, 199, 188, 68, 86, 77, 30, - 190, 150, 255, 191, 222, 231, 11, 227, 155, 125, 152, 50, 31, 189, 185, 161, 109, 190, 202, - 157, 108, 173, 158, 13, 172, 234, 151, 208, 175, 28, 204, 188, 48, 62, 89, 191, 118, 60, 98, - 55, 189, 111, 157, 229, 205, 107, 233, 158, 17, 135, 65, 250, 153, 85, 22, 163, 69, 115, 244, - 213, 242, 77, 138, 19, 12, 150, 131, 252, 33, 116, 63, 178, 184, 34, 167, 189, 132, 24, 172, - 67, 227, 185, 103, 136, 253, 234, 194, 48, 24, 126, 34, 14, 175, 177, 248, 245, 120, 245, 224, - 233, 72, 36, 172, 106, 172, 53, 212, 224, 189, 172, 211, 14, 53, 251, 46, 186, 156, 246, 77, - 131, 251, 107, 225, 133, 12, 195, 135, 82, 218, 84, 145, 44, 254, 77, 105, 52, 18, 147, 2, 194, - 183, 74, 230, 225, 51, 159, 107, 218, 151, 118, 120, 128, 64, 234, 104, 238, 90, 201, 233, 247, - 102, 72, 0, 140, 231, 52, 121, 137, 246, 181, 102, 228, 64, 132, 5, 238, 193, 152, 191, 37, 0, - 25, 123, 138, 168, 74, 179, 110, 17, 241, 200, 143, 232, 187, 216, 176, 56, 11, 90, 113, 43, - 231, 244, 97, 120, 32, 252, 26, 88, 35, 3, 108, 46, 3, 43, 96, 183, 50, 196, 134, 107, 152, 11, - 103, 78, 217, 84, 236, 97, 144, 78, 91, 16, 54, 29, 136, 0, 120, 130, 45, 248, 169, 242, 32, 7, - 230, 95, 179, 208, 176, 251, 190, 85, 206, 102, 107, 39, 239, 19, 170, 75, 169, 228, 93, 96, - 203, 177, 72, 58, 82, 64, 14, 139, 197, 26, 186, 105, 239, 25, 214, 209, 28, 2, 61, 88, 184, - 33, 34, 119, 100, 89, 164, 186, 105, 35, 24, 186, 184, 2, 182, 137, 13, 67, 59, 43, 43, 12, - 244, 117, 205, 202, 180, 108, 162, 35, 111, 133, 138, 17, 106, 65, 105, 237, 167, 142, 79, 240, - 137, 65, 210, 214, 12, 30, 30, 62, 255, 101, 189, 56, 147, 236, 21, 104, 123, 157, 27, 142, 40, - 23, 35, 190, 27, 82, 196, 6, + 0, 0, 8, 149, 141, 24, 70, 56, 223, 63, 113, 225, 101, 247, 12, 53, 81, 2, 70, 98, 80, 224, + 108, 149, 149, 192, 180, 26, 52, 0, 10, 55, 12, 1, 36, 94, 47, 214, 59, 108, 233, 220, 81, 254, + 195, 216, 28, 72, 243, 66, 14, 140, 195, 139, 107, 119, 249, 218, 203, 158, 91, 2, 96, 92, 193, + 195, 72, 9, 127, 98, 5, 100, 128, 65, 63, 29, 54, 2, 32, 102, 47, 67, 168, 14, 130, 164, 77, + 36, 8, 119, 47, 224, 151, 89, 114, 19, 99, 90, 2, 225, 5, 75, 74, 168, 89, 181, 108, 217, 220, + 97, 98, 241, 221, 57, 51, 101, 94, 137, 141, 106, 255, 224, 191, 63, 189, 144, 21, 55, 105, 79, + 111, 8, 136, 46, 143, 144, 67, 219, 201, 243, 48, 94, 10, 180, 33, 50, 215, 146, 189, 68, 7, + 211, 147, 22, 89, 22, 61, 45, 77, 188, 71, 127, 7, 2, 181, 243, 203, 34, 220, 73, 195, 125, + 164, 123, 216, 200, 132, 74, 158, 47, 218, 127, 224, 255, 224, 170, 86, 2, 243, 138, 211, 23, + 88, 236, 24, 8, 240, 193, 214, 10, 138, 88, 57, 21, 228, 25, 123, 169, 233, 4, 141, 161, 169, + 47, 129, 136, 181, 67, 198, 246, 75, 232, 97, 14, 241, 109, 42, 166, 199, 188, 68, 86, 77, 30, + 190, 150, 255, 191, 222, 231, 11, 227, 155, 125, 152, 50, 31, 189, 185, 161, 109, 190, 202, + 157, 108, 173, 158, 13, 172, 234, 151, 208, 175, 28, 204, 188, 48, 62, 89, 191, 118, 60, 98, + 55, 189, 111, 157, 229, 205, 107, 233, 158, 17, 135, 65, 250, 153, 85, 22, 163, 69, 115, 244, + 213, 242, 77, 138, 19, 12, 150, 131, 252, 33, 116, 63, 178, 184, 34, 167, 189, 132, 24, 172, + 67, 227, 185, 103, 136, 253, 234, 194, 48, 24, 126, 34, 14, 175, 177, 248, 245, 120, 245, 224, + 233, 72, 36, 172, 106, 172, 53, 212, 224, 189, 172, 211, 14, 53, 251, 46, 186, 156, 246, 77, + 131, 251, 107, 225, 133, 12, 195, 135, 82, 218, 84, 145, 44, 254, 77, 105, 52, 18, 147, 2, 194, + 183, 74, 230, 225, 51, 159, 107, 218, 151, 118, 120, 128, 64, 234, 104, 238, 90, 201, 233, 247, + 102, 72, 0, 140, 231, 52, 121, 137, 246, 181, 102, 228, 64, 132, 5, 238, 193, 152, 191, 37, 0, + 25, 123, 138, 168, 74, 179, 110, 17, 241, 200, 143, 232, 187, 216, 176, 56, 11, 90, 113, 43, + 231, 244, 97, 120, 32, 252, 26, 88, 35, 3, 108, 46, 3, 43, 96, 183, 50, 196, 134, 107, 152, 11, + 103, 78, 217, 84, 236, 97, 144, 78, 91, 16, 54, 29, 136, 0, 120, 130, 45, 248, 169, 242, 32, 7, + 230, 95, 179, 208, 176, 251, 190, 85, 206, 102, 107, 39, 239, 19, 170, 75, 169, 228, 93, 96, + 203, 177, 72, 58, 82, 64, 14, 139, 197, 26, 186, 105, 239, 25, 214, 209, 28, 2, 61, 88, 184, + 33, 34, 119, 100, 89, 164, 186, 105, 35, 24, 186, 184, 2, 182, 137, 13, 67, 59, 43, 43, 12, + 244, 117, 205, 202, 180, 108, 162, 35, 111, 133, 138, 17, 106, 65, 105, 237, 167, 142, 79, 240, + 137, 65, 210, 214, 12, 30, 30, 62, 255, 101, 189, 56, 147, 236, 21, 104, 123, 157, 27, 142, 40, + 23, 35, 190, 27, 82, 196, 6, ]; pub(crate) const RECLAIM_INPUT: &[&[u8]] = &[ - &[ - 1, 8, 0, 0, 0, 4, 16, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 128, 176, 193, - 38, 145, 229, 208, 226, 218, 128, 10, 50, 99, 41, 109, 253, 125, 116, 100, 244, 82, 95, - 242, 87, 165, 210, 5, 65, 24, 184, 221, 112, 135, 41, 233, 98, 174, 50, 66, 158, 142, 182, - 55, 179, 215, 39, 252, 65, 239, 247, 32, 118, 211, 65, 158, 172, 197, 230, 87, 105, 247, - 147, 197, 72, 56, 101, 214, 52, 24, 91, 2, 181, 64, 207, 148, 68, 11, 83, 209, 195, 134, - 120, 73, 97, 212, 78, 253, 131, 179, 11, 100, 34, 20, 139, 147, 118, 47, 141, 17, 253, 70, - 161, 164, 175, 248, 223, 190, 227, 188, 54, 146, 38, 137, 252, 205, 236, 67, 179, 216, 117, - 160, 74, 236, 110, 66, 181, 241, 34, 134, 31, 163, 235, 0, 199, 64, 216, 208, 244, 48, 143, - 31, 215, 130, 218, 240, 219, 125, 114, 77, 110, 121, 206, 69, 185, 195, 133, 7, 25, 84, - 231, 66, 128, 11, 96, 254, 159, 79, 13, 11, 96, 210, 147, 111, 221, 249, 127, 90, 176, 153, - 19, 16, 178, 21, 54, 202, 69, 213, 243, 206, 123, 116, 43, 84, 253, 152, 100, 57, 43, 3, - 161, 178, 151, 144, 164, 221, 119, 161, 193, 26, 21, 113, 145, 241, 159, 57, 23, 224, 190, - 186, 192, 31, 60, 170, 11, 248, 79, 211, 24, 21, 236, 196, 99, 183, 179, 121, 140, 14, 76, - 74, 3, 126, 189, 116, 19, 51, 255, 53, 99, 184, 140, 229, 160, 58, 108, 12, 182, 118, 63, - 236, 182, 107, 204, 143, 160, 153, 198, 26, 240, 158, 137, 150, 243, 153, 222, 148, 104, - 150, 136, 207, 155, 47, 66, 141, 195, 229, 239, 174, 79, 93, 88, 181, 19, 167, 97, 169, 39, - 255, 29, 34, 98, 204, 52, 38, 77, 162, 130, 34, 74, 138, 80, 161, 8, 245, 74, 13, 193, 70, - 121, 82, 132, 117, 227, 49, 87, 5, - ], - &[ - 1, 8, 0, 0, 0, 4, 32, 78, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 228, 210, 85, 0, - 68, 231, 28, 46, 214, 210, 81, 196, 230, 180, 70, 194, 45, 3, 133, 200, 141, 201, 198, 111, - 89, 130, 144, 15, 103, 70, 115, 115, 191, 136, 103, 200, 240, 183, 116, 232, 156, 243, 148, - 228, 93, 70, 253, 65, 131, 0, 189, 103, 198, 45, 218, 238, 247, 59, 170, 60, 146, 159, 199, - 181, 3, 47, 178, 191, 251, 70, 141, 115, 235, 63, 121, 41, 28, 219, 154, 92, 242, 72, 27, - 88, 15, 46, 244, 121, 90, 25, 96, 8, 243, 164, 125, 93, 165, 176, 83, 112, 149, 98, 27, - 251, 58, 212, 98, 137, 69, 236, 177, 91, 223, 117, 57, 242, 205, 36, 36, 200, 146, 180, 34, - 208, 123, 178, 17, 254, 188, 185, 237, 161, 0, 160, 10, 124, 37, 73, 65, 167, 250, 162, 69, - 144, 116, 250, 190, 144, 9, 175, 235, 202, 31, 8, 209, 71, 245, 221, 84, 26, 78, 115, 187, - 163, 246, 149, 86, 203, 133, 188, 220, 31, 177, 174, 162, 11, 177, 159, 186, 165, 151, 28, - 22, 185, 14, 246, 198, 128, 226, 46, 97, 229, 117, 89, 122, 69, 111, 117, 121, 150, 144, - 151, 190, 38, 182, 106, 252, 183, 10, 154, 158, 246, 17, 234, 73, 168, 10, 123, 87, 139, - 152, 177, 161, 51, 68, 141, 218, 150, 21, 94, 247, 99, 173, 233, 95, 76, 15, 74, 46, 23, - 23, 4, 228, 97, 213, 232, 79, 102, 9, 233, 4, 43, 113, 44, 197, 129, 139, 59, 169, 35, 93, - 240, 93, 132, 225, 189, 5, 187, 144, 167, 54, 56, 7, 213, 7, 32, 12, 65, 10, 100, 12, 212, - 174, 15, 144, 183, 77, 20, 182, 52, 138, 68, 6, 225, 37, 208, 109, 58, 137, 171, 137, 147, - 44, 45, 92, 163, 41, 88, 40, 50, 228, 37, 176, 74, 161, 91, 88, 115, 198, 51, 188, 20, 83, - 155, 148, - ], + &[ + 1, 8, 0, 0, 0, 4, 16, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 128, 176, 193, + 38, 145, 229, 208, 226, 218, 128, 10, 50, 99, 41, 109, 253, 125, 116, 100, 244, 82, 95, + 242, 87, 165, 210, 5, 65, 24, 184, 221, 112, 135, 41, 233, 98, 174, 50, 66, 158, 142, 182, + 55, 179, 215, 39, 252, 65, 239, 247, 32, 118, 211, 65, 158, 172, 197, 230, 87, 105, 247, + 147, 197, 72, 56, 101, 214, 52, 24, 91, 2, 181, 64, 207, 148, 68, 11, 83, 209, 195, 134, + 120, 73, 97, 212, 78, 253, 131, 179, 11, 100, 34, 20, 139, 147, 118, 47, 141, 17, 253, 70, + 161, 164, 175, 248, 223, 190, 227, 188, 54, 146, 38, 137, 252, 205, 236, 67, 179, 216, 117, + 160, 74, 236, 110, 66, 181, 241, 34, 134, 31, 163, 235, 0, 199, 64, 216, 208, 244, 48, 143, + 31, 215, 130, 218, 240, 219, 125, 114, 77, 110, 121, 206, 69, 185, 195, 133, 7, 25, 84, + 231, 66, 128, 11, 96, 254, 159, 79, 13, 11, 96, 210, 147, 111, 221, 249, 127, 90, 176, 153, + 19, 16, 178, 21, 54, 202, 69, 213, 243, 206, 123, 116, 43, 84, 253, 152, 100, 57, 43, 3, + 161, 178, 151, 144, 164, 221, 119, 161, 193, 26, 21, 113, 145, 241, 159, 57, 23, 224, 190, + 186, 192, 31, 60, 170, 11, 248, 79, 211, 24, 21, 236, 196, 99, 183, 179, 121, 140, 14, 76, + 74, 3, 126, 189, 116, 19, 51, 255, 53, 99, 184, 140, 229, 160, 58, 108, 12, 182, 118, 63, + 236, 182, 107, 204, 143, 160, 153, 198, 26, 240, 158, 137, 150, 243, 153, 222, 148, 104, + 150, 136, 207, 155, 47, 66, 141, 195, 229, 239, 174, 79, 93, 88, 181, 19, 167, 97, 169, 39, + 255, 29, 34, 98, 204, 52, 38, 77, 162, 130, 34, 74, 138, 80, 161, 8, 245, 74, 13, 193, 70, + 121, 82, 132, 117, 227, 49, 87, 5, + ], + &[ + 1, 8, 0, 0, 0, 4, 32, 78, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 228, 210, 85, 0, + 68, 231, 28, 46, 214, 210, 81, 196, 230, 180, 70, 194, 45, 3, 133, 200, 141, 201, 198, 111, + 89, 130, 144, 15, 103, 70, 115, 115, 191, 136, 103, 200, 240, 183, 116, 232, 156, 243, 148, + 228, 93, 70, 253, 65, 131, 0, 189, 103, 198, 45, 218, 238, 247, 59, 170, 60, 146, 159, 199, + 181, 3, 47, 178, 191, 251, 70, 141, 115, 235, 63, 121, 41, 28, 219, 154, 92, 242, 72, 27, + 88, 15, 46, 244, 121, 90, 25, 96, 8, 243, 164, 125, 93, 165, 176, 83, 112, 149, 98, 27, + 251, 58, 212, 98, 137, 69, 236, 177, 91, 223, 117, 57, 242, 205, 36, 36, 200, 146, 180, 34, + 208, 123, 178, 17, 254, 188, 185, 237, 161, 0, 160, 10, 124, 37, 73, 65, 167, 250, 162, 69, + 144, 116, 250, 190, 144, 9, 175, 235, 202, 31, 8, 209, 71, 245, 221, 84, 26, 78, 115, 187, + 163, 246, 149, 86, 203, 133, 188, 220, 31, 177, 174, 162, 11, 177, 159, 186, 165, 151, 28, + 22, 185, 14, 246, 198, 128, 226, 46, 97, 229, 117, 89, 122, 69, 111, 117, 121, 150, 144, + 151, 190, 38, 182, 106, 252, 183, 10, 154, 158, 246, 17, 234, 73, 168, 10, 123, 87, 139, + 152, 177, 161, 51, 68, 141, 218, 150, 21, 94, 247, 99, 173, 233, 95, 76, 15, 74, 46, 23, + 23, 4, 228, 97, 213, 232, 79, 102, 9, 233, 4, 43, 113, 44, 197, 129, 139, 59, 169, 35, 93, + 240, 93, 132, 225, 189, 5, 187, 144, 167, 54, 56, 7, 213, 7, 32, 12, 65, 10, 100, 12, 212, + 174, 15, 144, 183, 77, 20, 182, 52, 138, 68, 6, 225, 37, 208, 109, 58, 137, 171, 137, 147, + 44, 45, 92, 163, 41, 88, 40, 50, 228, 37, 176, 74, 161, 91, 88, 115, 198, 51, 188, 20, 83, + 155, 148, + ], ]; pub(crate) const RECLAIM: &[u8] = &[ - 1, 8, 0, 0, 0, 0, 8, 181, 218, 94, 91, 229, 12, 93, 102, 103, 83, 128, 233, 35, 47, 43, 157, - 125, 73, 218, 195, 135, 59, 41, 236, 140, 102, 173, 161, 125, 251, 14, 2, 65, 169, 122, 135, - 41, 122, 69, 34, 114, 174, 83, 250, 231, 40, 132, 115, 136, 70, 202, 131, 95, 118, 10, 116, 82, - 46, 5, 203, 39, 9, 200, 98, 243, 129, 186, 1, 55, 53, 4, 200, 146, 79, 133, 119, 144, 50, 173, - 247, 74, 154, 80, 177, 159, 19, 166, 132, 205, 153, 205, 237, 110, 117, 254, 54, 176, 50, 183, - 217, 132, 167, 234, 73, 198, 87, 167, 131, 52, 49, 113, 84, 94, 207, 55, 136, 193, 5, 203, 139, - 211, 84, 9, 111, 25, 49, 151, 24, 4, 21, 106, 71, 113, 109, 83, 114, 123, 250, 211, 76, 64, 10, - 217, 184, 133, 24, 92, 47, 31, 239, 179, 71, 45, 138, 192, 134, 148, 230, 63, 74, 11, 53, 182, - 73, 110, 35, 147, 150, 235, 178, 207, 149, 85, 111, 169, 67, 12, 65, 186, 104, 142, 197, 123, - 147, 205, 234, 64, 137, 195, 147, 171, 49, 204, 30, 111, 40, 182, 151, 215, 220, 6, 200, 199, - 253, 245, 158, 221, 77, 194, 164, 165, 215, 204, 179, 218, 24, 116, 197, 134, 57, 254, 174, - 197, 81, 81, 180, 21, 11, 177, 199, 148, 221, 245, 169, 115, 98, 165, 11, 31, 157, 88, 59, 26, - 252, 235, 45, 184, 124, 252, 240, 128, 198, 10, 228, 238, 131, 113, 150, 95, 246, 180, 4, 16, - 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 219, 183, 141, 210, 65, 237, 205, 219, 148, 194, - 99, 219, 92, 13, 143, 190, 214, 137, 94, 119, 131, 77, 187, 255, 106, 239, 240, 156, 182, 215, - 89, 159, 91, 170, 24, 106, 103, 44, 194, 155, 81, 232, 143, 7, 111, 38, 243, 25, 215, 83, 45, - 88, 170, 161, 136, 54, 184, 214, 74, 150, 44, 249, 16, 80, 21, 182, 12, 68, 20, 39, 85, 25, 59, - 108, 17, 133, 84, 68, 245, 41, 244, 228, 98, 203, 39, 1, 161, 97, 127, 175, 16, 160, 98, 187, - 191, 15, 126, 19, 69, 0, 201, 2, 88, 203, 193, 200, 146, 15, 95, 248, 177, 104, 252, 141, 59, - 213, 61, 190, 112, 97, 186, 146, 162, 239, 199, 14, 0, 51, 46, 47, 0, 221, 168, 189, 254, 171, - 19, 95, 124, 201, 201, 228, 63, 17, 162, 55, 101, 251, 71, 65, 119, 162, 61, 68, 240, 205, 41, - 128, 117, 216, 117, 187, 6, 134, 78, 102, 58, 69, 175, 79, 222, 189, 1, 254, 63, 174, 89, 76, - 159, 135, 123, 78, 48, 4, 219, 127, 62, 176, 102, 15, 167, 4, + 1, 8, 0, 0, 0, 0, 8, 181, 218, 94, 91, 229, 12, 93, 102, 103, 83, 128, 233, 35, 47, 43, 157, + 125, 73, 218, 195, 135, 59, 41, 236, 140, 102, 173, 161, 125, 251, 14, 2, 65, 169, 122, 135, + 41, 122, 69, 34, 114, 174, 83, 250, 231, 40, 132, 115, 136, 70, 202, 131, 95, 118, 10, 116, 82, + 46, 5, 203, 39, 9, 200, 98, 243, 129, 186, 1, 55, 53, 4, 200, 146, 79, 133, 119, 144, 50, 173, + 247, 74, 154, 80, 177, 159, 19, 166, 132, 205, 153, 205, 237, 110, 117, 254, 54, 176, 50, 183, + 217, 132, 167, 234, 73, 198, 87, 167, 131, 52, 49, 113, 84, 94, 207, 55, 136, 193, 5, 203, 139, + 211, 84, 9, 111, 25, 49, 151, 24, 4, 21, 106, 71, 113, 109, 83, 114, 123, 250, 211, 76, 64, 10, + 217, 184, 133, 24, 92, 47, 31, 239, 179, 71, 45, 138, 192, 134, 148, 230, 63, 74, 11, 53, 182, + 73, 110, 35, 147, 150, 235, 178, 207, 149, 85, 111, 169, 67, 12, 65, 186, 104, 142, 197, 123, + 147, 205, 234, 64, 137, 195, 147, 171, 49, 204, 30, 111, 40, 182, 151, 215, 220, 6, 200, 199, + 253, 245, 158, 221, 77, 194, 164, 165, 215, 204, 179, 218, 24, 116, 197, 134, 57, 254, 174, + 197, 81, 81, 180, 21, 11, 177, 199, 148, 221, 245, 169, 115, 98, 165, 11, 31, 157, 88, 59, 26, + 252, 235, 45, 184, 124, 252, 240, 128, 198, 10, 228, 238, 131, 113, 150, 95, 246, 180, 4, 16, + 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 219, 183, 141, 210, 65, 237, 205, 219, 148, 194, + 99, 219, 92, 13, 143, 190, 214, 137, 94, 119, 131, 77, 187, 255, 106, 239, 240, 156, 182, 215, + 89, 159, 91, 170, 24, 106, 103, 44, 194, 155, 81, 232, 143, 7, 111, 38, 243, 25, 215, 83, 45, + 88, 170, 161, 136, 54, 184, 214, 74, 150, 44, 249, 16, 80, 21, 182, 12, 68, 20, 39, 85, 25, 59, + 108, 17, 133, 84, 68, 245, 41, 244, 228, 98, 203, 39, 1, 161, 97, 127, 175, 16, 160, 98, 187, + 191, 15, 126, 19, 69, 0, 201, 2, 88, 203, 193, 200, 146, 15, 95, 248, 177, 104, 252, 141, 59, + 213, 61, 190, 112, 97, 186, 146, 162, 239, 199, 14, 0, 51, 46, 47, 0, 221, 168, 189, 254, 171, + 19, 95, 124, 201, 201, 228, 63, 17, 162, 55, 101, 251, 71, 65, 119, 162, 61, 68, 240, 205, 41, + 128, 117, 216, 117, 187, 6, 134, 78, 102, 58, 69, 175, 79, 222, 189, 1, 254, 63, 174, 89, 76, + 159, 135, 123, 78, 48, 4, 219, 127, 62, 176, 102, 15, 167, 4, ]; diff --git a/pallets/manta-pay/src/bin/precompute_coins.rs b/pallets/manta-pay/src/bin/precompute_coins.rs index 548fcebcf..95eb93526 100644 --- a/pallets/manta-pay/src/bin/precompute_coins.rs +++ b/pallets/manta-pay/src/bin/precompute_coins.rs @@ -1,398 +1,398 @@ -// Copyright 2019-2022 Manta Network. -// This file is part of pallet-manta-pay. +// Copyright 2020-2022 Manta Network. +// This file is part of Manta. // -// pallet-manta-pay is free software: you can redistribute it and/or modify +// Manta 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. // -// pallet-manta-pay is distributed in the hope that it will be useful, +// Manta 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 pallet-manta-pay. If not, see . +// along with Manta. If not, see . //! Precomputed Transactions use anyhow::Result; use indoc::indoc; use manta_accounting::{ - asset::{Asset, AssetId}, - transfer::{self, SpendingKey}, + asset::{Asset, AssetId}, + transfer::{self, SpendingKey}, }; use manta_crypto::{ - accumulator::Accumulator, - constraint::ProofSystem as _, - merkle_tree::{forest::TreeArrayMerkleForest, full::Full}, - rand::{CryptoRng, Rand, RngCore, Sample}, + accumulator::Accumulator, + constraint::ProofSystem as _, + merkle_tree::{forest::TreeArrayMerkleForest, full::Full}, + rand::{CryptoRng, Rand, RngCore, Sample}, }; use manta_pay::config::{ - self, FullParameters, MerkleTreeConfiguration, Mint, MultiProvingContext, - MultiVerifyingContext, NoteEncryptionScheme, Parameters, PrivateTransfer, ProofSystem, - ProvingContext, Reclaim, UtxoAccumulatorModel, UtxoCommitmentScheme, VerifyingContext, - VoidNumberCommitmentScheme, + self, FullParameters, MerkleTreeConfiguration, Mint, MultiProvingContext, + MultiVerifyingContext, NoteEncryptionScheme, Parameters, PrivateTransfer, ProofSystem, + ProvingContext, Reclaim, UtxoAccumulatorModel, UtxoCommitmentScheme, VerifyingContext, + VoidNumberCommitmentScheme, }; use manta_util::codec::{Decode, IoReader}; use pallet_manta_pay::types::TransferPost; use rand::thread_rng; use scale_codec::Encode; use std::{ - env, - fs::{self, File, OpenOptions}, - io::Write, - path::{Path, PathBuf}, + env, + fs::{self, File, OpenOptions}, + io::Write, + path::{Path, PathBuf}, }; /// UTXO Accumulator for Building Circuits type UtxoAccumulator = - TreeArrayMerkleForest, 256>; + TreeArrayMerkleForest, 256>; /// Loads parameters from the SDK, using `directory` as a temporary directory to store files. #[inline] fn load_parameters( - directory: &Path, + directory: &Path, ) -> Result<( - MultiProvingContext, - MultiVerifyingContext, - Parameters, - UtxoAccumulatorModel, + MultiProvingContext, + MultiVerifyingContext, + Parameters, + UtxoAccumulatorModel, )> { - let mint_path = directory.join("mint.dat"); - manta_sdk::pay::testnet::proving::Mint::download(&mint_path)?; - let private_transfer_path = directory.join("private-transfer.dat"); - manta_sdk::pay::testnet::proving::PrivateTransfer::download(&private_transfer_path)?; - let reclaim_path = directory.join("reclaim.dat"); - manta_sdk::pay::testnet::proving::Reclaim::download(&reclaim_path)?; - let proving_context = MultiProvingContext { - mint: ProvingContext::decode(IoReader(File::open(mint_path)?)) - .expect("Unable to decode MINT proving context."), - private_transfer: ProvingContext::decode(IoReader(File::open(private_transfer_path)?)) - .expect("Unable to decode PRIVATE_TRANSFER proving context."), - reclaim: ProvingContext::decode(IoReader(File::open(reclaim_path)?)) - .expect("Unable to decode RECLAIM proving context."), - }; - let verifying_context = MultiVerifyingContext { - mint: VerifyingContext::decode( - manta_sdk::pay::testnet::verifying::Mint::get().expect("Checksum did not match."), - ) - .expect("Unable to decode MINT verifying context."), - private_transfer: VerifyingContext::decode( - manta_sdk::pay::testnet::verifying::PrivateTransfer::get() - .expect("Checksum did not match."), - ) - .expect("Unable to decode PRIVATE_TRANSFER verifying context."), - reclaim: VerifyingContext::decode( - manta_sdk::pay::testnet::verifying::Reclaim::get().expect("Checksum did not match."), - ) - .expect("Unable to decode RECLAIM verifying context."), - }; - let parameters = Parameters { - note_encryption_scheme: NoteEncryptionScheme::decode( - manta_sdk::pay::testnet::parameters::NoteEncryptionScheme::get() - .expect("Checksum did not match."), - ) - .expect("Unable to decode NOTE_ENCRYPTION_SCHEME parameters."), - utxo_commitment: UtxoCommitmentScheme::decode( - manta_sdk::pay::testnet::parameters::UtxoCommitmentScheme::get() - .expect("Checksum did not match."), - ) - .expect("Unable to decode UTXO_COMMITMENT_SCHEME parameters."), - void_number_commitment: VoidNumberCommitmentScheme::decode( - manta_sdk::pay::testnet::parameters::VoidNumberCommitmentScheme::get() - .expect("Checksum did not match."), - ) - .expect("Unable to decode VOID_NUMBER_COMMITMENT_SCHEME parameters."), - }; - Ok(( - proving_context, - verifying_context, - parameters, - UtxoAccumulatorModel::decode( - manta_sdk::pay::testnet::parameters::UtxoAccumulatorModel::get() - .expect("Checksum did not match."), - ) - .expect("Unable to decode UTXO_ACCUMULATOR_MODEL."), - )) + let mint_path = directory.join("mint.dat"); + manta_sdk::pay::testnet::proving::Mint::download(&mint_path)?; + let private_transfer_path = directory.join("private-transfer.dat"); + manta_sdk::pay::testnet::proving::PrivateTransfer::download(&private_transfer_path)?; + let reclaim_path = directory.join("reclaim.dat"); + manta_sdk::pay::testnet::proving::Reclaim::download(&reclaim_path)?; + let proving_context = MultiProvingContext { + mint: ProvingContext::decode(IoReader(File::open(mint_path)?)) + .expect("Unable to decode MINT proving context."), + private_transfer: ProvingContext::decode(IoReader(File::open(private_transfer_path)?)) + .expect("Unable to decode PRIVATE_TRANSFER proving context."), + reclaim: ProvingContext::decode(IoReader(File::open(reclaim_path)?)) + .expect("Unable to decode RECLAIM proving context."), + }; + let verifying_context = MultiVerifyingContext { + mint: VerifyingContext::decode( + manta_sdk::pay::testnet::verifying::Mint::get().expect("Checksum did not match."), + ) + .expect("Unable to decode MINT verifying context."), + private_transfer: VerifyingContext::decode( + manta_sdk::pay::testnet::verifying::PrivateTransfer::get() + .expect("Checksum did not match."), + ) + .expect("Unable to decode PRIVATE_TRANSFER verifying context."), + reclaim: VerifyingContext::decode( + manta_sdk::pay::testnet::verifying::Reclaim::get().expect("Checksum did not match."), + ) + .expect("Unable to decode RECLAIM verifying context."), + }; + let parameters = Parameters { + note_encryption_scheme: NoteEncryptionScheme::decode( + manta_sdk::pay::testnet::parameters::NoteEncryptionScheme::get() + .expect("Checksum did not match."), + ) + .expect("Unable to decode NOTE_ENCRYPTION_SCHEME parameters."), + utxo_commitment: UtxoCommitmentScheme::decode( + manta_sdk::pay::testnet::parameters::UtxoCommitmentScheme::get() + .expect("Checksum did not match."), + ) + .expect("Unable to decode UTXO_COMMITMENT_SCHEME parameters."), + void_number_commitment: VoidNumberCommitmentScheme::decode( + manta_sdk::pay::testnet::parameters::VoidNumberCommitmentScheme::get() + .expect("Checksum did not match."), + ) + .expect("Unable to decode VOID_NUMBER_COMMITMENT_SCHEME parameters."), + }; + Ok(( + proving_context, + verifying_context, + parameters, + UtxoAccumulatorModel::decode( + manta_sdk::pay::testnet::parameters::UtxoAccumulatorModel::get() + .expect("Checksum did not match."), + ) + .expect("Unable to decode UTXO_ACCUMULATOR_MODEL."), + )) } /// Asserts that `post` represents a valid `Transfer` verifying against `verifying_context`. #[inline] fn assert_valid_proof(verifying_context: &VerifyingContext, post: &config::TransferPost) { - assert!( - ProofSystem::verify( - verifying_context, - &post.generate_proof_input(), - &post.validity_proof, - ) - .expect("Unable to verify proof."), - "Invalid proof: {:?}.", - post - ); + assert!( + ProofSystem::verify( + verifying_context, + &post.generate_proof_input(), + &post.validity_proof, + ) + .expect("Unable to verify proof."), + "Invalid proof: {:?}.", + post + ); } /// Samples a [`Mint`] transaction. #[inline] fn sample_mint( - proving_context: &ProvingContext, - verifying_context: &VerifyingContext, - parameters: &Parameters, - utxo_accumulator_model: &UtxoAccumulatorModel, - asset: Asset, - rng: &mut R, + proving_context: &ProvingContext, + verifying_context: &VerifyingContext, + parameters: &Parameters, + utxo_accumulator_model: &UtxoAccumulatorModel, + asset: Asset, + rng: &mut R, ) -> TransferPost where - R: CryptoRng + RngCore + ?Sized, + R: CryptoRng + RngCore + ?Sized, { - let mint = Mint::from_spending_key(parameters, &SpendingKey::gen(rng), asset, rng) - .into_post( - FullParameters::new(parameters, utxo_accumulator_model), - proving_context, - rng, - ) - .expect("Unable to build MINT proof."); - assert_valid_proof(verifying_context, &mint); - mint.into() + let mint = Mint::from_spending_key(parameters, &SpendingKey::gen(rng), asset, rng) + .into_post( + FullParameters::new(parameters, utxo_accumulator_model), + proving_context, + rng, + ) + .expect("Unable to build MINT proof."); + assert_valid_proof(verifying_context, &mint); + mint.into() } /// Samples a [`PrivateTransfer`] transaction under two [`Mint`]s. #[inline] fn sample_private_transfer( - proving_context: &MultiProvingContext, - verifying_context: &MultiVerifyingContext, - parameters: &Parameters, - utxo_accumulator_model: &UtxoAccumulatorModel, - asset_0: Asset, - asset_1: Asset, - rng: &mut R, + proving_context: &MultiProvingContext, + verifying_context: &MultiVerifyingContext, + parameters: &Parameters, + utxo_accumulator_model: &UtxoAccumulatorModel, + asset_0: Asset, + asset_1: Asset, + rng: &mut R, ) -> ([TransferPost; 2], TransferPost) where - R: CryptoRng + RngCore + ?Sized, + R: CryptoRng + RngCore + ?Sized, { - let mut utxo_accumulator = UtxoAccumulator::new(utxo_accumulator_model.clone()); - let spending_key_0 = SpendingKey::new(rng.gen(), rng.gen()); - let (mint_0, pre_sender_0) = transfer::test::sample_mint( - &proving_context.mint, - FullParameters::new(parameters, utxo_accumulator.model()), - &spending_key_0, - asset_0, - rng, - ) - .expect("Unable to build MINT proof."); - assert_valid_proof(&verifying_context.mint, &mint_0); - let sender_0 = pre_sender_0 - .insert_and_upgrade(&mut utxo_accumulator) - .expect("Just inserted so this should not fail."); - let spending_key_1 = SpendingKey::new(rng.gen(), rng.gen()); - let (mint_1, pre_sender_1) = transfer::test::sample_mint( - &proving_context.mint, - FullParameters::new(parameters, utxo_accumulator.model()), - &spending_key_1, - asset_1, - rng, - ) - .expect("Unable to build MINT proof."); - assert_valid_proof(&verifying_context.mint, &mint_1); - let sender_1 = pre_sender_1 - .insert_and_upgrade(&mut utxo_accumulator) - .expect("Just inserted so this should not fail."); - let private_transfer = PrivateTransfer::build( - [sender_0, sender_1], - [ - spending_key_0.receiver(parameters, rng.gen(), asset_1), - spending_key_1.receiver(parameters, rng.gen(), asset_0), - ], - ) - .into_post( - FullParameters::new(parameters, utxo_accumulator.model()), - &proving_context.private_transfer, - rng, - ) - .expect("Unable to build PRIVATE_TRANSFER proof."); - assert_valid_proof(&verifying_context.private_transfer, &private_transfer); - ([mint_0.into(), mint_1.into()], private_transfer.into()) + let mut utxo_accumulator = UtxoAccumulator::new(utxo_accumulator_model.clone()); + let spending_key_0 = SpendingKey::new(rng.gen(), rng.gen()); + let (mint_0, pre_sender_0) = transfer::test::sample_mint( + &proving_context.mint, + FullParameters::new(parameters, utxo_accumulator.model()), + &spending_key_0, + asset_0, + rng, + ) + .expect("Unable to build MINT proof."); + assert_valid_proof(&verifying_context.mint, &mint_0); + let sender_0 = pre_sender_0 + .insert_and_upgrade(&mut utxo_accumulator) + .expect("Just inserted so this should not fail."); + let spending_key_1 = SpendingKey::new(rng.gen(), rng.gen()); + let (mint_1, pre_sender_1) = transfer::test::sample_mint( + &proving_context.mint, + FullParameters::new(parameters, utxo_accumulator.model()), + &spending_key_1, + asset_1, + rng, + ) + .expect("Unable to build MINT proof."); + assert_valid_proof(&verifying_context.mint, &mint_1); + let sender_1 = pre_sender_1 + .insert_and_upgrade(&mut utxo_accumulator) + .expect("Just inserted so this should not fail."); + let private_transfer = PrivateTransfer::build( + [sender_0, sender_1], + [ + spending_key_0.receiver(parameters, rng.gen(), asset_1), + spending_key_1.receiver(parameters, rng.gen(), asset_0), + ], + ) + .into_post( + FullParameters::new(parameters, utxo_accumulator.model()), + &proving_context.private_transfer, + rng, + ) + .expect("Unable to build PRIVATE_TRANSFER proof."); + assert_valid_proof(&verifying_context.private_transfer, &private_transfer); + ([mint_0.into(), mint_1.into()], private_transfer.into()) } /// Samples a [`Reclaim`] transaction under two [`Mint`]s. #[inline] fn sample_reclaim( - proving_context: &MultiProvingContext, - verifying_context: &MultiVerifyingContext, - parameters: &Parameters, - utxo_accumulator_model: &UtxoAccumulatorModel, - asset_0: Asset, - asset_1: Asset, - rng: &mut R, + proving_context: &MultiProvingContext, + verifying_context: &MultiVerifyingContext, + parameters: &Parameters, + utxo_accumulator_model: &UtxoAccumulatorModel, + asset_0: Asset, + asset_1: Asset, + rng: &mut R, ) -> ([TransferPost; 2], TransferPost) where - R: CryptoRng + RngCore + ?Sized, + R: CryptoRng + RngCore + ?Sized, { - let mut utxo_accumulator = UtxoAccumulator::new(utxo_accumulator_model.clone()); - let spending_key_0 = SpendingKey::new(rng.gen(), rng.gen()); - let (mint_0, pre_sender_0) = transfer::test::sample_mint( - &proving_context.mint, - FullParameters::new(parameters, utxo_accumulator.model()), - &spending_key_0, - asset_0, - rng, - ) - .expect("Unable to build MINT proof."); - assert_valid_proof(&verifying_context.mint, &mint_0); - let sender_0 = pre_sender_0 - .insert_and_upgrade(&mut utxo_accumulator) - .expect("Just inserted so this should not fail."); - let spending_key_1 = SpendingKey::new(rng.gen(), rng.gen()); - let (mint_1, pre_sender_1) = transfer::test::sample_mint( - &proving_context.mint, - FullParameters::new(parameters, utxo_accumulator.model()), - &spending_key_1, - asset_1, - rng, - ) - .expect("Unable to build MINT proof."); - assert_valid_proof(&verifying_context.mint, &mint_1); - let sender_1 = pre_sender_1 - .insert_and_upgrade(&mut utxo_accumulator) - .expect("Just inserted so this should not fail."); - let reclaim = Reclaim::build( - [sender_0, sender_1], - [spending_key_0.receiver(parameters, rng.gen(), asset_1)], - asset_0, - ) - .into_post( - FullParameters::new(parameters, utxo_accumulator.model()), - &proving_context.reclaim, - rng, - ) - .expect("Unable to build RECLAIM proof."); - assert_valid_proof(&verifying_context.reclaim, &reclaim); - ([mint_0.into(), mint_1.into()], reclaim.into()) + let mut utxo_accumulator = UtxoAccumulator::new(utxo_accumulator_model.clone()); + let spending_key_0 = SpendingKey::new(rng.gen(), rng.gen()); + let (mint_0, pre_sender_0) = transfer::test::sample_mint( + &proving_context.mint, + FullParameters::new(parameters, utxo_accumulator.model()), + &spending_key_0, + asset_0, + rng, + ) + .expect("Unable to build MINT proof."); + assert_valid_proof(&verifying_context.mint, &mint_0); + let sender_0 = pre_sender_0 + .insert_and_upgrade(&mut utxo_accumulator) + .expect("Just inserted so this should not fail."); + let spending_key_1 = SpendingKey::new(rng.gen(), rng.gen()); + let (mint_1, pre_sender_1) = transfer::test::sample_mint( + &proving_context.mint, + FullParameters::new(parameters, utxo_accumulator.model()), + &spending_key_1, + asset_1, + rng, + ) + .expect("Unable to build MINT proof."); + assert_valid_proof(&verifying_context.mint, &mint_1); + let sender_1 = pre_sender_1 + .insert_and_upgrade(&mut utxo_accumulator) + .expect("Just inserted so this should not fail."); + let reclaim = Reclaim::build( + [sender_0, sender_1], + [spending_key_0.receiver(parameters, rng.gen(), asset_1)], + asset_0, + ) + .into_post( + FullParameters::new(parameters, utxo_accumulator.model()), + &proving_context.reclaim, + rng, + ) + .expect("Unable to build RECLAIM proof."); + assert_valid_proof(&verifying_context.reclaim, &reclaim); + ([mint_0.into(), mint_1.into()], reclaim.into()) } /// Writes a new `const` definition to `$writer`. macro_rules! write_const_array { - ($writer:ident, $name:ident, $value:expr) => { - writeln!( - $writer, - "pub(crate) const {}: &[u8] = &{:?};\n", - stringify!($name), - $value.encode().as_slice() - ) - }; + ($writer:ident, $name:ident, $value:expr) => { + writeln!( + $writer, + "pub(crate) const {}: &[u8] = &{:?};\n", + stringify!($name), + $value.encode().as_slice() + ) + }; } /// Writes a new `const` definition to `$writer`. macro_rules! write_const_nested_array { - ($writer:ident, $name:ident, $value:expr) => { - writeln!( - $writer, - "pub(crate) const {}: &[&[u8]] = &[{}];\n", - stringify!($name), - $value - .iter() - .flat_map(|v| { - format!("&{:?},", v.encode().as_slice()) - .chars() - .collect::>() - }) - .collect::(), - ) - }; + ($writer:ident, $name:ident, $value:expr) => { + writeln!( + $writer, + "pub(crate) const {}: &[&[u8]] = &[{}];\n", + stringify!($name), + $value + .iter() + .flat_map(|v| { + format!("&{:?},", v.encode().as_slice()) + .chars() + .collect::>() + }) + .collect::(), + ) + }; } /// Builds sample transactions for testing. #[inline] fn main() -> Result<()> { - let target_file = env::args() - .nth(1) - .map(PathBuf::from) - .unwrap_or(env::current_dir()?.join("precomputed_coins.rs")); - assert!( - !target_file.exists(), - "Specify a file to place the generated files: {:?}.", - target_file, - ); - fs::create_dir_all( - &target_file - .parent() - .expect("This file should have a parent."), - )?; + let target_file = env::args() + .nth(1) + .map(PathBuf::from) + .unwrap_or(env::current_dir()?.join("precomputed_coins.rs")); + assert!( + !target_file.exists(), + "Specify a file to place the generated files: {:?}.", + target_file, + ); + fs::create_dir_all( + &target_file + .parent() + .expect("This file should have a parent."), + )?; - let directory = tempfile::tempdir().expect("Unable to generate temporary test directory."); - println!("[INFO] Temporary Directory: {:?}", directory); + let directory = tempfile::tempdir().expect("Unable to generate temporary test directory."); + println!("[INFO] Temporary Directory: {:?}", directory); - let mut rng = thread_rng(); - let (proving_context, verifying_context, parameters, utxo_accumulator_model) = - load_parameters(directory.path())?; - let asset_id: u32 = 8; + let mut rng = thread_rng(); + let (proving_context, verifying_context, parameters, utxo_accumulator_model) = + load_parameters(directory.path())?; + let asset_id: u32 = 8; - let mint = sample_mint( - &proving_context.mint, - &verifying_context.mint, - ¶meters, - &utxo_accumulator_model, - AssetId(asset_id).value(100_000), - &mut rng, - ); - let (private_transfer_input, private_transfer) = sample_private_transfer( - &proving_context, - &verifying_context, - ¶meters, - &utxo_accumulator_model, - AssetId(asset_id).value(10_000), - AssetId(asset_id).value(20_000), - &mut rng, - ); - let (reclaim_input, reclaim) = sample_reclaim( - &proving_context, - &verifying_context, - ¶meters, - &utxo_accumulator_model, - AssetId(asset_id).value(10_000), - AssetId(asset_id).value(20_000), - &mut rng, - ); + let mint = sample_mint( + &proving_context.mint, + &verifying_context.mint, + ¶meters, + &utxo_accumulator_model, + AssetId(asset_id).value(100_000), + &mut rng, + ); + let (private_transfer_input, private_transfer) = sample_private_transfer( + &proving_context, + &verifying_context, + ¶meters, + &utxo_accumulator_model, + AssetId(asset_id).value(10_000), + AssetId(asset_id).value(20_000), + &mut rng, + ); + let (reclaim_input, reclaim) = sample_reclaim( + &proving_context, + &verifying_context, + ¶meters, + &utxo_accumulator_model, + AssetId(asset_id).value(10_000), + AssetId(asset_id).value(20_000), + &mut rng, + ); - let mut target_file = OpenOptions::new() - .create_new(true) - .write(true) - .open(target_file)?; + let mut target_file = OpenOptions::new() + .create_new(true) + .write(true) + .open(target_file)?; - writeln!( - target_file, - indoc! {r" - // Copyright 2019-2022 Manta Network. - // This file is part of pallet-manta-pay. - // - // pallet-manta-pay 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. - // - // pallet-manta-pay 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 pallet-manta-pay. If not, see . + writeln!( + target_file, + indoc! {r" + // Copyright 2019-2022 Manta Network. + // This file is part of Manta. + // + // Manta 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. + // + // Manta 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 Manta. If not, see . - //! Precomputed Coins - //! - //! THIS FILE IS AUTOMATICALLY GENERATED by `src/bin/precompute_coins.rs`. DO NOT EDIT. - "} - )?; + //! Precomputed Coins + //! + //! THIS FILE IS AUTOMATICALLY GENERATED by `src/bin/precompute_coins.rs`. DO NOT EDIT. + "} + )?; - write_const_array!(target_file, MINT, mint)?; - write_const_nested_array!(target_file, PRIVATE_TRANSFER_INPUT, private_transfer_input)?; - write_const_array!(target_file, PRIVATE_TRANSFER, private_transfer)?; - write_const_nested_array!(target_file, RECLAIM_INPUT, reclaim_input)?; - write_const_array!(target_file, RECLAIM, reclaim)?; + write_const_array!(target_file, MINT, mint)?; + write_const_nested_array!(target_file, PRIVATE_TRANSFER_INPUT, private_transfer_input)?; + write_const_array!(target_file, PRIVATE_TRANSFER, private_transfer)?; + write_const_nested_array!(target_file, RECLAIM_INPUT, reclaim_input)?; + write_const_array!(target_file, RECLAIM, reclaim)?; - directory - .close() - .expect("Unable to delete temporary test directory."); + directory + .close() + .expect("Unable to delete temporary test directory."); - Ok(()) + Ok(()) } diff --git a/pallets/manta-pay/src/lib.rs b/pallets/manta-pay/src/lib.rs index 7b66d0499..6c24d7953 100644 --- a/pallets/manta-pay/src/lib.rs +++ b/pallets/manta-pay/src/lib.rs @@ -1,18 +1,18 @@ -// Copyright 2019-2022 Manta Network. -// This file is part of pallet-manta-pay. +// Copyright 2020-2022 Manta Network. +// This file is part of Manta. // -// pallet-manta-pay is free software: you can redistribute it and/or modify +// Manta 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. // -// pallet-manta-pay is distributed in the hope that it will be useful, +// Manta 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 pallet-manta-pay. If not, see . +// along with Manta. If not, see . //! # MantaPay Module //! @@ -59,22 +59,22 @@ use alloc::{vec, vec::Vec}; use core::marker::PhantomData; use frame_support::{transactional, PalletId}; use manta_accounting::{ - asset, - transfer::{ - canonical::TransferShape, InvalidSinkAccount, InvalidSourceAccount, Proof, ReceiverLedger, - ReceiverPostError, ReceiverPostingKey, SenderLedger, SenderPostError, SenderPostingKey, - SinkPostingKey, SourcePostingKey, TransferLedger, TransferLedgerSuperPostingKey, - TransferPostError, TransferPostingKey, - }, + asset, + transfer::{ + canonical::TransferShape, InvalidSinkAccount, InvalidSourceAccount, Proof, ReceiverLedger, + ReceiverPostError, ReceiverPostingKey, SenderLedger, SenderPostError, SenderPostingKey, + SinkPostingKey, SourcePostingKey, TransferLedger, TransferLedgerSuperPostingKey, + TransferPostError, TransferPostingKey, + }, }; use manta_crypto::{ - constraint::ProofSystem, - merkle_tree::{self, forest::Configuration as _}, + constraint::ProofSystem, + merkle_tree::{self, forest::Configuration as _}, }; use manta_pay::config; use manta_primitives::{ - assets::{AssetConfig, FungibleLedger as _, FungibleLedgerError}, - types::{AssetId, Balance}, + assets::{AssetConfig, FungibleLedger as _, FungibleLedgerError}, + types::{AssetId, Balance}, }; use manta_util::codec::Decode as _; use scale_codec::{Decode, Encode, MaxEncodedLen}; @@ -109,452 +109,452 @@ pub mod runtime; /// MantaPay Pallet #[frame_support::pallet] pub mod pallet { - use super::*; - use frame_support::pallet_prelude::*; - use frame_system::pallet_prelude::*; - use sp_runtime::traits::AccountIdConversion; - - /// Pallet - #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] - pub struct Pallet(_); - - /// The module configuration trait. - #[pallet::config] - pub trait Config: frame_system::Config { - /// The overarching event type. - type Event: From> + IsType<::Event>; - - /// Asset Configuration - type AssetConfig: AssetConfig; - - /// Weight information for extrinsics in this pallet. - type WeightInfo: WeightInfo; - - /// Pallet ID - type PalletId: Get; - } - - /// Fungible Ledger Implementation for [`Config`] - pub(crate) type FungibleLedger = - <::AssetConfig as AssetConfig>::FungibleLedger; - - #[pallet::hooks] - impl Hooks> for Pallet {} - - /// UTXOs and Encrypted Notes Grouped by Shard - #[pallet::storage] - pub(super) type Shards = - StorageDoubleMap<_, Identity, u8, Identity, u64, (Utxo, EncryptedNote), ValueQuery>; - - /// Shard Merkle Tree Paths - #[pallet::storage] - pub(super) type ShardTrees = - StorageMap<_, Identity, u8, UtxoMerkleTreePath, ValueQuery>; - - /// Outputs of Utxo Accumulator - #[pallet::storage] - pub(super) type UtxoAccumulatorOutputs = - StorageMap<_, Identity, UtxoAccumulatorOutput, (), ValueQuery>; - - /// UTXO Set - #[pallet::storage] - pub(super) type UtxoSet = StorageMap<_, Identity, Utxo, (), ValueQuery>; - - /// Void Number Set - #[pallet::storage] - pub(super) type VoidNumberSet = StorageMap<_, Identity, VoidNumber, (), ValueQuery>; - - /// Void Number Ordered by Insertion - #[pallet::storage] - pub(super) type VoidNumberSetInsertionOrder = - StorageMap<_, Identity, u64, VoidNumber, ValueQuery>; - - /// The size of Void Number Set - #[pallet::storage] - pub(super) type VoidNumberSetSize = StorageValue<_, u64, ValueQuery>; - - #[pallet::call] - impl Pallet { - /// Transforms some public assets into private ones using `post`, withdrawing the public - /// assets from the `origin` account. - #[pallet::weight(T::WeightInfo::to_private())] - #[transactional] - pub fn to_private(origin: OriginFor, post: TransferPost) -> DispatchResultWithPostInfo { - let origin = ensure_signed(origin)?; - Self::post_transaction(None, vec![origin], vec![], post) - } - - /// Transforms some private assets into public ones using `post`, depositing the public - /// assets in the `origin` account. - #[pallet::weight(T::WeightInfo::to_public())] - #[transactional] - pub fn to_public(origin: OriginFor, post: TransferPost) -> DispatchResultWithPostInfo { - let origin = ensure_signed(origin)?; - Self::post_transaction(None, vec![], vec![origin], post) - } - - /// Transfers private assets encoded in `post`. - /// - /// # Note - /// - /// In this transaction, `origin` is just signing the `post` and is not necessarily related - /// to any of the participants in the transaction itself. - #[pallet::weight(T::WeightInfo::private_transfer())] - #[transactional] - pub fn private_transfer( - origin: OriginFor, - post: TransferPost, - ) -> DispatchResultWithPostInfo { - let origin = ensure_signed(origin)?; - Self::post_transaction(Some(origin), vec![], vec![], post) - } - - /// Transfers public `asset` from `origin` to the `sink` account. - #[pallet::weight(T::WeightInfo::public_transfer())] - #[transactional] - pub fn public_transfer( - origin: OriginFor, - asset: Asset, - sink: T::AccountId, - ) -> DispatchResultWithPostInfo { - let origin = ensure_signed(origin)?; - FungibleLedger::::transfer(asset.id, &origin, &sink, asset.value) - .map_err(Error::::from)?; - Self::deposit_event(Event::Transfer { - asset, - source: origin, - sink, - }); - Ok(().into()) - } - } - - /// Event - #[pallet::event] - #[pallet::generate_deposit(fn deposit_event)] - pub enum Event { - /// Public Transfer Event - Transfer { - /// Asset Transferred - asset: Asset, - - /// Source Account - source: T::AccountId, - - /// Sink Account - sink: T::AccountId, - }, - - /// To Private Event - ToPrivate { - /// Asset Converted - asset: Asset, - - /// Source Account - source: T::AccountId, - }, - - /// Private Transfer Event - PrivateTransfer { - /// Origin Account - origin: T::AccountId, - }, - - /// To Public Event - ToPublic { - /// Asset Converted - asset: Asset, - - /// Sink Account - sink: T::AccountId, - }, - } - - /// Error - #[pallet::error] - pub enum Error { - /// Uninitialized Supply - /// - /// Supply of the given Asset Id has not yet been initialized. - UninitializedSupply, - - /// Zero Transfer - /// - /// Public transfers cannot include amounts equal to zero. - ZeroTransfer, - - /// Balance Low - /// - /// Attempted to withdraw from balance which was smaller than the withdrawal amount. - BalanceLow, - - /// Invalid Serialized Form - /// - /// The transfer could not be interpreted because of an issue during deserialization. - InvalidSerializedForm, - - /// Invalid Shape - /// - /// The transfer had an invalid shape. - InvalidShape, - - /// Asset Spent - /// - /// An asset present in this transfer has already been spent. - AssetSpent, - - /// Invalid UTXO Accumulator Output - /// - /// The sender was constructed on an invalid version of the ledger state. - InvalidUtxoAccumulatorOutput, - - /// Asset Registered - /// - /// An asset present in this transfer has already been registered to the ledger. - AssetRegistered, - - /// Duplicate Spend - /// - /// There were multiple spend entries for the same underlying asset in this transfer. - DuplicateSpend, - - /// Duplicate Register - /// - /// There were multiple register entries for the same underlying asset in this transfer. - DuplicateRegister, - - /// Invalid Proof - /// - /// The submitted proof did not pass validation, or errored during validation. - InvalidProof, - - /// Invalid Source Account - /// - /// At least one of the source accounts is invalid. - InvalidSourceAccount, - - /// Invalid Sink Account - /// - /// At least one of the sink accounts in invalid. - InvalidSinkAccount, - - /// [`InvalidAssetId`](FungibleLedgerError::InvalidAssetId) from [`FungibleLedgerError`] - PublicUpdateInvalidAssetId, - - /// [`BelowMinimum`](FungibleLedgerError::BelowMinimum) from [`FungibleLedgerError`] - PublicUpdateBelowMinimum, - - /// [`CannotCreate`](FungibleLedgerError::CannotCreate) from [`FungibleLedgerError`] - PublicUpdateCannotCreate, - - /// [`UnknownAsset`](FungibleLedgerError::UnknownAsset) from [`FungibleLedgerError`] - PublicUpdateUnknownAsset, - - /// [`Overflow`](FungibleLedgerError::Overflow) from [`FungibleLedgerError`] - PublicUpdateOverflow, - - /// [`Underflow`](FungibleLedgerError::Underflow) from [`FungibleLedgerError`] - PublicUpdateUnderflow, - - /// [`Frozen`](FungibleLedgerError::Frozen) from [`FungibleLedgerError`] - PublicUpdateFrozen, - - /// [`ReducedToZero`](FungibleLedgerError::ReducedToZero) from [`FungibleLedgerError`] - PublicUpdateReducedToZero, - - /// [`NoFunds`](FungibleLedgerError::NoFunds) from [`FungibleLedgerError`] - PublicUpdateNoFunds, - - /// [`WouldDie`](FungibleLedgerError::WouldDie) from [`FungibleLedgerError`] - PublicUpdateWouldDie, - - /// [`InvalidTransfer`](FungibleLedgerError::InvalidTransfer) from [`FungibleLedgerError`] - PublicUpdateInvalidTransfer, - - /// Internal Ledger Error - /// - /// This is caused by some internal error in the ledger and should never occur. - InternalLedgerError, - } - - impl From> for Error - where - T: Config, - { - #[inline] - fn from(_: InvalidSourceAccount) -> Self { - Self::InvalidSourceAccount - } - } - - impl From> for Error - where - T: Config, - { - #[inline] - fn from(_: InvalidSinkAccount) -> Self { - Self::InvalidSinkAccount - } - } - - impl From for Error { - #[inline] - fn from(err: SenderPostError) -> Self { - match err { - SenderPostError::AssetSpent => Self::AssetSpent, - SenderPostError::InvalidUtxoAccumulatorOutput => Self::InvalidUtxoAccumulatorOutput, - } - } - } - - impl From for Error { - #[inline] - fn from(err: ReceiverPostError) -> Self { - match err { - ReceiverPostError::AssetRegistered => Self::AssetRegistered, - } - } - } - - impl From for Error - where - T: Config, - { - #[inline] - fn from(err: FungibleLedgerError) -> Self { - match err { - FungibleLedgerError::InvalidAssetId => Self::PublicUpdateInvalidAssetId, - FungibleLedgerError::BelowMinimum => Self::PublicUpdateBelowMinimum, - FungibleLedgerError::CannotCreate => Self::PublicUpdateCannotCreate, - FungibleLedgerError::UnknownAsset => Self::PublicUpdateUnknownAsset, - FungibleLedgerError::Overflow => Self::PublicUpdateOverflow, - FungibleLedgerError::Underflow => Self::PublicUpdateUnderflow, - FungibleLedgerError::Frozen => Self::PublicUpdateFrozen, - FungibleLedgerError::ReducedToZero(_) => Self::PublicUpdateReducedToZero, - FungibleLedgerError::NoFunds => Self::PublicUpdateNoFunds, - FungibleLedgerError::WouldDie => Self::PublicUpdateWouldDie, - FungibleLedgerError::InvalidTransfer(_e) => Self::PublicUpdateInvalidTransfer, - _ => Self::InternalLedgerError, - } - } - } - - impl From> for Error - where - T: Config, - { - #[inline] - fn from(err: TransferPostError) -> Self { - match err { - TransferPostError::InvalidShape => Self::InvalidShape, - TransferPostError::InvalidSourceAccount(err) => err.into(), - TransferPostError::InvalidSinkAccount(err) => err.into(), - TransferPostError::Sender(err) => err.into(), - TransferPostError::Receiver(err) => err.into(), - TransferPostError::DuplicateSpend => Self::DuplicateSpend, - TransferPostError::DuplicateRegister => Self::DuplicateRegister, - TransferPostError::InvalidProof => Self::InvalidProof, - TransferPostError::UpdateError(err) => err.into(), - } - } - } - - impl Pallet - where - T: Config, - { - /// Maximum Number of Updates per Shard - const PULL_MAX_PER_SHARD_UPDATE_SIZE: usize = 128; - - /// Maximum Size of Sender Data Update - const PULL_MAX_SENDER_UPDATE_SIZE: usize = 1024; - - /// Pulls receiver data from the ledger starting at the `receiver_index`. - #[inline] - fn pull_receivers(receiver_index: [usize; 256]) -> (bool, ReceiverChunk) { - let mut more_receivers = false; - let mut receivers = Vec::new(); - for (i, index) in receiver_index.into_iter().enumerate() { - more_receivers |= Self::pull_receivers_for_shard(i as u8, index, &mut receivers); - } - (more_receivers, receivers) - } - - /// Pulls receiver data from the shard at `shard_index` starting at the `receiver_index`, - /// pushing the results back to `receivers`. - #[inline] - fn pull_receivers_for_shard( - shard_index: u8, - receiver_index: usize, - receivers: &mut ReceiverChunk, - ) -> bool { - let mut iter = if receiver_index == 0 { - Shards::::iter_prefix(shard_index) - } else { - let raw_key = Shards::::hashed_key_for(shard_index, receiver_index as u64 - 1); - Shards::::iter_prefix_from(shard_index, raw_key) - }; - for _ in 0..Self::PULL_MAX_PER_SHARD_UPDATE_SIZE { - match iter.next() { - Some((_, next)) => receivers.push(next), - _ => return false, - } - } - iter.next().is_some() - } - - /// Pulls sender data from the ledger starting at the `sender_index`. - #[inline] - fn pull_senders(sender_index: usize) -> (bool, SenderChunk) { - let mut senders = Vec::new(); - let mut iter = VoidNumberSetInsertionOrder::::iter().skip(sender_index); - for _ in 0..Self::PULL_MAX_SENDER_UPDATE_SIZE { - match iter.next() { - Some((_, next)) => senders.push(next), - _ => return (false, senders), - } - } - (iter.next().is_some(), senders) - } - - /// Returns the diff of ledger state since the given `checkpoint`. - #[inline] - pub fn pull_ledger_diff(checkpoint: Checkpoint) -> PullResponse { - let (more_receivers, receivers) = Self::pull_receivers(*checkpoint.receiver_index); - let (more_senders, senders) = Self::pull_senders(checkpoint.sender_index); - PullResponse { - should_continue: more_receivers || more_senders, - receivers, - senders, - } - } - - /// Returns the account ID of this pallet. - #[inline] - pub fn account_id() -> T::AccountId { - T::PalletId::get().into_account() - } - - /// Posts the transaction encoded in `post` to the ledger, using `sources` and `sinks` as - /// the public deposit and public withdraw accounts respectively. - #[inline] - fn post_transaction( - origin: Option, - sources: Vec, - sinks: Vec, - post: TransferPost, - ) -> DispatchResultWithPostInfo { - Self::deposit_event( - config::TransferPost::try_from(post) - .map_err(|_| Error::::InvalidSerializedForm)? - .post(sources, sinks, &(), &mut Ledger(PhantomData)) - .map_err(Error::::from)? - .convert(origin), - ); - Ok(().into()) - } - } + use super::*; + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; + use sp_runtime::traits::AccountIdConversion; + + /// Pallet + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(_); + + /// The module configuration trait. + #[pallet::config] + pub trait Config: frame_system::Config { + /// The overarching event type. + type Event: From> + IsType<::Event>; + + /// Asset Configuration + type AssetConfig: AssetConfig; + + /// Weight information for extrinsics in this pallet. + type WeightInfo: WeightInfo; + + /// Pallet ID + type PalletId: Get; + } + + /// Fungible Ledger Implementation for [`Config`] + pub(crate) type FungibleLedger = + <::AssetConfig as AssetConfig>::FungibleLedger; + + #[pallet::hooks] + impl Hooks> for Pallet {} + + /// UTXOs and Encrypted Notes Grouped by Shard + #[pallet::storage] + pub(super) type Shards = + StorageDoubleMap<_, Identity, u8, Identity, u64, (Utxo, EncryptedNote), ValueQuery>; + + /// Shard Merkle Tree Paths + #[pallet::storage] + pub(super) type ShardTrees = + StorageMap<_, Identity, u8, UtxoMerkleTreePath, ValueQuery>; + + /// Outputs of Utxo Accumulator + #[pallet::storage] + pub(super) type UtxoAccumulatorOutputs = + StorageMap<_, Identity, UtxoAccumulatorOutput, (), ValueQuery>; + + /// UTXO Set + #[pallet::storage] + pub(super) type UtxoSet = StorageMap<_, Identity, Utxo, (), ValueQuery>; + + /// Void Number Set + #[pallet::storage] + pub(super) type VoidNumberSet = StorageMap<_, Identity, VoidNumber, (), ValueQuery>; + + /// Void Number Ordered by Insertion + #[pallet::storage] + pub(super) type VoidNumberSetInsertionOrder = + StorageMap<_, Identity, u64, VoidNumber, ValueQuery>; + + /// The size of Void Number Set + #[pallet::storage] + pub(super) type VoidNumberSetSize = StorageValue<_, u64, ValueQuery>; + + #[pallet::call] + impl Pallet { + /// Transforms some public assets into private ones using `post`, withdrawing the public + /// assets from the `origin` account. + #[pallet::weight(T::WeightInfo::to_private())] + #[transactional] + pub fn to_private(origin: OriginFor, post: TransferPost) -> DispatchResultWithPostInfo { + let origin = ensure_signed(origin)?; + Self::post_transaction(None, vec![origin], vec![], post) + } + + /// Transforms some private assets into public ones using `post`, depositing the public + /// assets in the `origin` account. + #[pallet::weight(T::WeightInfo::to_public())] + #[transactional] + pub fn to_public(origin: OriginFor, post: TransferPost) -> DispatchResultWithPostInfo { + let origin = ensure_signed(origin)?; + Self::post_transaction(None, vec![], vec![origin], post) + } + + /// Transfers private assets encoded in `post`. + /// + /// # Note + /// + /// In this transaction, `origin` is just signing the `post` and is not necessarily related + /// to any of the participants in the transaction itself. + #[pallet::weight(T::WeightInfo::private_transfer())] + #[transactional] + pub fn private_transfer( + origin: OriginFor, + post: TransferPost, + ) -> DispatchResultWithPostInfo { + let origin = ensure_signed(origin)?; + Self::post_transaction(Some(origin), vec![], vec![], post) + } + + /// Transfers public `asset` from `origin` to the `sink` account. + #[pallet::weight(T::WeightInfo::public_transfer())] + #[transactional] + pub fn public_transfer( + origin: OriginFor, + asset: Asset, + sink: T::AccountId, + ) -> DispatchResultWithPostInfo { + let origin = ensure_signed(origin)?; + FungibleLedger::::transfer(asset.id, &origin, &sink, asset.value) + .map_err(Error::::from)?; + Self::deposit_event(Event::Transfer { + asset, + source: origin, + sink, + }); + Ok(().into()) + } + } + + /// Event + #[pallet::event] + #[pallet::generate_deposit(fn deposit_event)] + pub enum Event { + /// Public Transfer Event + Transfer { + /// Asset Transferred + asset: Asset, + + /// Source Account + source: T::AccountId, + + /// Sink Account + sink: T::AccountId, + }, + + /// To Private Event + ToPrivate { + /// Asset Converted + asset: Asset, + + /// Source Account + source: T::AccountId, + }, + + /// Private Transfer Event + PrivateTransfer { + /// Origin Account + origin: T::AccountId, + }, + + /// To Public Event + ToPublic { + /// Asset Converted + asset: Asset, + + /// Sink Account + sink: T::AccountId, + }, + } + + /// Error + #[pallet::error] + pub enum Error { + /// Uninitialized Supply + /// + /// Supply of the given Asset Id has not yet been initialized. + UninitializedSupply, + + /// Zero Transfer + /// + /// Public transfers cannot include amounts equal to zero. + ZeroTransfer, + + /// Balance Low + /// + /// Attempted to withdraw from balance which was smaller than the withdrawal amount. + BalanceLow, + + /// Invalid Serialized Form + /// + /// The transfer could not be interpreted because of an issue during deserialization. + InvalidSerializedForm, + + /// Invalid Shape + /// + /// The transfer had an invalid shape. + InvalidShape, + + /// Asset Spent + /// + /// An asset present in this transfer has already been spent. + AssetSpent, + + /// Invalid UTXO Accumulator Output + /// + /// The sender was constructed on an invalid version of the ledger state. + InvalidUtxoAccumulatorOutput, + + /// Asset Registered + /// + /// An asset present in this transfer has already been registered to the ledger. + AssetRegistered, + + /// Duplicate Spend + /// + /// There were multiple spend entries for the same underlying asset in this transfer. + DuplicateSpend, + + /// Duplicate Register + /// + /// There were multiple register entries for the same underlying asset in this transfer. + DuplicateRegister, + + /// Invalid Proof + /// + /// The submitted proof did not pass validation, or errored during validation. + InvalidProof, + + /// Invalid Source Account + /// + /// At least one of the source accounts is invalid. + InvalidSourceAccount, + + /// Invalid Sink Account + /// + /// At least one of the sink accounts in invalid. + InvalidSinkAccount, + + /// [`InvalidAssetId`](FungibleLedgerError::InvalidAssetId) from [`FungibleLedgerError`] + PublicUpdateInvalidAssetId, + + /// [`BelowMinimum`](FungibleLedgerError::BelowMinimum) from [`FungibleLedgerError`] + PublicUpdateBelowMinimum, + + /// [`CannotCreate`](FungibleLedgerError::CannotCreate) from [`FungibleLedgerError`] + PublicUpdateCannotCreate, + + /// [`UnknownAsset`](FungibleLedgerError::UnknownAsset) from [`FungibleLedgerError`] + PublicUpdateUnknownAsset, + + /// [`Overflow`](FungibleLedgerError::Overflow) from [`FungibleLedgerError`] + PublicUpdateOverflow, + + /// [`Underflow`](FungibleLedgerError::Underflow) from [`FungibleLedgerError`] + PublicUpdateUnderflow, + + /// [`Frozen`](FungibleLedgerError::Frozen) from [`FungibleLedgerError`] + PublicUpdateFrozen, + + /// [`ReducedToZero`](FungibleLedgerError::ReducedToZero) from [`FungibleLedgerError`] + PublicUpdateReducedToZero, + + /// [`NoFunds`](FungibleLedgerError::NoFunds) from [`FungibleLedgerError`] + PublicUpdateNoFunds, + + /// [`WouldDie`](FungibleLedgerError::WouldDie) from [`FungibleLedgerError`] + PublicUpdateWouldDie, + + /// [`InvalidTransfer`](FungibleLedgerError::InvalidTransfer) from [`FungibleLedgerError`] + PublicUpdateInvalidTransfer, + + /// Internal Ledger Error + /// + /// This is caused by some internal error in the ledger and should never occur. + InternalLedgerError, + } + + impl From> for Error + where + T: Config, + { + #[inline] + fn from(_: InvalidSourceAccount) -> Self { + Self::InvalidSourceAccount + } + } + + impl From> for Error + where + T: Config, + { + #[inline] + fn from(_: InvalidSinkAccount) -> Self { + Self::InvalidSinkAccount + } + } + + impl From for Error { + #[inline] + fn from(err: SenderPostError) -> Self { + match err { + SenderPostError::AssetSpent => Self::AssetSpent, + SenderPostError::InvalidUtxoAccumulatorOutput => Self::InvalidUtxoAccumulatorOutput, + } + } + } + + impl From for Error { + #[inline] + fn from(err: ReceiverPostError) -> Self { + match err { + ReceiverPostError::AssetRegistered => Self::AssetRegistered, + } + } + } + + impl From for Error + where + T: Config, + { + #[inline] + fn from(err: FungibleLedgerError) -> Self { + match err { + FungibleLedgerError::InvalidAssetId => Self::PublicUpdateInvalidAssetId, + FungibleLedgerError::BelowMinimum => Self::PublicUpdateBelowMinimum, + FungibleLedgerError::CannotCreate => Self::PublicUpdateCannotCreate, + FungibleLedgerError::UnknownAsset => Self::PublicUpdateUnknownAsset, + FungibleLedgerError::Overflow => Self::PublicUpdateOverflow, + FungibleLedgerError::Underflow => Self::PublicUpdateUnderflow, + FungibleLedgerError::Frozen => Self::PublicUpdateFrozen, + FungibleLedgerError::ReducedToZero(_) => Self::PublicUpdateReducedToZero, + FungibleLedgerError::NoFunds => Self::PublicUpdateNoFunds, + FungibleLedgerError::WouldDie => Self::PublicUpdateWouldDie, + FungibleLedgerError::InvalidTransfer(_e) => Self::PublicUpdateInvalidTransfer, + _ => Self::InternalLedgerError, + } + } + } + + impl From> for Error + where + T: Config, + { + #[inline] + fn from(err: TransferPostError) -> Self { + match err { + TransferPostError::InvalidShape => Self::InvalidShape, + TransferPostError::InvalidSourceAccount(err) => err.into(), + TransferPostError::InvalidSinkAccount(err) => err.into(), + TransferPostError::Sender(err) => err.into(), + TransferPostError::Receiver(err) => err.into(), + TransferPostError::DuplicateSpend => Self::DuplicateSpend, + TransferPostError::DuplicateRegister => Self::DuplicateRegister, + TransferPostError::InvalidProof => Self::InvalidProof, + TransferPostError::UpdateError(err) => err.into(), + } + } + } + + impl Pallet + where + T: Config, + { + /// Maximum Number of Updates per Shard + const PULL_MAX_PER_SHARD_UPDATE_SIZE: usize = 128; + + /// Maximum Size of Sender Data Update + const PULL_MAX_SENDER_UPDATE_SIZE: usize = 1024; + + /// Pulls receiver data from the ledger starting at the `receiver_index`. + #[inline] + fn pull_receivers(receiver_index: [usize; 256]) -> (bool, ReceiverChunk) { + let mut more_receivers = false; + let mut receivers = Vec::new(); + for (i, index) in receiver_index.into_iter().enumerate() { + more_receivers |= Self::pull_receivers_for_shard(i as u8, index, &mut receivers); + } + (more_receivers, receivers) + } + + /// Pulls receiver data from the shard at `shard_index` starting at the `receiver_index`, + /// pushing the results back to `receivers`. + #[inline] + fn pull_receivers_for_shard( + shard_index: u8, + receiver_index: usize, + receivers: &mut ReceiverChunk, + ) -> bool { + let mut iter = if receiver_index == 0 { + Shards::::iter_prefix(shard_index) + } else { + let raw_key = Shards::::hashed_key_for(shard_index, receiver_index as u64 - 1); + Shards::::iter_prefix_from(shard_index, raw_key) + }; + for _ in 0..Self::PULL_MAX_PER_SHARD_UPDATE_SIZE { + match iter.next() { + Some((_, next)) => receivers.push(next), + _ => return false, + } + } + iter.next().is_some() + } + + /// Pulls sender data from the ledger starting at the `sender_index`. + #[inline] + fn pull_senders(sender_index: usize) -> (bool, SenderChunk) { + let mut senders = Vec::new(); + let mut iter = VoidNumberSetInsertionOrder::::iter().skip(sender_index); + for _ in 0..Self::PULL_MAX_SENDER_UPDATE_SIZE { + match iter.next() { + Some((_, next)) => senders.push(next), + _ => return (false, senders), + } + } + (iter.next().is_some(), senders) + } + + /// Returns the diff of ledger state since the given `checkpoint`. + #[inline] + pub fn pull_ledger_diff(checkpoint: Checkpoint) -> PullResponse { + let (more_receivers, receivers) = Self::pull_receivers(*checkpoint.receiver_index); + let (more_senders, senders) = Self::pull_senders(checkpoint.sender_index); + PullResponse { + should_continue: more_receivers || more_senders, + receivers, + senders, + } + } + + /// Returns the account ID of this pallet. + #[inline] + pub fn account_id() -> T::AccountId { + T::PalletId::get().into_account() + } + + /// Posts the transaction encoded in `post` to the ledger, using `sources` and `sinks` as + /// the public deposit and public withdraw accounts respectively. + #[inline] + fn post_transaction( + origin: Option, + sources: Vec, + sinks: Vec, + post: TransferPost, + ) -> DispatchResultWithPostInfo { + Self::deposit_event( + config::TransferPost::try_from(post) + .map_err(|_| Error::::InvalidSerializedForm)? + .post(sources, sinks, &(), &mut Ledger(PhantomData)) + .map_err(Error::::from)? + .convert(origin), + ); + Ok(().into()) + } + } } /// Receiver Chunk Data Type @@ -565,85 +565,85 @@ pub type SenderChunk = Vec; /// Ledger Source Pull Response #[cfg_attr( - feature = "serde", - derive(Deserialize, Serialize), - serde(crate = "manta_util::serde", deny_unknown_fields) + feature = "serde", + derive(Deserialize, Serialize), + serde(crate = "manta_util::serde", deny_unknown_fields) )] #[derive(Clone, Debug, Decode, Default, Encode, Eq, Hash, PartialEq, TypeInfo)] pub struct PullResponse { - /// Pull Continuation Flag - /// - /// The `should_continue` flag is set to `true` if the client should request more data from the - /// ledger to finish the pull. - pub should_continue: bool, + /// Pull Continuation Flag + /// + /// The `should_continue` flag is set to `true` if the client should request more data from the + /// ledger to finish the pull. + pub should_continue: bool, - /// Ledger Receiver Chunk - pub receivers: ReceiverChunk, + /// Ledger Receiver Chunk + pub receivers: ReceiverChunk, - /// Ledger Sender Chunk - pub senders: SenderChunk, + /// Ledger Sender Chunk + pub senders: SenderChunk, } /// Preprocessed Event enum PreprocessedEvent where - T: Config, + T: Config, { - /// To Private Event - ToPrivate { - /// Asset Minted - asset: Asset, - - /// Source Account - source: T::AccountId, - }, - - /// Private Transfer Event - PrivateTransfer, - - /// To Public Event - ToPublic { - /// Asset Reclaimed - asset: Asset, - - /// Sink Account - sink: T::AccountId, - }, + /// To Private Event + ToPrivate { + /// Asset Minted + asset: Asset, + + /// Source Account + source: T::AccountId, + }, + + /// Private Transfer Event + PrivateTransfer, + + /// To Public Event + ToPublic { + /// Asset Reclaimed + asset: Asset, + + /// Sink Account + sink: T::AccountId, + }, } impl PreprocessedEvent where - T: Config, + T: Config, { - /// Converts a [`PreprocessedEvent`] with into an [`Event`] using the given `origin` for - /// [`PreprocessedEvent::PrivateTransfer`]. - #[inline] - fn convert(self, origin: Option) -> Event { - match self { - Self::ToPrivate { asset, source } => Event::ToPrivate { asset, source }, - Self::PrivateTransfer => Event::PrivateTransfer { - // FIXME: get rid of unwrap eventually. - origin: origin.unwrap(), - }, - Self::ToPublic { asset, sink } => Event::ToPublic { asset, sink }, - } - } + /// Converts a [`PreprocessedEvent`] with into an [`Event`] using the given `origin` for + /// [`PreprocessedEvent::PrivateTransfer`]. + #[inline] + fn convert(self, origin: Option) -> Event { + match self { + Self::ToPrivate { asset, source } => Event::ToPrivate { asset, source }, + Self::PrivateTransfer => Event::PrivateTransfer { + // FIXME: get rid of unwrap eventually. + origin: origin.unwrap(), + }, + Self::ToPublic { asset, sink } => Event::ToPublic { asset, sink }, + } + } } /// Ledger struct Ledger(PhantomData) where - T: Config; + T: Config; /// Wrap Type #[derive(Clone, Copy)] pub struct Wrap(T); impl AsRef for Wrap { - #[inline] - fn as_ref(&self) -> &T { - &self.0 - } + #[inline] + fn as_ref(&self) -> &T { + &self.0 + } } /// Wrap Pair Type @@ -651,265 +651,265 @@ impl AsRef for Wrap { pub struct WrapPair(L, R); impl AsRef for WrapPair { - #[inline] - fn as_ref(&self) -> &R { - &self.1 - } + #[inline] + fn as_ref(&self) -> &R { + &self.1 + } } impl SenderLedger for Ledger where - T: Config, + T: Config, { - type ValidVoidNumber = Wrap; - type ValidUtxoAccumulatorOutput = Wrap; - type SuperPostingKey = (Wrap<()>, ()); - - #[inline] - fn is_unspent(&self, void_number: config::VoidNumber) -> Option { - if VoidNumberSet::::contains_key(encode(&void_number)) { - None - } else { - Some(Wrap(void_number)) - } - } - - #[inline] - fn has_matching_utxo_accumulator_output( - &self, - output: config::UtxoAccumulatorOutput, - ) -> Option { - if UtxoAccumulatorOutputs::::contains_key(encode(&output)) { - return Some(Wrap(output)); - } - None - } - - #[inline] - fn spend_all(&mut self, iter: I, super_key: &Self::SuperPostingKey) - where - I: IntoIterator, - { - let _ = super_key; - let index = VoidNumberSetSize::::get(); - let mut i = 0; - for (_, void_number) in iter { - let void_number = encode(&void_number.0); - VoidNumberSet::::insert(void_number, ()); - VoidNumberSetInsertionOrder::::insert(index + i, void_number); - i += 1; - } - if i != 0 { - VoidNumberSetSize::::set(index + i); - } - } + type ValidVoidNumber = Wrap; + type ValidUtxoAccumulatorOutput = Wrap; + type SuperPostingKey = (Wrap<()>, ()); + + #[inline] + fn is_unspent(&self, void_number: config::VoidNumber) -> Option { + if VoidNumberSet::::contains_key(encode(&void_number)) { + None + } else { + Some(Wrap(void_number)) + } + } + + #[inline] + fn has_matching_utxo_accumulator_output( + &self, + output: config::UtxoAccumulatorOutput, + ) -> Option { + if UtxoAccumulatorOutputs::::contains_key(encode(&output)) { + return Some(Wrap(output)); + } + None + } + + #[inline] + fn spend_all(&mut self, iter: I, super_key: &Self::SuperPostingKey) + where + I: IntoIterator, + { + let _ = super_key; + let index = VoidNumberSetSize::::get(); + let mut i = 0; + for (_, void_number) in iter { + let void_number = encode(&void_number.0); + VoidNumberSet::::insert(void_number, ()); + VoidNumberSetInsertionOrder::::insert(index + i, void_number); + i += 1; + } + if i != 0 { + VoidNumberSetSize::::set(index + i); + } + } } impl ReceiverLedger for Ledger where - T: Config, + T: Config, { - type ValidUtxo = Wrap; - type SuperPostingKey = (Wrap<()>, ()); - - #[inline] - fn is_not_registered(&self, utxo: config::Utxo) -> Option { - if UtxoSet::::contains_key(encode(&utxo)) { - None - } else { - Some(Wrap(utxo)) - } - } - - #[inline] - fn register_all(&mut self, iter: I, super_key: &Self::SuperPostingKey) - where - I: IntoIterator, - { - let _ = super_key; - let parameters = config::UtxoAccumulatorModel::decode( - manta_sdk::pay::testnet::parameters::UtxoAccumulatorModel::get() - .expect("Checksum did not match."), - ) - .expect("Unable to decode the Merkle Tree Parameters."); - let mut shard_indices = iter - .into_iter() - .map(move |(utxo, note)| { - ( - config::MerkleTreeConfiguration::tree_index(&utxo.0), - utxo.0, - note, - ) - }) - .collect::>(); - shard_indices.sort_by_key(|(s, _, _)| *s); - let mut shard_insertions = Vec::<(_, Vec<_>)>::new(); - for (shard_index, utxo, note) in shard_indices { - match shard_insertions.last_mut() { - Some((index, pairs)) if shard_index == *index => pairs.push((utxo, note)), - _ => shard_insertions.push((shard_index, vec![(utxo, note)])), - } - } - for (shard_index, insertions) in shard_insertions { - let mut tree = ShardTrees::::get(shard_index); - let mut next_root = Option::::None; - let mut current_path = core::mem::take(&mut tree.current_path).into(); - for (utxo, note) in insertions { - next_root = Some( - merkle_tree::single_path::raw::insert( - ¶meters, - &mut tree.leaf_digest, - &mut current_path, - utxo, - ) - .expect("If this errors, then we have run out of Merkle Tree capacity."), - ); - let next_index = current_path.leaf_index().0 as u64; - let utxo = encode(&utxo); - UtxoSet::::insert(utxo, ()); - Shards::::insert(shard_index, next_index, (utxo, EncryptedNote::from(note))); - } - tree.current_path = current_path.into(); - if let Some(next_root) = next_root { - ShardTrees::::insert(shard_index, tree); - UtxoAccumulatorOutputs::::insert(encode(&next_root), ()); - } - } - } + type ValidUtxo = Wrap; + type SuperPostingKey = (Wrap<()>, ()); + + #[inline] + fn is_not_registered(&self, utxo: config::Utxo) -> Option { + if UtxoSet::::contains_key(encode(&utxo)) { + None + } else { + Some(Wrap(utxo)) + } + } + + #[inline] + fn register_all(&mut self, iter: I, super_key: &Self::SuperPostingKey) + where + I: IntoIterator, + { + let _ = super_key; + let parameters = config::UtxoAccumulatorModel::decode( + manta_sdk::pay::testnet::parameters::UtxoAccumulatorModel::get() + .expect("Checksum did not match."), + ) + .expect("Unable to decode the Merkle Tree Parameters."); + let mut shard_indices = iter + .into_iter() + .map(move |(utxo, note)| { + ( + config::MerkleTreeConfiguration::tree_index(&utxo.0), + utxo.0, + note, + ) + }) + .collect::>(); + shard_indices.sort_by_key(|(s, _, _)| *s); + let mut shard_insertions = Vec::<(_, Vec<_>)>::new(); + for (shard_index, utxo, note) in shard_indices { + match shard_insertions.last_mut() { + Some((index, pairs)) if shard_index == *index => pairs.push((utxo, note)), + _ => shard_insertions.push((shard_index, vec![(utxo, note)])), + } + } + for (shard_index, insertions) in shard_insertions { + let mut tree = ShardTrees::::get(shard_index); + let mut next_root = Option::::None; + let mut current_path = core::mem::take(&mut tree.current_path).into(); + for (utxo, note) in insertions { + next_root = Some( + merkle_tree::single_path::raw::insert( + ¶meters, + &mut tree.leaf_digest, + &mut current_path, + utxo, + ) + .expect("If this errors, then we have run out of Merkle Tree capacity."), + ); + let next_index = current_path.leaf_index().0 as u64; + let utxo = encode(&utxo); + UtxoSet::::insert(utxo, ()); + Shards::::insert(shard_index, next_index, (utxo, EncryptedNote::from(note))); + } + tree.current_path = current_path.into(); + if let Some(next_root) = next_root { + ShardTrees::::insert(shard_index, tree); + UtxoAccumulatorOutputs::::insert(encode(&next_root), ()); + } + } + } } impl TransferLedger for Ledger where - T: Config, + T: Config, { - type AccountId = T::AccountId; - type UpdateError = FungibleLedgerError; - type Event = PreprocessedEvent; - type ValidSourceAccount = WrapPair; - type ValidSinkAccount = WrapPair; - type ValidProof = Wrap<()>; - type SuperPostingKey = (); - - #[inline] - fn check_source_accounts( - &self, - asset_id: asset::AssetId, - sources: I, - ) -> Result, InvalidSourceAccount> - where - I: Iterator, - { - sources - .map(move |(account_id, withdraw)| { - FungibleLedger::::can_withdraw(asset_id.0, &account_id, withdraw.0) - .map(|_| WrapPair(account_id.clone(), withdraw)) - .map_err(|_| InvalidSourceAccount { - account_id, - asset_id, - withdraw, - }) - }) - .collect() - } - - #[inline] - fn check_sink_accounts( - &self, - asset_id: asset::AssetId, - sinks: I, - ) -> Result, InvalidSinkAccount> - where - I: Iterator, - { - // NOTE: Existence of accounts is type-checked so we don't need to do anything here, just - // pass the data forward. - sinks - .map(move |(account_id, deposit)| { - FungibleLedger::::can_deposit(asset_id.0, &account_id, deposit.0) - .map(|_| WrapPair(account_id.clone(), deposit)) - .map_err(|_| InvalidSinkAccount { - account_id, - asset_id, - deposit, - }) - }) - .collect() - } - - #[inline] - fn is_valid( - &self, - asset_id: Option, - sources: &[SourcePostingKey], - senders: &[SenderPostingKey], - receivers: &[ReceiverPostingKey], - sinks: &[SinkPostingKey], - proof: Proof, - ) -> Option<(Self::ValidProof, Self::Event)> { - let (mut verifying_context, event) = match TransferShape::select( - asset_id.is_some(), - sources.len(), - senders.len(), - receivers.len(), - sinks.len(), - )? { - TransferShape::Mint => ( - manta_sdk::pay::testnet::verifying::Mint::get().expect("Checksum did not match."), - PreprocessedEvent::::ToPrivate { - asset: Asset::new(asset_id.unwrap().0, (sources[0].1).0), - source: sources[0].0.clone(), - }, - ), - TransferShape::PrivateTransfer => ( - manta_sdk::pay::testnet::verifying::PrivateTransfer::get() - .expect("Checksum did not match."), - PreprocessedEvent::::PrivateTransfer, - ), - TransferShape::Reclaim => ( - manta_sdk::pay::testnet::verifying::Reclaim::get() - .expect("Checksum did not match."), - PreprocessedEvent::::ToPublic { - asset: Asset::new(asset_id.unwrap().0, (sinks[0].1).0), - sink: sinks[0].0.clone(), - }, - ), - }; - config::ProofSystem::verify( - &config::VerifyingContext::decode(&mut verifying_context) - .expect("Unable to decode the verifying context."), - &TransferPostingKey::generate_proof_input(asset_id, sources, senders, receivers, sinks), - &proof, - ) - .ok()? - .then(move || (Wrap(()), event)) - } - - #[inline] - fn update_public_balances( - &mut self, - asset_id: asset::AssetId, - sources: Vec>, - sinks: Vec>, - proof: Self::ValidProof, - super_key: &TransferLedgerSuperPostingKey, - ) -> Result<(), Self::UpdateError> { - let _ = (proof, super_key); - for WrapPair(account_id, withdraw) in sources { - FungibleLedger::::transfer( - asset_id.0, - &account_id, - &Pallet::::account_id(), - withdraw.0, - )?; - } - for WrapPair(account_id, deposit) in sinks { - FungibleLedger::::transfer( - asset_id.0, - &Pallet::::account_id(), - &account_id, - deposit.0, - )?; - } - Ok(()) - } + type AccountId = T::AccountId; + type UpdateError = FungibleLedgerError; + type Event = PreprocessedEvent; + type ValidSourceAccount = WrapPair; + type ValidSinkAccount = WrapPair; + type ValidProof = Wrap<()>; + type SuperPostingKey = (); + + #[inline] + fn check_source_accounts( + &self, + asset_id: asset::AssetId, + sources: I, + ) -> Result, InvalidSourceAccount> + where + I: Iterator, + { + sources + .map(move |(account_id, withdraw)| { + FungibleLedger::::can_withdraw(asset_id.0, &account_id, withdraw.0) + .map(|_| WrapPair(account_id.clone(), withdraw)) + .map_err(|_| InvalidSourceAccount { + account_id, + asset_id, + withdraw, + }) + }) + .collect() + } + + #[inline] + fn check_sink_accounts( + &self, + asset_id: asset::AssetId, + sinks: I, + ) -> Result, InvalidSinkAccount> + where + I: Iterator, + { + // NOTE: Existence of accounts is type-checked so we don't need to do anything here, just + // pass the data forward. + sinks + .map(move |(account_id, deposit)| { + FungibleLedger::::can_deposit(asset_id.0, &account_id, deposit.0) + .map(|_| WrapPair(account_id.clone(), deposit)) + .map_err(|_| InvalidSinkAccount { + account_id, + asset_id, + deposit, + }) + }) + .collect() + } + + #[inline] + fn is_valid( + &self, + asset_id: Option, + sources: &[SourcePostingKey], + senders: &[SenderPostingKey], + receivers: &[ReceiverPostingKey], + sinks: &[SinkPostingKey], + proof: Proof, + ) -> Option<(Self::ValidProof, Self::Event)> { + let (mut verifying_context, event) = match TransferShape::select( + asset_id.is_some(), + sources.len(), + senders.len(), + receivers.len(), + sinks.len(), + )? { + TransferShape::Mint => ( + manta_sdk::pay::testnet::verifying::Mint::get().expect("Checksum did not match."), + PreprocessedEvent::::ToPrivate { + asset: Asset::new(asset_id.unwrap().0, (sources[0].1).0), + source: sources[0].0.clone(), + }, + ), + TransferShape::PrivateTransfer => ( + manta_sdk::pay::testnet::verifying::PrivateTransfer::get() + .expect("Checksum did not match."), + PreprocessedEvent::::PrivateTransfer, + ), + TransferShape::Reclaim => ( + manta_sdk::pay::testnet::verifying::Reclaim::get() + .expect("Checksum did not match."), + PreprocessedEvent::::ToPublic { + asset: Asset::new(asset_id.unwrap().0, (sinks[0].1).0), + sink: sinks[0].0.clone(), + }, + ), + }; + config::ProofSystem::verify( + &config::VerifyingContext::decode(&mut verifying_context) + .expect("Unable to decode the verifying context."), + &TransferPostingKey::generate_proof_input(asset_id, sources, senders, receivers, sinks), + &proof, + ) + .ok()? + .then(move || (Wrap(()), event)) + } + + #[inline] + fn update_public_balances( + &mut self, + asset_id: asset::AssetId, + sources: Vec>, + sinks: Vec>, + proof: Self::ValidProof, + super_key: &TransferLedgerSuperPostingKey, + ) -> Result<(), Self::UpdateError> { + let _ = (proof, super_key); + for WrapPair(account_id, withdraw) in sources { + FungibleLedger::::transfer( + asset_id.0, + &account_id, + &Pallet::::account_id(), + withdraw.0, + )?; + } + for WrapPair(account_id, deposit) in sinks { + FungibleLedger::::transfer( + asset_id.0, + &Pallet::::account_id(), + &account_id, + deposit.0, + )?; + } + Ok(()) + } } diff --git a/pallets/manta-pay/src/mock.rs b/pallets/manta-pay/src/mock.rs index 01ba256f2..4580d02cf 100644 --- a/pallets/manta-pay/src/mock.rs +++ b/pallets/manta-pay/src/mock.rs @@ -1,247 +1,247 @@ -// Copyright 2019-2022 Manta Network. -// This file is part of pallet-manta-pay. +// Copyright 2020-2022 Manta Network. +// This file is part of Manta. // -// pallet-manta-pay is free software: you can redistribute it and/or modify +// Manta 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. // -// pallet-manta-pay is distributed in the hope that it will be useful, +// Manta 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 pallet-manta-pay. If not, see . +// along with Manta. If not, see . use frame_support::{ - pallet_prelude::DispatchResult, - parameter_types, - traits::{ConstU32, Everything}, - PalletId, + pallet_prelude::DispatchResult, + parameter_types, + traits::{ConstU32, Everything}, + PalletId, }; use frame_system::EnsureRoot; use manta_primitives::{ - assets::{ - AssetConfig, AssetLocation, AssetRegistrar, AssetRegistrarMetadata, AssetStorageMetadata, - ConcreteFungibleLedger, - }, - constants::{ASSET_MANAGER_PALLET_ID, MANTA_PAY_PALLET_ID}, - types::{AssetId, Balance}, + assets::{ + AssetConfig, AssetLocation, AssetRegistrar, AssetRegistrarMetadata, AssetStorageMetadata, + ConcreteFungibleLedger, + }, + constants::{ASSET_MANAGER_PALLET_ID, MANTA_PAY_PALLET_ID}, + types::{AssetId, Balance}, }; use sp_core::H256; use sp_runtime::{ - testing::Header, - traits::{BlakeTwo256, IdentityLookup}, - AccountId32, + testing::Header, + traits::{BlakeTwo256, IdentityLookup}, + AccountId32, }; use xcm::{ - prelude::{Parachain, X1}, - v1::MultiLocation, - VersionedMultiLocation, + prelude::{Parachain, X1}, + v1::MultiLocation, + VersionedMultiLocation, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - System: frame_system::{Pallet, Call, Config, Storage, Event}, - MantaPayPallet: crate::{Pallet, Call, Storage, Event}, - Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - Assets: pallet_assets::{Pallet, Storage, Event}, - AssetManager: pallet_asset_manager::{Pallet, Call, Storage, Event}, - } + pub enum Test where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Config, Storage, Event}, + MantaPayPallet: crate::{Pallet, Call, Storage, Event}, + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, + Assets: pallet_assets::{Pallet, Storage, Event}, + AssetManager: pallet_asset_manager::{Pallet, Call, Storage, Event}, + } ); type BlockNumber = u64; parameter_types! { - pub const BlockHashCount: BlockNumber = 250; - pub const SS58Prefix: u8 = 42; + pub const BlockHashCount: BlockNumber = 250; + pub const SS58Prefix: u8 = 42; } impl frame_system::Config for Test { - type BaseCallFilter = Everything; - type BlockWeights = (); - type BlockLength = (); - type DbWeight = (); - type Origin = Origin; - type Call = Call; - type Index = u64; - type BlockNumber = BlockNumber; - type Hash = H256; - type Hashing = BlakeTwo256; - type AccountId = AccountId32; - type Lookup = IdentityLookup; - type Header = Header; - type Event = Event; - type BlockHashCount = BlockHashCount; - 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>; + type BaseCallFilter = Everything; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type Origin = Origin; + type Call = Call; + type Index = u64; + type BlockNumber = BlockNumber; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = AccountId32; + type Lookup = IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = BlockHashCount; + 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>; } parameter_types! { - pub ExistentialDeposit: Balance = 1; - pub const MaxLocks: u32 = 50; - pub const MaxReserves: u32 = 50; + pub ExistentialDeposit: Balance = 1; + pub const MaxLocks: u32 = 50; + pub const MaxReserves: u32 = 50; } impl pallet_balances::Config for Test { - type MaxLocks = MaxLocks; - type Balance = Balance; - type Event = Event; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; - type WeightInfo = (); - type MaxReserves = MaxReserves; - type ReserveIdentifier = [u8; 8]; + type MaxLocks = MaxLocks; + type Balance = Balance; + type Event = Event; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = (); + type MaxReserves = MaxReserves; + type ReserveIdentifier = [u8; 8]; } parameter_types! { - pub const AssetDeposit: Balance = 0; // Does not really matter as this will be only called by root - pub const AssetAccountDeposit: Balance = 0; - pub const ApprovalDeposit: Balance = 0; - pub const AssetsStringLimit: u32 = 50; - pub const MetadataDepositBase: Balance = 0; - pub const MetadataDepositPerByte: Balance = 0; + pub const AssetDeposit: Balance = 0; // Does not really matter as this will be only called by root + pub const AssetAccountDeposit: Balance = 0; + pub const ApprovalDeposit: Balance = 0; + pub const AssetsStringLimit: u32 = 50; + pub const MetadataDepositBase: Balance = 0; + pub const MetadataDepositPerByte: Balance = 0; } impl pallet_assets::Config for Test { - type Event = Event; - type Balance = Balance; - type AssetId = AssetId; - type Currency = Balances; - type ForceOrigin = EnsureRoot; - type AssetDeposit = AssetDeposit; - type AssetAccountDeposit = AssetAccountDeposit; - type MetadataDepositBase = MetadataDepositBase; - type MetadataDepositPerByte = MetadataDepositPerByte; - type ApprovalDeposit = ApprovalDeposit; - type StringLimit = AssetsStringLimit; - type Freezer = (); - type Extra = (); - type WeightInfo = pallet_assets::weights::SubstrateWeight; + type Event = Event; + type Balance = Balance; + type AssetId = AssetId; + type Currency = Balances; + type ForceOrigin = EnsureRoot; + type AssetDeposit = AssetDeposit; + type AssetAccountDeposit = AssetAccountDeposit; + type MetadataDepositBase = MetadataDepositBase; + type MetadataDepositPerByte = MetadataDepositPerByte; + type ApprovalDeposit = ApprovalDeposit; + type StringLimit = AssetsStringLimit; + type Freezer = (); + type Extra = (); + type WeightInfo = pallet_assets::weights::SubstrateWeight; } pub struct MantaAssetRegistrar; impl AssetRegistrar for MantaAssetRegistrar { - fn create_asset( - asset_id: AssetId, - min_balance: Balance, - metadata: AssetStorageMetadata, - is_sufficient: bool, - ) -> DispatchResult { - Assets::force_create( - Origin::root(), - asset_id, - AssetManager::account_id(), - is_sufficient, - min_balance, - )?; - - Assets::force_set_metadata( - Origin::root(), - asset_id, - metadata.name, - metadata.symbol, - metadata.decimals, - metadata.is_frozen, - )?; - - Assets::force_asset_status( - Origin::root(), - asset_id, - AssetManager::account_id(), - AssetManager::account_id(), - AssetManager::account_id(), - AssetManager::account_id(), - min_balance, - is_sufficient, - metadata.is_frozen, - ) - } - - fn update_asset_metadata(asset_id: AssetId, metadata: AssetStorageMetadata) -> DispatchResult { - Assets::force_set_metadata( - Origin::root(), - asset_id, - metadata.name, - metadata.symbol, - metadata.decimals, - metadata.is_frozen, - ) - } + fn create_asset( + asset_id: AssetId, + min_balance: Balance, + metadata: AssetStorageMetadata, + is_sufficient: bool, + ) -> DispatchResult { + Assets::force_create( + Origin::root(), + asset_id, + AssetManager::account_id(), + is_sufficient, + min_balance, + )?; + + Assets::force_set_metadata( + Origin::root(), + asset_id, + metadata.name, + metadata.symbol, + metadata.decimals, + metadata.is_frozen, + )?; + + Assets::force_asset_status( + Origin::root(), + asset_id, + AssetManager::account_id(), + AssetManager::account_id(), + AssetManager::account_id(), + AssetManager::account_id(), + min_balance, + is_sufficient, + metadata.is_frozen, + ) + } + + fn update_asset_metadata(asset_id: AssetId, metadata: AssetStorageMetadata) -> DispatchResult { + Assets::force_set_metadata( + Origin::root(), + asset_id, + metadata.name, + metadata.symbol, + metadata.decimals, + metadata.is_frozen, + ) + } } parameter_types! { - pub const DummyAssetId: AssetId = 0; - pub const NativeAssetId: AssetId = 1; - pub const StartNonNativeAssetId: AssetId = 8; - pub NativeAssetLocation: AssetLocation = AssetLocation( - VersionedMultiLocation::V1(MultiLocation::new(1, X1(Parachain(1024))))); - pub NativeAssetMetadata: AssetRegistrarMetadata = AssetRegistrarMetadata { - name: b"Dolphin".to_vec(), - symbol: b"DOL".to_vec(), - decimals: 18, - min_balance: 1u128, - evm_address: None, - is_frozen: false, - is_sufficient: true, - }; - pub const AssetManagerPalletId: PalletId = ASSET_MANAGER_PALLET_ID; + pub const DummyAssetId: AssetId = 0; + pub const NativeAssetId: AssetId = 1; + pub const StartNonNativeAssetId: AssetId = 8; + pub NativeAssetLocation: AssetLocation = AssetLocation( + VersionedMultiLocation::V1(MultiLocation::new(1, X1(Parachain(1024))))); + pub NativeAssetMetadata: AssetRegistrarMetadata = AssetRegistrarMetadata { + name: b"Dolphin".to_vec(), + symbol: b"DOL".to_vec(), + decimals: 18, + min_balance: 1u128, + evm_address: None, + is_frozen: false, + is_sufficient: true, + }; + pub const AssetManagerPalletId: PalletId = ASSET_MANAGER_PALLET_ID; } #[derive(Clone, Eq, PartialEq)] pub struct MantaAssetConfig; impl AssetConfig for MantaAssetConfig { - type DummyAssetId = DummyAssetId; - type NativeAssetId = NativeAssetId; - type StartNonNativeAssetId = StartNonNativeAssetId; - type AssetRegistrarMetadata = AssetRegistrarMetadata; - type NativeAssetLocation = NativeAssetLocation; - type NativeAssetMetadata = NativeAssetMetadata; - type StorageMetadata = AssetStorageMetadata; - type AssetLocation = AssetLocation; - type AssetRegistrar = MantaAssetRegistrar; - type FungibleLedger = ConcreteFungibleLedger; + type DummyAssetId = DummyAssetId; + type NativeAssetId = NativeAssetId; + type StartNonNativeAssetId = StartNonNativeAssetId; + type AssetRegistrarMetadata = AssetRegistrarMetadata; + type NativeAssetLocation = NativeAssetLocation; + type NativeAssetMetadata = NativeAssetMetadata; + type StorageMetadata = AssetStorageMetadata; + type AssetLocation = AssetLocation; + type AssetRegistrar = MantaAssetRegistrar; + type FungibleLedger = ConcreteFungibleLedger; } impl pallet_asset_manager::Config for Test { - type Event = Event; - type AssetConfig = MantaAssetConfig; - type ModifierOrigin = EnsureRoot; - type PalletId = AssetManagerPalletId; - type WeightInfo = (); + type Event = Event; + type AssetConfig = MantaAssetConfig; + type ModifierOrigin = EnsureRoot; + type PalletId = AssetManagerPalletId; + type WeightInfo = (); } parameter_types! { - pub const MantaPayPalletId: PalletId = MANTA_PAY_PALLET_ID; + pub const MantaPayPalletId: PalletId = MANTA_PAY_PALLET_ID; } impl crate::Config for Test { - type Event = Event; - type WeightInfo = crate::weights::SubstrateWeight; - type PalletId = MantaPayPalletId; - type AssetConfig = MantaAssetConfig; + type Event = Event; + type WeightInfo = crate::weights::SubstrateWeight; + type PalletId = MantaPayPalletId; + type AssetConfig = MantaAssetConfig; } pub fn new_test_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default() - .build_storage::() - .unwrap() - .into() + frame_system::GenesisConfig::default() + .build_storage::() + .unwrap() + .into() } diff --git a/pallets/manta-pay/src/rpc.rs b/pallets/manta-pay/src/rpc.rs index e0af4b406..f74b329c8 100644 --- a/pallets/manta-pay/src/rpc.rs +++ b/pallets/manta-pay/src/rpc.rs @@ -1,18 +1,18 @@ -// Copyright 2019-2022 Manta Network. -// This file is part of pallet-manta-pay. +// Copyright 2020-2022 Manta Network. +// This file is part of Manta. // -// pallet-manta-pay is free software: you can redistribute it and/or modify +// Manta 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. // -// pallet-manta-pay is distributed in the hope that it will be useful, +// Manta 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 pallet-manta-pay. If not, see . +// along with Manta. If not, see . //! MantaPay RPC Interfaces @@ -29,47 +29,47 @@ use sp_runtime::{generic::BlockId, traits::Block}; /// Pull API #[rpc(server)] pub trait PullApi { - /// Returns the update required to be synchronized with the ledger starting from - /// `checkpoint`. - #[rpc(name = "mantaPay_pull_ledger_diff")] - fn pull_ledger_diff(&self, checkpoint: Checkpoint) -> Result; + /// Returns the update required to be synchronized with the ledger starting from + /// `checkpoint`. + #[rpc(name = "mantaPay_pull_ledger_diff")] + fn pull_ledger_diff(&self, checkpoint: Checkpoint) -> Result; } /// Pull RPC API Implementation pub struct Pull { - /// Client - client: Arc, + /// Client + client: Arc, - /// Type Parameter Marker - __: PhantomData, + /// Type Parameter Marker + __: PhantomData, } impl Pull { - /// Builds a new [`Pull`] RPC API implementation. - #[inline] - pub fn new(client: Arc) -> Self { - Self { - client, - __: PhantomData, - } - } + /// Builds a new [`Pull`] RPC API implementation. + #[inline] + pub fn new(client: Arc) -> Self { + Self { + client, + __: PhantomData, + } + } } impl PullApi for Pull where - B: Block, - C: 'static + ProvideRuntimeApi + HeaderBackend, - C::Api: PullLedgerDiffApi, + B: Block, + C: 'static + ProvideRuntimeApi + HeaderBackend, + C::Api: PullLedgerDiffApi, { - #[inline] - fn pull_ledger_diff(&self, checkpoint: Checkpoint) -> Result { - let api = self.client.runtime_api(); - let at = BlockId::hash(self.client.info().best_hash); - api.pull_ledger_diff(&at, checkpoint.into()) - .map_err(|err| Error { - code: ErrorCode::ServerError(1), - message: "Unable to compute state diff for pull".into(), - data: Some(err.to_string().into()), - }) - } + #[inline] + fn pull_ledger_diff(&self, checkpoint: Checkpoint) -> Result { + let api = self.client.runtime_api(); + let at = BlockId::hash(self.client.info().best_hash); + api.pull_ledger_diff(&at, checkpoint.into()) + .map_err(|err| Error { + code: ErrorCode::ServerError(1), + message: "Unable to compute state diff for pull".into(), + data: Some(err.to_string().into()), + }) + } } diff --git a/pallets/manta-pay/src/runtime.rs b/pallets/manta-pay/src/runtime.rs index 2414cd51e..20e247012 100644 --- a/pallets/manta-pay/src/runtime.rs +++ b/pallets/manta-pay/src/runtime.rs @@ -1,18 +1,18 @@ -// Copyright 2019-2022 Manta Network. -// This file is part of pallet-manta-pay. +// Copyright 2020-2022 Manta Network. +// This file is part of Manta. // -// pallet-manta-pay is free software: you can redistribute it and/or modify +// Manta 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. // -// pallet-manta-pay is distributed in the hope that it will be useful, +// Manta 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 pallet-manta-pay. If not, see . +// along with Manta. If not, see . //! MantaPay Runtime APIs @@ -20,7 +20,7 @@ use crate::PullResponse; use manta_pay::signer::RawCheckpoint; sp_api::decl_runtime_apis! { - pub trait PullLedgerDiffApi { - fn pull_ledger_diff(checkpoint: RawCheckpoint) -> PullResponse; - } + pub trait PullLedgerDiffApi { + fn pull_ledger_diff(checkpoint: RawCheckpoint) -> PullResponse; + } } diff --git a/pallets/manta-pay/src/test/mod.rs b/pallets/manta-pay/src/test/mod.rs index 2e3213fc2..0b70190fe 100644 --- a/pallets/manta-pay/src/test/mod.rs +++ b/pallets/manta-pay/src/test/mod.rs @@ -1,18 +1,18 @@ -// Copyright 2019-2022 Manta Network. -// This file is part of pallet-manta-pay. +// Copyright 2020-2022 Manta Network. +// This file is part of Manta. // -// pallet-manta-pay is free software: you can redistribute it and/or modify +// Manta 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. // -// pallet-manta-pay is distributed in the hope that it will be useful, +// Manta 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 pallet-manta-pay. If not, see . +// along with Manta. If not, see . mod payment; mod storage; diff --git a/pallets/manta-pay/src/test/payment.rs b/pallets/manta-pay/src/test/payment.rs index 86cd2617c..ce634c310 100644 --- a/pallets/manta-pay/src/test/payment.rs +++ b/pallets/manta-pay/src/test/payment.rs @@ -1,41 +1,41 @@ -// Copyright 2019-2022 Manta Network. -// This file is part of pallet-manta-pay. +// Copyright 2020-2022 Manta Network. +// This file is part of Manta. // -// pallet-manta-pay is free software: you can redistribute it and/or modify +// Manta 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. // -// pallet-manta-pay is distributed in the hope that it will be useful, +// Manta 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 pallet-manta-pay. If not, see . +// along with Manta. If not, see . use crate::{ - mock::{new_test_ext, MantaAssetConfig, MantaAssetRegistrar, MantaPayPallet, Origin, Test}, - Error, FungibleLedger, + mock::{new_test_ext, MantaAssetConfig, MantaAssetRegistrar, MantaPayPallet, Origin, Test}, + Error, FungibleLedger, }; use frame_support::{assert_noop, assert_ok}; use manta_accounting::{ - asset::{Asset, AssetId, AssetValue}, - transfer::{self, test::value_distribution, SpendingKey}, + asset::{Asset, AssetId, AssetValue}, + transfer::{self, test::value_distribution, SpendingKey}, }; use manta_crypto::{ - accumulator::Accumulator, - merkle_tree::{forest::TreeArrayMerkleForest, full::Full}, - rand::{CryptoRng, Rand, RngCore, Sample}, + accumulator::Accumulator, + merkle_tree::{forest::TreeArrayMerkleForest, full::Full}, + rand::{CryptoRng, Rand, RngCore, Sample}, }; use manta_pay::config::{ - FullParameters, MerkleTreeConfiguration, Mint, MultiProvingContext, NoteEncryptionScheme, - Parameters, PrivateTransfer, ProvingContext, Reclaim, TransferPost, UtxoAccumulatorModel, - UtxoCommitmentScheme, VoidNumberCommitmentScheme, + FullParameters, MerkleTreeConfiguration, Mint, MultiProvingContext, NoteEncryptionScheme, + Parameters, PrivateTransfer, ProvingContext, Reclaim, TransferPost, UtxoAccumulatorModel, + UtxoCommitmentScheme, VoidNumberCommitmentScheme, }; use manta_primitives::{ - assets::{AssetConfig, AssetRegistrar, AssetRegistrarMetadata, FungibleLedger as _}, - constants::DEFAULT_ASSET_ED, + assets::{AssetConfig, AssetRegistrar, AssetRegistrarMetadata, FungibleLedger as _}, + constants::DEFAULT_ASSET_ED, }; use manta_util::codec::{Decode, IoReader}; use rand::thread_rng; @@ -43,424 +43,424 @@ use std::fs::File; /// UTXO Accumulator for Building Circuits type UtxoAccumulator = - TreeArrayMerkleForest, 256>; + TreeArrayMerkleForest, 256>; lazy_static::lazy_static! { - static ref PROVING_CONTEXT: MultiProvingContext = load_proving_context(); - static ref PARAMETERS: Parameters = load_parameters(); - static ref UTXO_ACCUMULATOR_MODEL: UtxoAccumulatorModel = load_utxo_accumulator_model(); + static ref PROVING_CONTEXT: MultiProvingContext = load_proving_context(); + static ref PARAMETERS: Parameters = load_parameters(); + static ref UTXO_ACCUMULATOR_MODEL: UtxoAccumulatorModel = load_utxo_accumulator_model(); } pub const ALICE: sp_runtime::AccountId32 = sp_runtime::AccountId32::new([0u8; 32]); pub const NATIVE_ASSET_ID: AssetId = - AssetId(>::NativeAssetId::get()); + AssetId(>::NativeAssetId::get()); /// Loads the [`MultiProvingContext`] from the SDK. #[inline] fn load_proving_context() -> MultiProvingContext { - let directory = tempfile::tempdir().expect("Unable to create temporary directory."); - let path = directory.path(); - let mint_path = path.join("mint.dat"); - manta_sdk::pay::testnet::proving::Mint::download(&mint_path) - .expect("Unable to download MINT proving context."); - let private_transfer_path = path.join("private-transfer.dat"); - manta_sdk::pay::testnet::proving::PrivateTransfer::download(&private_transfer_path) - .expect("Unable to download PRIVATE_TRANSFER proving context."); - let reclaim_path = path.join("reclaim.dat"); - manta_sdk::pay::testnet::proving::Reclaim::download(&reclaim_path) - .expect("Unable to download RECLAIM proving context."); - MultiProvingContext { - mint: ProvingContext::decode(IoReader( - File::open(mint_path).expect("Unable to open MINT proving context file."), - )) - .expect("Unable to decode MINT proving context."), - private_transfer: ProvingContext::decode(IoReader( - File::open(private_transfer_path) - .expect("Unable to open PRIVATE_TRANSFER proving context file."), - )) - .expect("Unable to decode PRIVATE_TRANSFER proving context."), - reclaim: ProvingContext::decode(IoReader( - File::open(reclaim_path).expect("Unable to open RECLAIM proving context file."), - )) - .expect("Unable to decode RECLAIM proving context."), - } + let directory = tempfile::tempdir().expect("Unable to create temporary directory."); + let path = directory.path(); + let mint_path = path.join("mint.dat"); + manta_sdk::pay::testnet::proving::Mint::download(&mint_path) + .expect("Unable to download MINT proving context."); + let private_transfer_path = path.join("private-transfer.dat"); + manta_sdk::pay::testnet::proving::PrivateTransfer::download(&private_transfer_path) + .expect("Unable to download PRIVATE_TRANSFER proving context."); + let reclaim_path = path.join("reclaim.dat"); + manta_sdk::pay::testnet::proving::Reclaim::download(&reclaim_path) + .expect("Unable to download RECLAIM proving context."); + MultiProvingContext { + mint: ProvingContext::decode(IoReader( + File::open(mint_path).expect("Unable to open MINT proving context file."), + )) + .expect("Unable to decode MINT proving context."), + private_transfer: ProvingContext::decode(IoReader( + File::open(private_transfer_path) + .expect("Unable to open PRIVATE_TRANSFER proving context file."), + )) + .expect("Unable to decode PRIVATE_TRANSFER proving context."), + reclaim: ProvingContext::decode(IoReader( + File::open(reclaim_path).expect("Unable to open RECLAIM proving context file."), + )) + .expect("Unable to decode RECLAIM proving context."), + } } /// Loads the [`Parameters`] from the SDK. #[inline] fn load_parameters() -> Parameters { - Parameters { - note_encryption_scheme: NoteEncryptionScheme::decode( - manta_sdk::pay::testnet::parameters::NoteEncryptionScheme::get() - .expect("Checksum did not match."), - ) - .expect("Unable to decode NOTE_ENCRYPTION_SCHEME parameters."), - utxo_commitment: UtxoCommitmentScheme::decode( - manta_sdk::pay::testnet::parameters::UtxoCommitmentScheme::get() - .expect("Checksum did not match."), - ) - .expect("Unable to decode UTXO_COMMITMENT_SCHEME parameters."), - void_number_commitment: VoidNumberCommitmentScheme::decode( - manta_sdk::pay::testnet::parameters::VoidNumberCommitmentScheme::get() - .expect("Checksum did not match."), - ) - .expect("Unable to decode VOID_NUMBER_COMMITMENT_SCHEME parameters."), - } + Parameters { + note_encryption_scheme: NoteEncryptionScheme::decode( + manta_sdk::pay::testnet::parameters::NoteEncryptionScheme::get() + .expect("Checksum did not match."), + ) + .expect("Unable to decode NOTE_ENCRYPTION_SCHEME parameters."), + utxo_commitment: UtxoCommitmentScheme::decode( + manta_sdk::pay::testnet::parameters::UtxoCommitmentScheme::get() + .expect("Checksum did not match."), + ) + .expect("Unable to decode UTXO_COMMITMENT_SCHEME parameters."), + void_number_commitment: VoidNumberCommitmentScheme::decode( + manta_sdk::pay::testnet::parameters::VoidNumberCommitmentScheme::get() + .expect("Checksum did not match."), + ) + .expect("Unable to decode VOID_NUMBER_COMMITMENT_SCHEME parameters."), + } } /// Loads the [`UtxoAccumulatorModel`] from the SDK. #[inline] fn load_utxo_accumulator_model() -> UtxoAccumulatorModel { - UtxoAccumulatorModel::decode( - manta_sdk::pay::testnet::parameters::UtxoAccumulatorModel::get() - .expect("Checksum did not match."), - ) - .expect("Unable to decode UTXO_ACCUMULATOR_MODEL.") + UtxoAccumulatorModel::decode( + manta_sdk::pay::testnet::parameters::UtxoAccumulatorModel::get() + .expect("Checksum did not match."), + ) + .expect("Unable to decode UTXO_ACCUMULATOR_MODEL.") } /// Samples a [`Mint`] transaction of `asset` with a random secret. #[inline] fn sample_mint(asset: Asset, rng: &mut R) -> TransferPost where - R: CryptoRng + RngCore + ?Sized, + R: CryptoRng + RngCore + ?Sized, { - Mint::from_spending_key(&PARAMETERS, &rng.gen(), asset, rng) - .into_post( - FullParameters::new(&PARAMETERS, &UTXO_ACCUMULATOR_MODEL), - &PROVING_CONTEXT.mint, - rng, - ) - .expect("Unable to build MINT proof.") + Mint::from_spending_key(&PARAMETERS, &rng.gen(), asset, rng) + .into_post( + FullParameters::new(&PARAMETERS, &UTXO_ACCUMULATOR_MODEL), + &PROVING_CONTEXT.mint, + rng, + ) + .expect("Unable to build MINT proof.") } /// Mints many assets with the given `id` and `value`. #[inline] fn mint_tokens(id: AssetId, values: &[AssetValue], rng: &mut R) where - R: CryptoRng + RngCore + ?Sized, + R: CryptoRng + RngCore + ?Sized, { - for value in values { - assert_ok!(MantaPayPallet::to_private( - Origin::signed(ALICE), - sample_mint(value.with(id), rng).into() - )); - } + for value in values { + assert_ok!(MantaPayPallet::to_private( + Origin::signed(ALICE), + sample_mint(value.with(id), rng).into() + )); + } } /// Builds `count`-many [`PrivateTransfer`] tests. #[inline] fn private_transfer_test( - count: usize, - asset_id_option: Option, - rng: &mut R, + count: usize, + asset_id_option: Option, + rng: &mut R, ) -> Vec where - R: CryptoRng + RngCore + ?Sized, + R: CryptoRng + RngCore + ?Sized, { - let asset_id = match asset_id_option { - Some(id) => id, - None => rng.gen(), - }; - // FIXME: get rid of the division after parity fixes the pallet-asset bug - let double_balance: u128 = rng.gen(); - let total_free_balance = AssetValue(double_balance / 2); - let balances = value_distribution(count, total_free_balance, rng); - initialize_test(asset_id, total_free_balance + DEFAULT_ASSET_ED); - let mut utxo_accumulator = UtxoAccumulator::new(UTXO_ACCUMULATOR_MODEL.clone()); - let mut posts = Vec::new(); - for balance in balances { - let spending_key = SpendingKey::gen(rng); - let (mint_0, pre_sender_0) = transfer::test::sample_mint( - &PROVING_CONTEXT.mint, - FullParameters::new(&PARAMETERS, utxo_accumulator.model()), - &spending_key, - asset_id.with(balance), - rng, - ) - .unwrap(); - assert_ok!(MantaPayPallet::to_private( - Origin::signed(ALICE), - mint_0.into() - )); - let sender_0 = pre_sender_0 - .insert_and_upgrade(&mut utxo_accumulator) - .expect("Just inserted so this should not fail."); - let (mint_1, pre_sender_1) = transfer::test::sample_mint( - &PROVING_CONTEXT.mint, - FullParameters::new(&PARAMETERS, utxo_accumulator.model()), - &spending_key, - asset_id.value(0), - rng, - ) - .unwrap(); - assert_ok!(MantaPayPallet::to_private( - Origin::signed(ALICE), - mint_1.into() - )); - let sender_1 = pre_sender_1 - .insert_and_upgrade(&mut utxo_accumulator) - .expect("Just inserted so this should not fail."); - let (receiver_0, pre_sender_0) = - spending_key.internal_pair(&PARAMETERS, rng.gen(), asset_id.value(0)); - let (receiver_1, pre_sender_1) = - spending_key.internal_pair(&PARAMETERS, rng.gen(), asset_id.with(balance)); - let private_transfer = - PrivateTransfer::build([sender_0, sender_1], [receiver_0, receiver_1]) - .into_post( - FullParameters::new(&PARAMETERS, utxo_accumulator.model()), - &PROVING_CONTEXT.private_transfer, - rng, - ) - .unwrap(); - assert_ok!(MantaPayPallet::private_transfer( - Origin::signed(ALICE), - private_transfer.clone().into(), - )); - pre_sender_0.insert_utxo(&mut utxo_accumulator); - pre_sender_1.insert_utxo(&mut utxo_accumulator); - posts.push(private_transfer) - } - posts + let asset_id = match asset_id_option { + Some(id) => id, + None => rng.gen(), + }; + // FIXME: get rid of the division after parity fixes the pallet-asset bug + let double_balance: u128 = rng.gen(); + let total_free_balance = AssetValue(double_balance / 2); + let balances = value_distribution(count, total_free_balance, rng); + initialize_test(asset_id, total_free_balance + DEFAULT_ASSET_ED); + let mut utxo_accumulator = UtxoAccumulator::new(UTXO_ACCUMULATOR_MODEL.clone()); + let mut posts = Vec::new(); + for balance in balances { + let spending_key = SpendingKey::gen(rng); + let (mint_0, pre_sender_0) = transfer::test::sample_mint( + &PROVING_CONTEXT.mint, + FullParameters::new(&PARAMETERS, utxo_accumulator.model()), + &spending_key, + asset_id.with(balance), + rng, + ) + .unwrap(); + assert_ok!(MantaPayPallet::to_private( + Origin::signed(ALICE), + mint_0.into() + )); + let sender_0 = pre_sender_0 + .insert_and_upgrade(&mut utxo_accumulator) + .expect("Just inserted so this should not fail."); + let (mint_1, pre_sender_1) = transfer::test::sample_mint( + &PROVING_CONTEXT.mint, + FullParameters::new(&PARAMETERS, utxo_accumulator.model()), + &spending_key, + asset_id.value(0), + rng, + ) + .unwrap(); + assert_ok!(MantaPayPallet::to_private( + Origin::signed(ALICE), + mint_1.into() + )); + let sender_1 = pre_sender_1 + .insert_and_upgrade(&mut utxo_accumulator) + .expect("Just inserted so this should not fail."); + let (receiver_0, pre_sender_0) = + spending_key.internal_pair(&PARAMETERS, rng.gen(), asset_id.value(0)); + let (receiver_1, pre_sender_1) = + spending_key.internal_pair(&PARAMETERS, rng.gen(), asset_id.with(balance)); + let private_transfer = + PrivateTransfer::build([sender_0, sender_1], [receiver_0, receiver_1]) + .into_post( + FullParameters::new(&PARAMETERS, utxo_accumulator.model()), + &PROVING_CONTEXT.private_transfer, + rng, + ) + .unwrap(); + assert_ok!(MantaPayPallet::private_transfer( + Origin::signed(ALICE), + private_transfer.clone().into(), + )); + pre_sender_0.insert_utxo(&mut utxo_accumulator); + pre_sender_1.insert_utxo(&mut utxo_accumulator); + posts.push(private_transfer) + } + posts } /// Builds `count`-many [`Reclaim`] tests. #[inline] fn reclaim_test(count: usize, id_option: Option, rng: &mut R) -> Vec where - R: CryptoRng + RngCore + ?Sized, + R: CryptoRng + RngCore + ?Sized, { - let asset_id = match id_option { - Some(id) => id, - None => rng.gen(), - }; - // FIXME: This is a workaround due to the substrate asset bug - let double_balance: u128 = rng.gen(); - let total_free_balance = AssetValue(double_balance / 2); - let balances = value_distribution(count, total_free_balance, rng); - initialize_test(asset_id, total_free_balance + DEFAULT_ASSET_ED); - let mut utxo_accumulator = UtxoAccumulator::new(UTXO_ACCUMULATOR_MODEL.clone()); - let mut posts = Vec::new(); - for balance in balances { - let spending_key = SpendingKey::gen(rng); - let (mint_0, pre_sender_0) = transfer::test::sample_mint( - &PROVING_CONTEXT.mint, - FullParameters::new(&PARAMETERS, utxo_accumulator.model()), - &spending_key, - asset_id.with(balance), - rng, - ) - .unwrap(); - assert_ok!(MantaPayPallet::to_private( - Origin::signed(ALICE), - mint_0.into() - )); - let sender_0 = pre_sender_0 - .insert_and_upgrade(&mut utxo_accumulator) - .expect("Just inserted so this should not fail."); - let (mint_1, pre_sender_1) = transfer::test::sample_mint( - &PROVING_CONTEXT.mint, - FullParameters::new(&PARAMETERS, utxo_accumulator.model()), - &spending_key, - asset_id.value(0), - rng, - ) - .unwrap(); - assert_ok!(MantaPayPallet::to_private( - Origin::signed(ALICE), - mint_1.into() - )); - let sender_1 = pre_sender_1 - .insert_and_upgrade(&mut utxo_accumulator) - .expect("Just inserted so this should not fail."); - let (receiver, pre_sender) = - spending_key.internal_pair(&PARAMETERS, rng.gen(), asset_id.value(0)); - let reclaim = Reclaim::build([sender_0, sender_1], [receiver], asset_id.with(balance)) - .into_post( - FullParameters::new(&PARAMETERS, utxo_accumulator.model()), - &PROVING_CONTEXT.reclaim, - rng, - ) - .unwrap(); - assert_ok!(MantaPayPallet::to_public( - Origin::signed(ALICE), - reclaim.clone().into() - )); - pre_sender.insert_utxo(&mut utxo_accumulator); - posts.push(reclaim); - } - posts + let asset_id = match id_option { + Some(id) => id, + None => rng.gen(), + }; + // FIXME: This is a workaround due to the substrate asset bug + let double_balance: u128 = rng.gen(); + let total_free_balance = AssetValue(double_balance / 2); + let balances = value_distribution(count, total_free_balance, rng); + initialize_test(asset_id, total_free_balance + DEFAULT_ASSET_ED); + let mut utxo_accumulator = UtxoAccumulator::new(UTXO_ACCUMULATOR_MODEL.clone()); + let mut posts = Vec::new(); + for balance in balances { + let spending_key = SpendingKey::gen(rng); + let (mint_0, pre_sender_0) = transfer::test::sample_mint( + &PROVING_CONTEXT.mint, + FullParameters::new(&PARAMETERS, utxo_accumulator.model()), + &spending_key, + asset_id.with(balance), + rng, + ) + .unwrap(); + assert_ok!(MantaPayPallet::to_private( + Origin::signed(ALICE), + mint_0.into() + )); + let sender_0 = pre_sender_0 + .insert_and_upgrade(&mut utxo_accumulator) + .expect("Just inserted so this should not fail."); + let (mint_1, pre_sender_1) = transfer::test::sample_mint( + &PROVING_CONTEXT.mint, + FullParameters::new(&PARAMETERS, utxo_accumulator.model()), + &spending_key, + asset_id.value(0), + rng, + ) + .unwrap(); + assert_ok!(MantaPayPallet::to_private( + Origin::signed(ALICE), + mint_1.into() + )); + let sender_1 = pre_sender_1 + .insert_and_upgrade(&mut utxo_accumulator) + .expect("Just inserted so this should not fail."); + let (receiver, pre_sender) = + spending_key.internal_pair(&PARAMETERS, rng.gen(), asset_id.value(0)); + let reclaim = Reclaim::build([sender_0, sender_1], [receiver], asset_id.with(balance)) + .into_post( + FullParameters::new(&PARAMETERS, utxo_accumulator.model()), + &PROVING_CONTEXT.reclaim, + rng, + ) + .unwrap(); + assert_ok!(MantaPayPallet::to_public( + Origin::signed(ALICE), + reclaim.clone().into() + )); + pre_sender.insert_utxo(&mut utxo_accumulator); + posts.push(reclaim); + } + posts } /// Initializes a test by allocating `value`-many assets of the given `id` to the default account. #[inline] fn initialize_test(id: AssetId, value: AssetValue) { - let metadata = AssetRegistrarMetadata::default(); - assert_ok!(MantaAssetRegistrar::create_asset( - id.0, - DEFAULT_ASSET_ED, - metadata.into(), - true - )); - assert_ok!(FungibleLedger::::mint(id.0, &ALICE, value.0)); - assert_ok!(FungibleLedger::::mint( - id.0, - &MantaPayPallet::account_id(), - DEFAULT_ASSET_ED - )); + let metadata = AssetRegistrarMetadata::default(); + assert_ok!(MantaAssetRegistrar::create_asset( + id.0, + DEFAULT_ASSET_ED, + metadata.into(), + true + )); + assert_ok!(FungibleLedger::::mint(id.0, &ALICE, value.0)); + assert_ok!(FungibleLedger::::mint( + id.0, + &MantaPayPallet::account_id(), + DEFAULT_ASSET_ED + )); } /// Tests multiple to_private from some total supply. #[test] fn to_private_should_work() { - let mut rng = thread_rng(); - new_test_ext().execute_with(|| { - let asset_id = rng.gen(); - // FIXME: get rid of divide by two after parity fix pallet-asset - // This is to work around the substrate bug - let double_supply: u128 = rng.gen(); - let total_free_supply = AssetValue(double_supply / 2); - initialize_test(asset_id, total_free_supply + DEFAULT_ASSET_ED); - mint_tokens( - asset_id, - &value_distribution(5, total_free_supply, &mut rng), - &mut rng, - ); - }); + let mut rng = thread_rng(); + new_test_ext().execute_with(|| { + let asset_id = rng.gen(); + // FIXME: get rid of divide by two after parity fix pallet-asset + // This is to work around the substrate bug + let double_supply: u128 = rng.gen(); + let total_free_supply = AssetValue(double_supply / 2); + initialize_test(asset_id, total_free_supply + DEFAULT_ASSET_ED); + mint_tokens( + asset_id, + &value_distribution(5, total_free_supply, &mut rng), + &mut rng, + ); + }); } #[test] fn native_asset_to_private_should_work() { - let mut rng = thread_rng(); - new_test_ext().execute_with(|| { - // FIXME: get rid of divide by two after parity fix pallet-asset - // This is to work around the substrate bug - let double_supply: u128 = rng.gen(); - let total_free_supply = AssetValue(double_supply / 2); - initialize_test(NATIVE_ASSET_ID, total_free_supply + DEFAULT_ASSET_ED); - mint_tokens( - NATIVE_ASSET_ID, - &value_distribution(5, total_free_supply, &mut rng), - &mut rng, - ); - }); + let mut rng = thread_rng(); + new_test_ext().execute_with(|| { + // FIXME: get rid of divide by two after parity fix pallet-asset + // This is to work around the substrate bug + let double_supply: u128 = rng.gen(); + let total_free_supply = AssetValue(double_supply / 2); + initialize_test(NATIVE_ASSET_ID, total_free_supply + DEFAULT_ASSET_ED); + mint_tokens( + NATIVE_ASSET_ID, + &value_distribution(5, total_free_supply, &mut rng), + &mut rng, + ); + }); } /// Tests a mint that would overdraw the total supply. #[test] fn overdrawn_mint_should_not_work() { - let mut rng = thread_rng(); - new_test_ext().execute_with(|| { - let asset_id = rng.gen(); - // FIXME: remove the division after parity fix the pallet-asset bug - let double_supply: u128 = rng.gen(); - let total_supply = AssetValue(double_supply / 2) - .checked_sub(AssetValue(1)) - .unwrap_or_default(); - initialize_test(asset_id, total_supply + DEFAULT_ASSET_ED); - assert_noop!( - MantaPayPallet::to_private( - Origin::signed(ALICE), - sample_mint(asset_id.with(total_supply + 1), &mut rng).into() - ), - Error::::InvalidSourceAccount - ); - }); + let mut rng = thread_rng(); + new_test_ext().execute_with(|| { + let asset_id = rng.gen(); + // FIXME: remove the division after parity fix the pallet-asset bug + let double_supply: u128 = rng.gen(); + let total_supply = AssetValue(double_supply / 2) + .checked_sub(AssetValue(1)) + .unwrap_or_default(); + initialize_test(asset_id, total_supply + DEFAULT_ASSET_ED); + assert_noop!( + MantaPayPallet::to_private( + Origin::signed(ALICE), + sample_mint(asset_id.with(total_supply + 1), &mut rng).into() + ), + Error::::InvalidSourceAccount + ); + }); } /// Tests a mint that would overdraw from a non-existent supply. #[test] fn to_private_without_init_should_not_work() { - let mut rng = thread_rng(); - new_test_ext().execute_with(|| { - assert_noop!( - MantaPayPallet::to_private( - Origin::signed(ALICE), - sample_mint(rng.gen(), &mut rng).into() - ), - Error::::InvalidSourceAccount, - ); - }); + let mut rng = thread_rng(); + new_test_ext().execute_with(|| { + assert_noop!( + MantaPayPallet::to_private( + Origin::signed(ALICE), + sample_mint(rng.gen(), &mut rng).into() + ), + Error::::InvalidSourceAccount, + ); + }); } /// Tests that a double-spent [`Mint`] will fail. #[test] fn mint_existing_coin_should_not_work() { - let mut rng = thread_rng(); - new_test_ext().execute_with(|| { - let asset_id = rng.gen(); - initialize_test(asset_id, AssetValue(32579)); - let mint_post = sample_mint(asset_id.value(100), &mut rng); - assert_ok!(MantaPayPallet::to_private( - Origin::signed(ALICE), - mint_post.clone().into() - )); - assert_noop!( - MantaPayPallet::to_private(Origin::signed(ALICE), mint_post.into()), - Error::::AssetRegistered - ); - }); + let mut rng = thread_rng(); + new_test_ext().execute_with(|| { + let asset_id = rng.gen(); + initialize_test(asset_id, AssetValue(32579)); + let mint_post = sample_mint(asset_id.value(100), &mut rng); + assert_ok!(MantaPayPallet::to_private( + Origin::signed(ALICE), + mint_post.clone().into() + )); + assert_noop!( + MantaPayPallet::to_private(Origin::signed(ALICE), mint_post.into()), + Error::::AssetRegistered + ); + }); } /// Tests a [`PrivateTransfer`] transaction. #[test] fn private_transfer_should_work() { - new_test_ext().execute_with(|| private_transfer_test(1, None, &mut thread_rng())); + new_test_ext().execute_with(|| private_transfer_test(1, None, &mut thread_rng())); } /// Test a [`PrivateTransfer`] transaction with native currency #[test] fn private_transfer_native_asset_shoud_work() { - new_test_ext().execute_with(|| { - private_transfer_test(1, Some(NATIVE_ASSET_ID), &mut thread_rng()); - }); + new_test_ext().execute_with(|| { + private_transfer_test(1, Some(NATIVE_ASSET_ID), &mut thread_rng()); + }); } /// Tests multiple [`PrivateTransfer`] transactions. #[test] fn private_transfer_10_times_should_work() { - new_test_ext().execute_with(|| private_transfer_test(10, None, &mut thread_rng())); + new_test_ext().execute_with(|| private_transfer_test(10, None, &mut thread_rng())); } /// Tests that a double-spent [`PrivateTransfer`] will fail. #[test] fn double_spend_in_private_transfer_should_not_work() { - new_test_ext().execute_with(|| { - for private_transfer in private_transfer_test(1, None, &mut thread_rng()) { - assert_noop!( - MantaPayPallet::private_transfer(Origin::signed(ALICE), private_transfer.into()), - Error::::AssetSpent, - ); - } - }); + new_test_ext().execute_with(|| { + for private_transfer in private_transfer_test(1, None, &mut thread_rng()) { + assert_noop!( + MantaPayPallet::private_transfer(Origin::signed(ALICE), private_transfer.into()), + Error::::AssetSpent, + ); + } + }); } /// Tests a [`Reclaim`] transaction. #[test] fn reclaim_should_work() { - new_test_ext().execute_with(|| reclaim_test(1, None, &mut thread_rng())); + new_test_ext().execute_with(|| reclaim_test(1, None, &mut thread_rng())); } /// Test a [`Reclaim`] of native currency #[test] fn reclaim_native_should_work() { - new_test_ext().execute_with(|| reclaim_test(1, Some(NATIVE_ASSET_ID), &mut thread_rng())); + new_test_ext().execute_with(|| reclaim_test(1, Some(NATIVE_ASSET_ID), &mut thread_rng())); } /// Tests multiple [`Reclaim`] transactions. #[test] fn reclaim_10_times_should_work() { - new_test_ext().execute_with(|| reclaim_test(10, None, &mut thread_rng())); + new_test_ext().execute_with(|| reclaim_test(10, None, &mut thread_rng())); } /// Tests that a double-spent [`Reclaim`] will fail. #[test] fn double_spend_in_reclaim_should_not_work() { - new_test_ext().execute_with(|| { - for reclaim in reclaim_test(1, None, &mut thread_rng()) { - assert_noop!( - MantaPayPallet::to_public(Origin::signed(ALICE), reclaim.into()), - Error::::AssetSpent, - ); - } - }); + new_test_ext().execute_with(|| { + for reclaim in reclaim_test(1, None, &mut thread_rng()) { + assert_noop!( + MantaPayPallet::to_public(Origin::signed(ALICE), reclaim.into()), + Error::::AssetSpent, + ); + } + }); } diff --git a/pallets/manta-pay/src/test/storage.rs b/pallets/manta-pay/src/test/storage.rs index 1644c1c5f..105a3588e 100644 --- a/pallets/manta-pay/src/test/storage.rs +++ b/pallets/manta-pay/src/test/storage.rs @@ -1,21 +1,21 @@ -// Copyright 2019-2022 Manta Network. -// This file is part of pallet-manta-pay. +// Copyright 2020-2022 Manta Network. +// This file is part of Manta. // -// pallet-manta-pay is free software: you can redistribute it and/or modify +// Manta 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. // -// pallet-manta-pay is distributed in the hope that it will be useful, +// Manta 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 pallet-manta-pay. If not, see . +// along with Manta. If not, see . use frame_support::{ - pallet_prelude::ValueQuery, storage::types::StorageDoubleMap, traits::StorageInstance, Identity, + pallet_prelude::ValueQuery, storage::types::StorageDoubleMap, traits::StorageInstance, Identity, }; use sp_io::TestExternalities; @@ -23,12 +23,12 @@ use sp_io::TestExternalities; struct Prefix; impl StorageInstance for Prefix { - const STORAGE_PREFIX: &'static str = "foo"; + const STORAGE_PREFIX: &'static str = "foo"; - #[inline] - fn pallet_prefix() -> &'static str { - "test" - } + #[inline] + fn pallet_prefix() -> &'static str { + "test" + } } /// @@ -37,38 +37,38 @@ type DoubleMap = StorageDoubleMap>(), - vec![ - (0, 0, 0), - (0, 1, 1), - (0, 2, 2), - (0, 3, 3), - (1, 0, 0), - (1, 1, 1), - (1, 2, 2), - (1, 3, 3), - (1, 4, 4) - ] - ); - assert_eq!( - DoubleMap::iter_prefix(0_u16).collect::>(), - vec![(0, 0), (1, 1), (2, 2), (3, 3)] - ); - assert_eq!( - DoubleMap::iter_prefix_values(1_u16).collect::>(), - vec![0, 1, 2, 3, 4] - ); - assert_eq!( - DoubleMap::iter_prefix_from(1, DoubleMap::hashed_key_for(1, 2)).collect::>(), - vec![(3, 3), (4, 4)] - ); - }) + TestExternalities::default().execute_with(|| { + for i in 0..4 { + DoubleMap::insert(0_u16, i as u32, i as u64); + } + for i in 0..5 { + DoubleMap::insert(1_u16, i as u32, i as u64) + } + assert_eq!( + DoubleMap::iter().collect::>(), + vec![ + (0, 0, 0), + (0, 1, 1), + (0, 2, 2), + (0, 3, 3), + (1, 0, 0), + (1, 1, 1), + (1, 2, 2), + (1, 3, 3), + (1, 4, 4) + ] + ); + assert_eq!( + DoubleMap::iter_prefix(0_u16).collect::>(), + vec![(0, 0), (1, 1), (2, 2), (3, 3)] + ); + assert_eq!( + DoubleMap::iter_prefix_values(1_u16).collect::>(), + vec![0, 1, 2, 3, 4] + ); + assert_eq!( + DoubleMap::iter_prefix_from(1, DoubleMap::hashed_key_for(1, 2)).collect::>(), + vec![(3, 3), (4, 4)] + ); + }) } diff --git a/pallets/manta-pay/src/types.rs b/pallets/manta-pay/src/types.rs index f62f5bc36..a73ac3c91 100644 --- a/pallets/manta-pay/src/types.rs +++ b/pallets/manta-pay/src/types.rs @@ -1,18 +1,18 @@ -// Copyright 2019-2022 Manta Network. -// This file is part of pallet-manta-pay. +// Copyright 2020-2022 Manta Network. +// This file is part of Manta. // -// pallet-manta-pay is free software: you can redistribute it and/or modify +// Manta 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. // -// pallet-manta-pay is distributed in the hope that it will be useful, +// Manta 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 pallet-manta-pay. If not, see . +// along with Manta. If not, see . //! Type Definitions for Manta Pay @@ -34,9 +34,9 @@ pub(crate) const PROOF_LENGTH: usize = 192; #[inline] pub(crate) fn encode(value: T) -> [u8; N] where - T: Encode, + T: Encode, { - into_array_unchecked(value.encode()) + into_array_unchecked(value.encode()) } /// Decodes the `bytes` array of the given length `N` into the SCALE decodable type `T` returning a @@ -44,9 +44,9 @@ where #[inline] pub(crate) fn decode(bytes: [u8; N]) -> Result where - T: Decode, + T: Decode, { - T::decode(&mut bytes.as_slice()) + T::decode(&mut bytes.as_slice()) } /// Group Type @@ -69,211 +69,211 @@ pub type Proof = [u8; PROOF_LENGTH]; /// Asset #[derive( - Clone, - Copy, - Debug, - Decode, - Default, - Encode, - Eq, - Hash, - MaxEncodedLen, - Ord, - PartialEq, - PartialOrd, - TypeInfo, + Clone, + Copy, + Debug, + Decode, + Default, + Encode, + Eq, + Hash, + MaxEncodedLen, + Ord, + PartialEq, + PartialOrd, + TypeInfo, )] pub struct Asset { - /// Asset Id - pub id: AssetId, + /// Asset Id + pub id: AssetId, - /// Asset Value - pub value: Balance, + /// Asset Value + pub value: Balance, } impl Asset { - /// Builds a new [`Asset`] from `id` and `value`. - #[inline] - pub fn new(id: AssetId, value: Balance) -> Self { - Self { id, value } - } + /// Builds a new [`Asset`] from `id` and `value`. + #[inline] + pub fn new(id: AssetId, value: Balance) -> Self { + Self { id, value } + } } /// Encrypted Note #[cfg_attr( - feature = "rpc", - derive(Deserialize, Serialize), - serde(crate = "manta_util::serde", deny_unknown_fields) + feature = "rpc", + derive(Deserialize, Serialize), + serde(crate = "manta_util::serde", deny_unknown_fields) )] #[derive(Clone, Debug, Decode, Encode, Eq, Hash, MaxEncodedLen, PartialEq, TypeInfo)] pub struct EncryptedNote { - /// Ephemeral Public Key - pub ephemeral_public_key: Group, - - /// Ciphertext - #[cfg_attr( - feature = "rpc", - serde( - with = "manta_util::serde_with::As::<[manta_util::serde_with::Same; CIPHER_TEXT_LENGTH]>" - ) - )] - pub ciphertext: Ciphertext, + /// Ephemeral Public Key + pub ephemeral_public_key: Group, + + /// Ciphertext + #[cfg_attr( + feature = "rpc", + serde( + with = "manta_util::serde_with::As::<[manta_util::serde_with::Same; CIPHER_TEXT_LENGTH]>" + ) + )] + pub ciphertext: Ciphertext, } impl Default for EncryptedNote { - #[inline] - fn default() -> Self { - Self { - ephemeral_public_key: [0; EPHEMERAL_PUBLIC_KEY_LENGTH], - ciphertext: [0; CIPHER_TEXT_LENGTH], - } - } + #[inline] + fn default() -> Self { + Self { + ephemeral_public_key: [0; EPHEMERAL_PUBLIC_KEY_LENGTH], + ciphertext: [0; CIPHER_TEXT_LENGTH], + } + } } impl From for EncryptedNote { - #[inline] - fn from(encrypted_note: config::EncryptedNote) -> Self { - Self { - ephemeral_public_key: encode(encrypted_note.ephemeral_public_key), - ciphertext: encrypted_note.ciphertext.into(), - } - } + #[inline] + fn from(encrypted_note: config::EncryptedNote) -> Self { + Self { + ephemeral_public_key: encode(encrypted_note.ephemeral_public_key), + ciphertext: encrypted_note.ciphertext.into(), + } + } } impl TryFrom for config::EncryptedNote { - type Error = Error; - - #[inline] - fn try_from(encrypted_note: EncryptedNote) -> Result { - Ok(Self { - ephemeral_public_key: decode(encrypted_note.ephemeral_public_key)?, - ciphertext: encrypted_note.ciphertext.into(), - }) - } + type Error = Error; + + #[inline] + fn try_from(encrypted_note: EncryptedNote) -> Result { + Ok(Self { + ephemeral_public_key: decode(encrypted_note.ephemeral_public_key)?, + ciphertext: encrypted_note.ciphertext.into(), + }) + } } /// Sender Post #[derive(Clone, Debug, Decode, Encode, Eq, Hash, MaxEncodedLen, PartialEq, TypeInfo)] pub struct SenderPost { - /// UTXO Accumulator Output - pub utxo_accumulator_output: UtxoAccumulatorOutput, + /// UTXO Accumulator Output + pub utxo_accumulator_output: UtxoAccumulatorOutput, - /// Void Number - pub void_number: VoidNumber, + /// Void Number + pub void_number: VoidNumber, } impl From for SenderPost { - #[inline] - fn from(post: config::SenderPost) -> Self { - Self { - utxo_accumulator_output: encode(post.utxo_accumulator_output), - void_number: encode(post.void_number), - } - } + #[inline] + fn from(post: config::SenderPost) -> Self { + Self { + utxo_accumulator_output: encode(post.utxo_accumulator_output), + void_number: encode(post.void_number), + } + } } impl TryFrom for config::SenderPost { - type Error = Error; - - #[inline] - fn try_from(post: SenderPost) -> Result { - Ok(Self { - utxo_accumulator_output: decode(post.utxo_accumulator_output)?, - void_number: decode(post.void_number)?, - }) - } + type Error = Error; + + #[inline] + fn try_from(post: SenderPost) -> Result { + Ok(Self { + utxo_accumulator_output: decode(post.utxo_accumulator_output)?, + void_number: decode(post.void_number)?, + }) + } } /// Receiver Post #[derive(Clone, Debug, Decode, Encode, Eq, Hash, MaxEncodedLen, PartialEq, TypeInfo)] pub struct ReceiverPost { - /// Unspent Transaction Output - pub utxo: Utxo, + /// Unspent Transaction Output + pub utxo: Utxo, - /// Encrypted Note - pub encrypted_note: EncryptedNote, + /// Encrypted Note + pub encrypted_note: EncryptedNote, } impl From for ReceiverPost { - #[inline] - fn from(post: config::ReceiverPost) -> Self { - Self { - utxo: encode(post.utxo), - encrypted_note: post.encrypted_note.into(), - } - } + #[inline] + fn from(post: config::ReceiverPost) -> Self { + Self { + utxo: encode(post.utxo), + encrypted_note: post.encrypted_note.into(), + } + } } impl TryFrom for config::ReceiverPost { - type Error = Error; - - #[inline] - fn try_from(post: ReceiverPost) -> Result { - Ok(Self { - utxo: decode(post.utxo)?, - encrypted_note: post.encrypted_note.try_into()?, - }) - } + type Error = Error; + + #[inline] + fn try_from(post: ReceiverPost) -> Result { + Ok(Self { + utxo: decode(post.utxo)?, + encrypted_note: post.encrypted_note.try_into()?, + }) + } } /// Transfer Post #[derive(Clone, Debug, Decode, Encode, Eq, PartialEq, TypeInfo)] pub struct TransferPost { - /// Asset Id - pub asset_id: Option, + /// Asset Id + pub asset_id: Option, - /// Sources - pub sources: Vec, + /// Sources + pub sources: Vec, - /// Sender Posts - pub sender_posts: Vec, + /// Sender Posts + pub sender_posts: Vec, - /// Receiver Posts - pub receiver_posts: Vec, + /// Receiver Posts + pub receiver_posts: Vec, - /// Sinks - pub sinks: Vec, + /// Sinks + pub sinks: Vec, - /// Validity Proof - pub validity_proof: Proof, + /// Validity Proof + pub validity_proof: Proof, } impl From for TransferPost { - #[inline] - fn from(post: config::TransferPost) -> Self { - Self { - asset_id: post.asset_id.map(|id| id.0), - sources: post.sources.into_iter().map(|s| s.0).collect(), - sender_posts: post.sender_posts.into_iter().map(Into::into).collect(), - receiver_posts: post.receiver_posts.into_iter().map(Into::into).collect(), - sinks: post.sinks.into_iter().map(|s| s.0).collect(), - validity_proof: encode(post.validity_proof), - } - } + #[inline] + fn from(post: config::TransferPost) -> Self { + Self { + asset_id: post.asset_id.map(|id| id.0), + sources: post.sources.into_iter().map(|s| s.0).collect(), + sender_posts: post.sender_posts.into_iter().map(Into::into).collect(), + receiver_posts: post.receiver_posts.into_iter().map(Into::into).collect(), + sinks: post.sinks.into_iter().map(|s| s.0).collect(), + validity_proof: encode(post.validity_proof), + } + } } impl TryFrom for config::TransferPost { - type Error = Error; - - #[inline] - fn try_from(post: TransferPost) -> Result { - Ok(Self { - asset_id: post.asset_id.map(asset::AssetId), - sources: post.sources.into_iter().map(asset::AssetValue).collect(), - sender_posts: post - .sender_posts - .into_iter() - .map(TryInto::try_into) - .collect::>()?, - receiver_posts: post - .receiver_posts - .into_iter() - .map(TryInto::try_into) - .collect::>()?, - sinks: post.sinks.into_iter().map(asset::AssetValue).collect(), - validity_proof: decode(post.validity_proof)?, - }) - } + type Error = Error; + + #[inline] + fn try_from(post: TransferPost) -> Result { + Ok(Self { + asset_id: post.asset_id.map(asset::AssetId), + sources: post.sources.into_iter().map(asset::AssetValue).collect(), + sender_posts: post + .sender_posts + .into_iter() + .map(TryInto::try_into) + .collect::>()?, + receiver_posts: post + .receiver_posts + .into_iter() + .map(TryInto::try_into) + .collect::>()?, + sinks: post.sinks.into_iter().map(asset::AssetValue).collect(), + validity_proof: decode(post.validity_proof)?, + }) + } } /// Leaf Digest Type @@ -285,59 +285,59 @@ pub type InnerDigest = merkle_tree::InnerDigest /// Merkle Tree Current Path #[derive(Clone, Debug, Decode, Default, Encode, Eq, PartialEq, TypeInfo)] pub struct CurrentPath { - /// Sibling Digest - pub sibling_digest: LeafDigest, + /// Sibling Digest + pub sibling_digest: LeafDigest, - /// Leaf Index - pub leaf_index: u32, + /// Leaf Index + pub leaf_index: u32, - /// Inner Path - pub inner_path: Vec, + /// Inner Path + pub inner_path: Vec, } impl MaxEncodedLen for CurrentPath { - #[inline] - fn max_encoded_len() -> usize { - 0_usize - .saturating_add(LeafDigest::max_encoded_len()) - .saturating_add(u32::max_encoded_len()) - .saturating_add( - // NOTE: We know that these paths don't exceed the path length. - InnerDigest::max_encoded_len().saturating_mul( - manta_crypto::merkle_tree::path_length::(), - ), - ) - } + #[inline] + fn max_encoded_len() -> usize { + 0_usize + .saturating_add(LeafDigest::max_encoded_len()) + .saturating_add(u32::max_encoded_len()) + .saturating_add( + // NOTE: We know that these paths don't exceed the path length. + InnerDigest::max_encoded_len().saturating_mul( + manta_crypto::merkle_tree::path_length::(), + ), + ) + } } impl From> for CurrentPath { - #[inline] - fn from(path: merkle_tree::CurrentPath) -> Self { - Self { - sibling_digest: path.sibling_digest, - leaf_index: path.inner_path.leaf_index.0 as u32, - inner_path: path.inner_path.path, - } - } + #[inline] + fn from(path: merkle_tree::CurrentPath) -> Self { + Self { + sibling_digest: path.sibling_digest, + leaf_index: path.inner_path.leaf_index.0 as u32, + inner_path: path.inner_path.path, + } + } } impl From for merkle_tree::CurrentPath { - #[inline] - fn from(path: CurrentPath) -> Self { - Self::new( - path.sibling_digest, - (path.leaf_index as usize).into(), - path.inner_path, - ) - } + #[inline] + fn from(path: CurrentPath) -> Self { + Self::new( + path.sibling_digest, + (path.leaf_index as usize).into(), + path.inner_path, + ) + } } /// UTXO Merkle Tree Path #[derive(Clone, Debug, Decode, Default, Encode, Eq, MaxEncodedLen, PartialEq, TypeInfo)] pub struct UtxoMerkleTreePath { - /// Current Leaf Digest - pub leaf_digest: Option, + /// Current Leaf Digest + pub leaf_digest: Option, - /// Current Path - pub current_path: CurrentPath, + /// Current Path + pub current_path: CurrentPath, } diff --git a/pallets/manta-pay/src/weights.rs b/pallets/manta-pay/src/weights.rs index 7a4a9d8da..03b4b1304 100644 --- a/pallets/manta-pay/src/weights.rs +++ b/pallets/manta-pay/src/weights.rs @@ -1,18 +1,18 @@ -// Copyright 2019-2022 Manta Network. -// This file is part of pallet-manta-pay. +// Copyright 2020-2022 Manta Network. +// This file is part of Manta. // -// pallet-manta-pay is free software: you can redistribute it and/or modify +// Manta 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. // -// pallet-manta-pay is distributed in the hope that it will be useful, +// Manta 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 pallet-manta-pay. If not, see . +// along with Manta. If not, see . //! Autogenerated weights //! @@ -26,24 +26,24 @@ use core::marker::PhantomData; use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, + traits::Get, + weights::{constants::RocksDbWeight, Weight}, }; use frame_system::Config; /// Weight functions needed for pallet_manta_pay. pub trait WeightInfo { - /// Returns the [`Weight`] of the [`Pallet::to_private`] extrinsic. - fn to_private() -> Weight; + /// Returns the [`Weight`] of the [`Pallet::to_private`] extrinsic. + fn to_private() -> Weight; - /// Returns the [`Weight`] of the [`Pallet::to_public`] extrinsic. - fn to_public() -> Weight; + /// Returns the [`Weight`] of the [`Pallet::to_public`] extrinsic. + fn to_public() -> Weight; - /// Returns the [`Weight`] of the [`Pallet::private_transfer`] extrinsic. - fn private_transfer() -> Weight; + /// Returns the [`Weight`] of the [`Pallet::private_transfer`] extrinsic. + fn private_transfer() -> Weight; - /// Returns the [`Weight`] of the [`Pallet::public_transfer`] extrinsic. - fn public_transfer() -> Weight; + /// Returns the [`Weight`] of the [`Pallet::public_transfer`] extrinsic. + fn public_transfer() -> Weight; } /// Concrete Weight Functions @@ -51,54 +51,54 @@ pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight where - T: Config, + T: Config, { - /// ```text - /// Storage: MantaPay Balances (r:1 w:1) - /// Storage: MantaPay UtxoSet (r:1 w:1) - /// Storage: MantaPay ShardTrees (r:1 w:1) - /// Storage: MantaPay UtxoSetOutputs (r:0 w:1) - /// Storage: MantaPay Shards (r:0 w:1) - /// ``` - fn to_private() -> Weight { - (36_400_000_000 as Weight) - .saturating_add(T::DbWeight::get().reads(6 as Weight)) - .saturating_add(T::DbWeight::get().writes(7 as Weight)) - } + /// ```text + /// Storage: MantaPay Balances (r:1 w:1) + /// Storage: MantaPay UtxoSet (r:1 w:1) + /// Storage: MantaPay ShardTrees (r:1 w:1) + /// Storage: MantaPay UtxoSetOutputs (r:0 w:1) + /// Storage: MantaPay Shards (r:0 w:1) + /// ``` + fn to_private() -> Weight { + (36_400_000_000 as Weight) + .saturating_add(T::DbWeight::get().reads(6 as Weight)) + .saturating_add(T::DbWeight::get().writes(7 as Weight)) + } - /// ```text - /// Storage: MantaPay UtxoSetOutputs (r:2 w:1) - /// Storage: MantaPay VoidNumberSet (r:2 w:2) - /// Storage: MantaPay UtxoSet (r:1 w:1) - /// Storage: MantaPay VoidNumberSetSize (r:1 w:1) - /// Storage: MantaPay ShardTrees (r:1 w:1) - /// Storage: MantaPay Balances (r:1 w:1) - /// Storage: MantaPay VoidNumberSetInsertionOrder (r:0 w:2) - /// Storage: MantaPay Shards (r:0 w:1) - /// ``` - fn to_public() -> Weight { - (44_100_000_000 as Weight) - .saturating_add(T::DbWeight::get().reads(10 as Weight)) - .saturating_add(T::DbWeight::get().writes(12 as Weight)) - } + /// ```text + /// Storage: MantaPay UtxoSetOutputs (r:2 w:1) + /// Storage: MantaPay VoidNumberSet (r:2 w:2) + /// Storage: MantaPay UtxoSet (r:1 w:1) + /// Storage: MantaPay VoidNumberSetSize (r:1 w:1) + /// Storage: MantaPay ShardTrees (r:1 w:1) + /// Storage: MantaPay Balances (r:1 w:1) + /// Storage: MantaPay VoidNumberSetInsertionOrder (r:0 w:2) + /// Storage: MantaPay Shards (r:0 w:1) + /// ``` + fn to_public() -> Weight { + (44_100_000_000 as Weight) + .saturating_add(T::DbWeight::get().reads(10 as Weight)) + .saturating_add(T::DbWeight::get().writes(12 as Weight)) + } - /// ```text - /// Storage: MantaPay UtxoSetOutputs (r:2 w:2) - /// Storage: MantaPay VoidNumberSet (r:2 w:2) - /// Storage: MantaPay UtxoSet (r:2 w:2) - /// Storage: MantaPay VoidNumberSetSize (r:1 w:1) - /// Storage: MantaPay ShardTrees (r:2 w:2) - /// Storage: MantaPay VoidNumberSetInsertionOrder (r:0 w:2) - /// Storage: MantaPay Shards (r:0 w:2) - /// ``` - fn private_transfer() -> Weight { - (51_500_000_000 as Weight) - .saturating_add(T::DbWeight::get().reads(9 as Weight)) - .saturating_add(T::DbWeight::get().writes(13 as Weight)) - } + /// ```text + /// Storage: MantaPay UtxoSetOutputs (r:2 w:2) + /// Storage: MantaPay VoidNumberSet (r:2 w:2) + /// Storage: MantaPay UtxoSet (r:2 w:2) + /// Storage: MantaPay VoidNumberSetSize (r:1 w:1) + /// Storage: MantaPay ShardTrees (r:2 w:2) + /// Storage: MantaPay VoidNumberSetInsertionOrder (r:0 w:2) + /// Storage: MantaPay Shards (r:0 w:2) + /// ``` + fn private_transfer() -> Weight { + (51_500_000_000 as Weight) + .saturating_add(T::DbWeight::get().reads(9 as Weight)) + .saturating_add(T::DbWeight::get().writes(13 as Weight)) + } - /// FIXME: PLACEHOLDER WEIGHT - fn public_transfer() -> Weight { - (100_000_000_000 as Weight) - } + /// FIXME: PLACEHOLDER WEIGHT + fn public_transfer() -> Weight { + (100_000_000_000 as Weight) + } } diff --git a/pallets/tx-pause/Cargo.toml b/pallets/tx-pause/Cargo.toml index 1cfd6093f..4f1b6ac20 100644 --- a/pallets/tx-pause/Cargo.toml +++ b/pallets/tx-pause/Cargo.toml @@ -1,41 +1,41 @@ [package] -authors = ['Manta Network'] -name = "pallet-tx-pause" -version = '3.2.0' -edition = "2021" -homepage = 'https://manta.network' -license = 'GPL-3.0' +authors = ['Manta Network'] +edition = "2021" +homepage = 'https://manta.network' +license = 'GPL-3.0' +name = "pallet-tx-pause" repository = 'https://github.com/Manta-Network/Manta/' +version = '3.2.0' [dependencies] codec = { package = "parity-scale-codec", version = '3.0.0', default-features = false } -scale-info = { version = "2.0.0", default-features = false, features = ["derive"] } -sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18", default-features = false } +frame-benchmarking = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18", default-features = false, optional = true } frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18", default-features = false } frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18", default-features = false } +scale-info = { version = "2.0.0", default-features = false, features = ["derive"] } +sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18", default-features = false } sp-std = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18", default-features = false } -frame-benchmarking = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18", default-features = false, optional = true } [dev-dependencies] +manta-primitives = { path = '../../primitives' } +pallet-balances = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18" } sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18" } sp-io = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18" } -pallet-balances = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.18" } -manta-primitives = { path = '../../primitives' } [features] default = ["std"] +runtime-benchmarks = [ + "frame-benchmarking", + 'frame-support/runtime-benchmarks', + 'frame-system/runtime-benchmarks', +] std = [ - "scale-info/std", - "sp-runtime/std", - "frame-support/std", - "frame-system/std", - "sp-std/std", + "scale-info/std", + "sp-runtime/std", + "frame-support/std", + "frame-system/std", + "sp-std/std", ] try-runtime = [ - "frame-support/try-runtime", -] -runtime-benchmarks = [ - "frame-benchmarking", - 'frame-support/runtime-benchmarks', - 'frame-system/runtime-benchmarks', + "frame-support/try-runtime", ] diff --git a/pallets/tx-pause/src/benchmarking.rs b/pallets/tx-pause/src/benchmarking.rs index cc4b68eeb..c5ce657c0 100644 --- a/pallets/tx-pause/src/benchmarking.rs +++ b/pallets/tx-pause/src/benchmarking.rs @@ -27,40 +27,40 @@ use frame_benchmarking::{benchmarks, impl_benchmark_test_suite}; use frame_system::{EventRecord, RawOrigin}; pub fn assert_last_event(generic_event: ::Event) { - let events = frame_system::Pallet::::events(); - let system_event: ::Event = generic_event.into(); - let EventRecord { event, .. } = &events[events.len() - 1]; - assert_eq!(event, &system_event); + let events = frame_system::Pallet::::events(); + let system_event: ::Event = generic_event.into(); + let EventRecord { event, .. } = &events[events.len() - 1]; + assert_eq!(event, &system_event); } benchmarks! { - // Benchmark `pause_transaction` extrinsic: - pause_transaction { - let pallet_name = b"Balances".to_vec(); - let function_name = b"transfer".to_vec(); - }: pause_transaction(RawOrigin::Root, pallet_name.clone(), function_name.clone()) - verify { - assert_last_event::( - Event::TransactionPaused(pallet_name.clone(), function_name).into() - ); - } + // Benchmark `pause_transaction` extrinsic: + pause_transaction { + let pallet_name = b"Balances".to_vec(); + let function_name = b"transfer".to_vec(); + }: pause_transaction(RawOrigin::Root, pallet_name.clone(), function_name.clone()) + verify { + assert_last_event::( + Event::TransactionPaused(pallet_name.clone(), function_name).into() + ); + } - // Benchmark `unpause_transaction` extrinsic: - unpause_transaction { - let origin: T::Origin = T::Origin::from(RawOrigin::Root); - let pallet_name = b"Balances".to_vec(); - let function_name = b"transfer".to_vec(); - TransactionPause::::pause_transaction(origin, pallet_name.clone(), function_name.clone())?; - }: unpause_transaction(RawOrigin::Root, pallet_name.clone(), function_name.clone()) - verify { - assert_last_event::( - Event::TransactionUnpaused(pallet_name, function_name).into() - ); - } + // Benchmark `unpause_transaction` extrinsic: + unpause_transaction { + let origin: T::Origin = T::Origin::from(RawOrigin::Root); + let pallet_name = b"Balances".to_vec(); + let function_name = b"transfer".to_vec(); + TransactionPause::::pause_transaction(origin, pallet_name.clone(), function_name.clone())?; + }: unpause_transaction(RawOrigin::Root, pallet_name.clone(), function_name.clone()) + verify { + assert_last_event::( + Event::TransactionUnpaused(pallet_name, function_name).into() + ); + } } impl_benchmark_test_suite!( - TransactionPause, - crate::mock::ExtBuilder::default().build(), - crate::mock::Runtime, + TransactionPause, + crate::mock::ExtBuilder::default().build(), + crate::mock::Runtime, ); diff --git a/pallets/tx-pause/src/lib.rs b/pallets/tx-pause/src/lib.rs index 6de39d9c4..3c2d311c5 100644 --- a/pallets/tx-pause/src/lib.rs +++ b/pallets/tx-pause/src/lib.rs @@ -24,10 +24,10 @@ mod benchmarking; use frame_support::{ - dispatch::{CallMetadata, GetCallMetadata}, - pallet_prelude::*, - traits::{Contains, PalletInfoAccess}, - transactional, + dispatch::{CallMetadata, GetCallMetadata}, + pallet_prelude::*, + traits::{Contains, PalletInfoAccess}, + transactional, }; use frame_system::pallet_prelude::*; use sp_runtime::DispatchResult; @@ -42,112 +42,112 @@ pub use weights::WeightInfo; #[frame_support::pallet] pub mod pallet { - use super::*; - - #[pallet::config] - pub trait Config: frame_system::Config { - type Event: From> + IsType<::Event>; - - /// The origin which may set filter. - type UpdateOrigin: EnsureOrigin; - - /// Weight information for the extrinsics in this pallet. - type WeightInfo: WeightInfo; - } - - #[pallet::error] - pub enum Error { - /// can not pause - CannotPause, - /// invalid character encoding - InvalidCharacter, - } - - #[pallet::event] - #[pallet::generate_deposit(fn deposit_event)] - pub enum Event { - /// Paused transaction . \[pallet_name_bytes, function_name_bytes\] - TransactionPaused(Vec, Vec), - /// Unpaused transaction . \[pallet_name_bytes, function_name_bytes\] - TransactionUnpaused(Vec, Vec), - } - - /// The paused transaction map - /// - /// map (PalletNameBytes, FunctionNameBytes) => Option<()> - #[pallet::storage] - #[pallet::getter(fn paused_transactions)] - pub type PausedTransactions = - StorageMap<_, Twox64Concat, (Vec, Vec), (), OptionQuery>; - - #[pallet::pallet] - #[pallet::without_storage_info] - pub struct Pallet(_); - - #[pallet::hooks] - impl Hooks for Pallet {} - - #[pallet::call] - impl Pallet { - /// Pause an extrinsic by passing the extrinsic and corresponding pallet names. - /// Use names as they are written in the source code of the pallet. - #[pallet::weight(T::WeightInfo::pause_transaction())] - #[transactional] - pub fn pause_transaction( - origin: OriginFor, - pallet_name: Vec, - function_name: Vec, - ) -> DispatchResult { - T::UpdateOrigin::ensure_origin(origin)?; - - // not allowed to pause calls of this pallet to ensure safe - let pallet_name_string = - sp_std::str::from_utf8(&pallet_name).map_err(|_| Error::::InvalidCharacter)?; - ensure!( - pallet_name_string != ::name(), - Error::::CannotPause - ); - - PausedTransactions::::mutate_exists( - (pallet_name.clone(), function_name.clone()), - |maybe_paused| { - if maybe_paused.is_none() { - *maybe_paused = Some(()); - Self::deposit_event(Event::TransactionPaused(pallet_name, function_name)); - } - }, - ); - Ok(()) - } - - /// Unpause an extrinsic by passing the extrinsic and corresponding pallet names. - /// Use names as they are written in the source code of the pallet. - #[pallet::weight(T::WeightInfo::unpause_transaction())] - #[transactional] - pub fn unpause_transaction( - origin: OriginFor, - pallet_name: Vec, - function_name: Vec, - ) -> DispatchResult { - T::UpdateOrigin::ensure_origin(origin)?; - if PausedTransactions::::take((&pallet_name, &function_name)).is_some() { - Self::deposit_event(Event::TransactionUnpaused(pallet_name, function_name)); - }; - Ok(()) - } - } + use super::*; + + #[pallet::config] + pub trait Config: frame_system::Config { + type Event: From> + IsType<::Event>; + + /// The origin which may set filter. + type UpdateOrigin: EnsureOrigin; + + /// Weight information for the extrinsics in this pallet. + type WeightInfo: WeightInfo; + } + + #[pallet::error] + pub enum Error { + /// can not pause + CannotPause, + /// invalid character encoding + InvalidCharacter, + } + + #[pallet::event] + #[pallet::generate_deposit(fn deposit_event)] + pub enum Event { + /// Paused transaction . \[pallet_name_bytes, function_name_bytes\] + TransactionPaused(Vec, Vec), + /// Unpaused transaction . \[pallet_name_bytes, function_name_bytes\] + TransactionUnpaused(Vec, Vec), + } + + /// The paused transaction map + /// + /// map (PalletNameBytes, FunctionNameBytes) => Option<()> + #[pallet::storage] + #[pallet::getter(fn paused_transactions)] + pub type PausedTransactions = + StorageMap<_, Twox64Concat, (Vec, Vec), (), OptionQuery>; + + #[pallet::pallet] + #[pallet::without_storage_info] + pub struct Pallet(_); + + #[pallet::hooks] + impl Hooks for Pallet {} + + #[pallet::call] + impl Pallet { + /// Pause an extrinsic by passing the extrinsic and corresponding pallet names. + /// Use names as they are written in the source code of the pallet. + #[pallet::weight(T::WeightInfo::pause_transaction())] + #[transactional] + pub fn pause_transaction( + origin: OriginFor, + pallet_name: Vec, + function_name: Vec, + ) -> DispatchResult { + T::UpdateOrigin::ensure_origin(origin)?; + + // not allowed to pause calls of this pallet to ensure safe + let pallet_name_string = + sp_std::str::from_utf8(&pallet_name).map_err(|_| Error::::InvalidCharacter)?; + ensure!( + pallet_name_string != ::name(), + Error::::CannotPause + ); + + PausedTransactions::::mutate_exists( + (pallet_name.clone(), function_name.clone()), + |maybe_paused| { + if maybe_paused.is_none() { + *maybe_paused = Some(()); + Self::deposit_event(Event::TransactionPaused(pallet_name, function_name)); + } + }, + ); + Ok(()) + } + + /// Unpause an extrinsic by passing the extrinsic and corresponding pallet names. + /// Use names as they are written in the source code of the pallet. + #[pallet::weight(T::WeightInfo::unpause_transaction())] + #[transactional] + pub fn unpause_transaction( + origin: OriginFor, + pallet_name: Vec, + function_name: Vec, + ) -> DispatchResult { + T::UpdateOrigin::ensure_origin(origin)?; + if PausedTransactions::::take((&pallet_name, &function_name)).is_some() { + Self::deposit_event(Event::TransactionUnpaused(pallet_name, function_name)); + }; + Ok(()) + } + } } pub struct PausedTransactionFilter(sp_std::marker::PhantomData); impl Contains for PausedTransactionFilter where - ::Call: GetCallMetadata, + ::Call: GetCallMetadata, { - fn contains(call: &T::Call) -> bool { - let CallMetadata { - function_name, - pallet_name, - } = call.get_call_metadata(); - PausedTransactions::::contains_key((pallet_name.as_bytes(), function_name.as_bytes())) - } + fn contains(call: &T::Call) -> bool { + let CallMetadata { + function_name, + pallet_name, + } = call.get_call_metadata(); + PausedTransactions::::contains_key((pallet_name.as_bytes(), function_name.as_bytes())) + } } diff --git a/pallets/tx-pause/src/mock.rs b/pallets/tx-pause/src/mock.rs index 87cd400b2..31570e9b5 100644 --- a/pallets/tx-pause/src/mock.rs +++ b/pallets/tx-pause/src/mock.rs @@ -23,8 +23,8 @@ use super::*; use frame_support::{ - construct_runtime, ord_parameter_types, parameter_types, - traits::{ConstU32, ConstU64}, + construct_runtime, ord_parameter_types, parameter_types, + traits::{ConstU32, ConstU64}, }; use frame_system::EnsureRoot; use manta_primitives::types::Balance; @@ -36,104 +36,99 @@ pub type AccountId = u128; pub const ALICE: AccountId = 1; mod tx_pause { - pub use super::super::*; + pub use super::super::*; } // Don't allow permission-less asset creation. pub struct BaseFilter; impl Contains for BaseFilter { - fn contains(call: &Call) -> bool { - if tx_pause::PausedTransactionFilter::::contains(call) { - // no paused call - return false; - } - - return true; - } + fn contains(call: &Call) -> bool { + !tx_pause::PausedTransactionFilter::::contains(call) // filter paused calls + } } impl frame_system::Config for Runtime { - type Origin = Origin; - type Index = u64; - type BlockNumber = u64; - type Call = Call; - type Hash = H256; - type Hashing = ::sp_runtime::traits::BlakeTwo256; - type AccountId = AccountId; - type Lookup = IdentityLookup; - type Header = Header; - type Event = Event; - type BlockHashCount = ConstU64<250>; - type BlockWeights = (); - type BlockLength = (); - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); - type DbWeight = (); - type BaseCallFilter = BaseFilter; - type SystemWeightInfo = (); - type SS58Prefix = (); - type OnSetCode = (); - type MaxConsumers = frame_support::traits::ConstU32<16>; + type Origin = Origin; + type Index = u64; + type BlockNumber = u64; + type Call = Call; + type Hash = H256; + type Hashing = ::sp_runtime::traits::BlakeTwo256; + type AccountId = AccountId; + type Lookup = IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = ConstU64<250>; + type BlockWeights = (); + type BlockLength = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type DbWeight = (); + type BaseCallFilter = BaseFilter; + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; } parameter_types! { - pub const NativeTokenExistentialDeposit: Balance = 10; + pub const NativeTokenExistentialDeposit: Balance = 10; } impl pallet_balances::Config for Runtime { - type Balance = Balance; - type DustRemoval = (); - type Event = Event; - type ExistentialDeposit = NativeTokenExistentialDeposit; - type AccountStore = System; - type MaxLocks = (); - type MaxReserves = ConstU32<50>; - type ReserveIdentifier = (); - type WeightInfo = (); + type Balance = Balance; + type DustRemoval = (); + type Event = Event; + type ExistentialDeposit = NativeTokenExistentialDeposit; + type AccountStore = System; + type MaxLocks = (); + type MaxReserves = ConstU32<50>; + type ReserveIdentifier = (); + type WeightInfo = (); } ord_parameter_types! { - pub const One: AccountId = 1; + pub const One: AccountId = 1; } impl Config for Runtime { - type Event = Event; - type UpdateOrigin = EnsureRoot; - type WeightInfo = (); + type Event = Event; + type UpdateOrigin = EnsureRoot; + type WeightInfo = (); } type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic - { - System: frame_system::{Pallet, Call, Config, Storage, Event}, - TransactionPause: tx_pause::{Pallet, Storage, Call, Event}, - Balances: pallet_balances::{Pallet, Storage, Call, Event}, - } + pub enum Runtime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic + { + System: frame_system::{Pallet, Call, Config, Storage, Event}, + TransactionPause: tx_pause::{Pallet, Storage, Call, Event}, + Balances: pallet_balances::{Pallet, Storage, Call, Event}, + } ); pub struct ExtBuilder; impl Default for ExtBuilder { - fn default() -> Self { - ExtBuilder - } + fn default() -> Self { + ExtBuilder + } } impl ExtBuilder { - pub fn build(self) -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); + pub fn build(self) -> sp_io::TestExternalities { + let t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); - t.into() - } + t.into() + } } diff --git a/pallets/tx-pause/src/tests.rs b/pallets/tx-pause/src/tests.rs index 70fea3f62..593c16520 100644 --- a/pallets/tx-pause/src/tests.rs +++ b/pallets/tx-pause/src/tests.rs @@ -28,142 +28,142 @@ use mock::{Event, *}; use sp_runtime::traits::BadOrigin; const BALANCE_TRANSFER: &::Call = - &mock::Call::Balances(pallet_balances::Call::transfer { - dest: ALICE, - value: 10, - }); + &mock::Call::Balances(pallet_balances::Call::transfer { + dest: ALICE, + value: 10, + }); #[test] fn pause_transaction_work() { - ExtBuilder::default().build().execute_with(|| { - assert!(::BaseCallFilter::contains( - BALANCE_TRANSFER - )); - - System::set_block_number(1); - assert_noop!( - TransactionPause::pause_transaction( - Origin::signed(1), - b"Balances".to_vec(), - b"transfer".to_vec() - ), - BadOrigin - ); - - assert_eq!( - TransactionPause::paused_transactions((b"Balances".to_vec(), b"transfer".to_vec())), - None - ); - assert_ok!(TransactionPause::pause_transaction( - RawOrigin::Root.into(), - b"Balances".to_vec(), - b"transfer".to_vec() - )); - System::assert_last_event(Event::TransactionPause(crate::Event::TransactionPaused( - b"Balances".to_vec(), - b"transfer".to_vec(), - ))); - assert_eq!( - TransactionPause::paused_transactions((b"Balances".to_vec(), b"transfer".to_vec())), - Some(()) - ); - assert!(!::BaseCallFilter::contains(BALANCE_TRANSFER)); - - assert_noop!( - TransactionPause::pause_transaction( - RawOrigin::Root.into(), - b"TransactionPause".to_vec(), - b"pause_transaction".to_vec() - ), - Error::::CannotPause - ); - assert_noop!( - TransactionPause::pause_transaction( - RawOrigin::Root.into(), - b"TransactionPause".to_vec(), - b"some_other_call".to_vec() - ), - Error::::CannotPause - ); - assert_ok!(TransactionPause::pause_transaction( - RawOrigin::Root.into(), - b"OtherPallet".to_vec(), - b"pause_transaction".to_vec() - )); - }); + ExtBuilder::default().build().execute_with(|| { + assert!(::BaseCallFilter::contains( + BALANCE_TRANSFER + )); + + System::set_block_number(1); + assert_noop!( + TransactionPause::pause_transaction( + Origin::signed(1), + b"Balances".to_vec(), + b"transfer".to_vec() + ), + BadOrigin + ); + + assert_eq!( + TransactionPause::paused_transactions((b"Balances".to_vec(), b"transfer".to_vec())), + None + ); + assert_ok!(TransactionPause::pause_transaction( + RawOrigin::Root.into(), + b"Balances".to_vec(), + b"transfer".to_vec() + )); + System::assert_last_event(Event::TransactionPause(crate::Event::TransactionPaused( + b"Balances".to_vec(), + b"transfer".to_vec(), + ))); + assert_eq!( + TransactionPause::paused_transactions((b"Balances".to_vec(), b"transfer".to_vec())), + Some(()) + ); + assert!(!::BaseCallFilter::contains(BALANCE_TRANSFER)); + + assert_noop!( + TransactionPause::pause_transaction( + RawOrigin::Root.into(), + b"TransactionPause".to_vec(), + b"pause_transaction".to_vec() + ), + Error::::CannotPause + ); + assert_noop!( + TransactionPause::pause_transaction( + RawOrigin::Root.into(), + b"TransactionPause".to_vec(), + b"some_other_call".to_vec() + ), + Error::::CannotPause + ); + assert_ok!(TransactionPause::pause_transaction( + RawOrigin::Root.into(), + b"OtherPallet".to_vec(), + b"pause_transaction".to_vec() + )); + }); } #[test] fn unpause_transaction_work() { - ExtBuilder::default().build().execute_with(|| { - assert!(::BaseCallFilter::contains( - BALANCE_TRANSFER - )); - - System::set_block_number(1); - - assert_ok!(TransactionPause::pause_transaction( - RawOrigin::Root.into(), - b"Balances".to_vec(), - b"transfer".to_vec() - )); - assert_eq!( - TransactionPause::paused_transactions((b"Balances".to_vec(), b"transfer".to_vec())), - Some(()) - ); - - assert!(!::BaseCallFilter::contains(BALANCE_TRANSFER)); - - assert_noop!( - TransactionPause::unpause_transaction( - Origin::signed(1), - b"Balances".to_vec(), - b"transfer".to_vec() - ), - BadOrigin - ); - - assert_ok!(TransactionPause::unpause_transaction( - RawOrigin::Root.into(), - b"Balances".to_vec(), - b"transfer".to_vec() - )); - System::assert_last_event(Event::TransactionPause(crate::Event::TransactionUnpaused( - b"Balances".to_vec(), - b"transfer".to_vec(), - ))); - assert_eq!( - TransactionPause::paused_transactions((b"Balances".to_vec(), b"transfer".to_vec())), - None - ); - - assert!(::BaseCallFilter::contains( - BALANCE_TRANSFER - )); - }); + ExtBuilder::default().build().execute_with(|| { + assert!(::BaseCallFilter::contains( + BALANCE_TRANSFER + )); + + System::set_block_number(1); + + assert_ok!(TransactionPause::pause_transaction( + RawOrigin::Root.into(), + b"Balances".to_vec(), + b"transfer".to_vec() + )); + assert_eq!( + TransactionPause::paused_transactions((b"Balances".to_vec(), b"transfer".to_vec())), + Some(()) + ); + + assert!(!::BaseCallFilter::contains(BALANCE_TRANSFER)); + + assert_noop!( + TransactionPause::unpause_transaction( + Origin::signed(1), + b"Balances".to_vec(), + b"transfer".to_vec() + ), + BadOrigin + ); + + assert_ok!(TransactionPause::unpause_transaction( + RawOrigin::Root.into(), + b"Balances".to_vec(), + b"transfer".to_vec() + )); + System::assert_last_event(Event::TransactionPause(crate::Event::TransactionUnpaused( + b"Balances".to_vec(), + b"transfer".to_vec(), + ))); + assert_eq!( + TransactionPause::paused_transactions((b"Balances".to_vec(), b"transfer".to_vec())), + None + ); + + assert!(::BaseCallFilter::contains( + BALANCE_TRANSFER + )); + }); } #[test] fn paused_transaction_filter_work() { - ExtBuilder::default().build().execute_with(|| { - assert!(!PausedTransactionFilter::::contains( - BALANCE_TRANSFER - )); - assert_ok!(TransactionPause::pause_transaction( - RawOrigin::Root.into(), - b"Balances".to_vec(), - b"transfer".to_vec() - )); - assert!(PausedTransactionFilter::::contains( - BALANCE_TRANSFER - )); - assert_ok!(TransactionPause::unpause_transaction( - RawOrigin::Root.into(), - b"Balances".to_vec(), - b"transfer".to_vec() - )); - assert!(!PausedTransactionFilter::::contains( - BALANCE_TRANSFER - )); - }); + ExtBuilder::default().build().execute_with(|| { + assert!(!PausedTransactionFilter::::contains( + BALANCE_TRANSFER + )); + assert_ok!(TransactionPause::pause_transaction( + RawOrigin::Root.into(), + b"Balances".to_vec(), + b"transfer".to_vec() + )); + assert!(PausedTransactionFilter::::contains( + BALANCE_TRANSFER + )); + assert_ok!(TransactionPause::unpause_transaction( + RawOrigin::Root.into(), + b"Balances".to_vec(), + b"transfer".to_vec() + )); + assert!(!PausedTransactionFilter::::contains( + BALANCE_TRANSFER + )); + }); } diff --git a/pallets/tx-pause/src/weights.rs b/pallets/tx-pause/src/weights.rs index ccb6c481d..72de0befc 100644 --- a/pallets/tx-pause/src/weights.rs +++ b/pallets/tx-pause/src/weights.rs @@ -44,39 +44,39 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_tx_pause. pub trait WeightInfo { - fn pause_transaction() -> Weight; - fn unpause_transaction() -> Weight; + fn pause_transaction() -> Weight; + fn unpause_transaction() -> Weight; } /// Weights for pallet_tx_pause using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { - // Storage: TransactionPause PausedTransactions (r:1 w:1) - fn pause_transaction() -> Weight { - (42_000_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: TransactionPause PausedTransactions (r:1 w:1) - fn unpause_transaction() -> Weight { - (42_450_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } + // Storage: TransactionPause PausedTransactions (r:1 w:1) + fn pause_transaction() -> Weight { + (42_000_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: TransactionPause PausedTransactions (r:1 w:1) + fn unpause_transaction() -> Weight { + (42_450_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: TransactionPause PausedTransactions (r:1 w:1) - fn pause_transaction() -> Weight { - (42_000_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: TransactionPause PausedTransactions (r:1 w:1) - fn unpause_transaction() -> Weight { - (42_450_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } + // Storage: TransactionPause PausedTransactions (r:1 w:1) + fn pause_transaction() -> Weight { + (42_000_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: TransactionPause PausedTransactions (r:1 w:1) + fn unpause_transaction() -> Weight { + (42_450_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } } diff --git a/pallets/vesting/Cargo.toml b/pallets/vesting/Cargo.toml index 29b9dac60..0233aeb1f 100644 --- a/pallets/vesting/Cargo.toml +++ b/pallets/vesting/Cargo.toml @@ -1,45 +1,45 @@ [package] -authors = ['Manta Network'] -name = "calamari-vesting" -version = '3.2.0' -edition = "2021" -homepage = 'https://manta.network' -license = 'GPL-3.0' +authors = ['Manta Network'] +edition = "2021" +homepage = 'https://manta.network' +license = 'GPL-3.0' +name = "calamari-vesting" repository = 'https://github.com/Manta-Network/Manta/' +version = '3.2.0' [dependencies] -codec = { package = "parity-scale-codec", version = '3.0.0', default-features = false, features = ["derive", "max-encoded-len"] } -scale-info = { version = "2.0.0", default-features = false, features = ["derive"] } +codec = { package = "parity-scale-codec", version = '3.0.0', default-features = false, features = ["derive", "max-encoded-len"] } +scale-info = { version = "2.0.0", default-features = false, features = ["derive"] } frame-benchmarking = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18", optional = true } -pallet-timestamp = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18", optional = true } -pallet-balances = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18", optional = true } -frame-support = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } -frame-system = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } -sp-runtime = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } -sp-std = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } +frame-support = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } +frame-system = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } +pallet-balances = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18", optional = true } +pallet-timestamp = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18", optional = true } +sp-runtime = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } +sp-std = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } [dev-dependencies] -chrono = "0.4" -pallet-balances = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } -pallet-timestamp = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } -sp-core = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } -sp-io = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } +chrono = "0.4" +pallet-balances = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } +pallet-timestamp = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } +sp-core = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } +sp-io = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } [features] -default = ["std"] -std = [ - "codec/std", - "frame-support/std", - "frame-system/std", - "scale-info/std", - "sp-runtime/std", - "sp-std/std", -] +default = ["std"] runtime-benchmarks = [ - "frame-benchmarking", - 'frame-support/runtime-benchmarks', - 'frame-system/runtime-benchmarks', - "pallet-timestamp/runtime-benchmarks", - "pallet-balances/runtime-benchmarks", + "frame-benchmarking", + 'frame-support/runtime-benchmarks', + 'frame-system/runtime-benchmarks', + "pallet-timestamp/runtime-benchmarks", + "pallet-balances/runtime-benchmarks", +] +std = [ + "codec/std", + "frame-support/std", + "frame-system/std", + "scale-info/std", + "sp-runtime/std", + "sp-std/std", ] diff --git a/pallets/vesting/src/benchmarking.rs b/pallets/vesting/src/benchmarking.rs index 90d941750..01e520833 100644 --- a/pallets/vesting/src/benchmarking.rs +++ b/pallets/vesting/src/benchmarking.rs @@ -31,111 +31,111 @@ const SEED: u32 = 0; const ED_MULTIPLIER: u32 = 100; fn assert_has_event(generic_event: ::Event) { - frame_system::Pallet::::assert_has_event(generic_event.into()); + frame_system::Pallet::::assert_has_event(generic_event.into()); } fn init_setup< - T: Config + pallet_timestamp::Config + pallet_balances::Config, - I: 'static, + T: Config + pallet_timestamp::Config + pallet_balances::Config, + I: 'static, >( - caller: &T::AccountId, + caller: &T::AccountId, ) where - ::Balance: TryFrom, - T: pallet_balances::Config, + ::Balance: TryFrom, + T: pallet_balances::Config, { - let now = Duration::from_secs(1636329600 - 1) - .as_millis() - .saturated_into::() - + 1; - pallet_timestamp::Pallet::::set_timestamp(now); - let existential_deposit = >::ExistentialDeposit::get(); - let amount = existential_deposit.saturating_mul(ED_MULTIPLIER.into()); - let source_caller = T::Lookup::unlookup(caller.clone()); - let _ = pallet_balances::Pallet::::make_free_balance_be(caller, amount); - assert_ok!(pallet_balances::Pallet::::set_balance( - RawOrigin::Root.into(), - source_caller, - amount, - amount - )); - assert_eq!( - pallet_balances::Pallet::::free_balance(caller), - amount - ); + let now = Duration::from_secs(1636329600 - 1) + .as_millis() + .saturated_into::() + + 1; + pallet_timestamp::Pallet::::set_timestamp(now); + let existential_deposit = >::ExistentialDeposit::get(); + let amount = existential_deposit.saturating_mul(ED_MULTIPLIER.into()); + let source_caller = T::Lookup::unlookup(caller.clone()); + let _ = pallet_balances::Pallet::::make_free_balance_be(caller, amount); + assert_ok!(pallet_balances::Pallet::::set_balance( + RawOrigin::Root.into(), + source_caller, + amount, + amount + )); + assert_eq!( + pallet_balances::Pallet::::free_balance(caller), + amount + ); } benchmarks! { - where_clause { - where - T: Config + pallet_timestamp::Config + pallet_balances::Config, - BalanceOf: AtLeast32BitUnsigned, - ::Balance: From, - } + where_clause { + where + T: Config + pallet_timestamp::Config + pallet_balances::Config, + BalanceOf: AtLeast32BitUnsigned, + ::Balance: From, + } - update_vesting_schedule { - let new_schedule = BoundedVec::try_from( - crate::Pallet::::vesting_schedule() - .iter() - .map(|(_, s)| s + 1) - .collect::>(), - ) - .unwrap_or_default(); - }: _(RawOrigin::Root, new_schedule.clone()) - verify { - assert_has_event::(Event::VestingScheduleUpdated(new_schedule).into()); - } + update_vesting_schedule { + let new_schedule = BoundedVec::try_from( + crate::Pallet::::vesting_schedule() + .iter() + .map(|(_, s)| s + 1) + .collect::>(), + ) + .unwrap_or_default(); + }: _(RawOrigin::Root, new_schedule.clone()) + verify { + assert_has_event::(Event::VestingScheduleUpdated(new_schedule).into()); + } - vest { - let caller: T::AccountId = whitelisted_caller(); - let recipient: T::AccountId = account("receiver", 0, SEED); - let source_recipient = T::Lookup::unlookup(recipient.clone()); - init_setup::(&caller); - let existential_deposit = >::ExistentialDeposit::get(); - let unvested = existential_deposit - .saturating_mul(ED_MULTIPLIER.div(10u32).into()) - .saturated_into::() - .try_into() - .ok() - .unwrap(); - assert_ok!( - crate::Pallet::::vested_transfer( - RawOrigin::Signed(caller).into(), source_recipient, unvested - ) - ); - assert!(crate::Pallet::::vesting_balance(&recipient).is_some()); - let now = Duration::from_secs(1660694400) - .as_millis() - .saturated_into::() - + 1; - pallet_timestamp::Pallet::::set_timestamp(now); - }: _(RawOrigin::Signed(recipient.clone())) - verify { - assert_has_event::(Event::VestingCompleted(recipient).into()); - } + vest { + let caller: T::AccountId = whitelisted_caller(); + let recipient: T::AccountId = account("receiver", 0, SEED); + let source_recipient = T::Lookup::unlookup(recipient.clone()); + init_setup::(&caller); + let existential_deposit = >::ExistentialDeposit::get(); + let unvested = existential_deposit + .saturating_mul(ED_MULTIPLIER.div(10u32).into()) + .saturated_into::() + .try_into() + .ok() + .unwrap(); + assert_ok!( + crate::Pallet::::vested_transfer( + RawOrigin::Signed(caller).into(), source_recipient, unvested + ) + ); + assert!(crate::Pallet::::vesting_balance(&recipient).is_some()); + let now = Duration::from_secs(1660694400) + .as_millis() + .saturated_into::() + + 1; + pallet_timestamp::Pallet::::set_timestamp(now); + }: _(RawOrigin::Signed(recipient.clone())) + verify { + assert_has_event::(Event::VestingCompleted(recipient).into()); + } - vested_transfer { - let caller: T::AccountId = whitelisted_caller(); - init_setup::(&caller); - let existential_deposit = >::ExistentialDeposit::get(); - let unvested = existential_deposit - .saturating_mul(ED_MULTIPLIER.div(10u32).into()) - .saturated_into::() - .try_into() - .ok() - .unwrap(); - let recipient: T::AccountId = account("receiver", 0, SEED); - let source_recipient = T::Lookup::unlookup(recipient.clone()); - }: _(RawOrigin::Signed(caller.clone()), source_recipient, unvested) - verify { - assert_eq!(crate::Pallet::::vesting_balance(&recipient), Some(unvested)); - assert_has_event::(Event::VestingUpdated(recipient, unvested).into()); - } + vested_transfer { + let caller: T::AccountId = whitelisted_caller(); + init_setup::(&caller); + let existential_deposit = >::ExistentialDeposit::get(); + let unvested = existential_deposit + .saturating_mul(ED_MULTIPLIER.div(10u32).into()) + .saturated_into::() + .try_into() + .ok() + .unwrap(); + let recipient: T::AccountId = account("receiver", 0, SEED); + let source_recipient = T::Lookup::unlookup(recipient.clone()); + }: _(RawOrigin::Signed(caller.clone()), source_recipient, unvested) + verify { + assert_eq!(crate::Pallet::::vesting_balance(&recipient), Some(unvested)); + assert_has_event::(Event::VestingUpdated(recipient, unvested).into()); + } } impl_benchmark_test_suite!( - Pallet, - crate::mock::ExtBuilder::default() - .existential_deposit(1) - .build(), - crate::mock::Test, + Pallet, + crate::mock::ExtBuilder::default() + .existential_deposit(1) + .build(), + crate::mock::Test, ); diff --git a/pallets/vesting/src/lib.rs b/pallets/vesting/src/lib.rs index 09250b81a..ff8d5f0de 100644 --- a/pallets/vesting/src/lib.rs +++ b/pallets/vesting/src/lib.rs @@ -26,288 +26,288 @@ pub mod weights; pub use crate::weights::WeightInfo; use frame_support::{ - ensure, - pallet_prelude::*, - traits::{ - Currency, ExistenceRequirement, Get, LockIdentifier, LockableCurrency, UnixTime, - WithdrawReasons, - }, + ensure, + pallet_prelude::*, + traits::{ + Currency, ExistenceRequirement, Get, LockIdentifier, LockableCurrency, UnixTime, + WithdrawReasons, + }, }; use frame_system::{ensure_signed, pallet_prelude::*}; pub use pallet::*; use sp_runtime::{ - traits::{Saturating, StaticLookup, Zero}, - Percent, + traits::{Saturating, StaticLookup, Zero}, + Percent, }; type BalanceOf = - <::Currency as Currency<::AccountId>>::Balance; + <::Currency as Currency<::AccountId>>::Balance; pub type Schedule = u64; const VESTING_ID: LockIdentifier = *b"calamvst"; #[frame_support::pallet] pub mod pallet { - use super::*; - - #[pallet::config] - pub trait Config: frame_system::Config { - /// The overarching event type. - type Event: From> + IsType<::Event>; - - /// The currency trait. - type Currency: LockableCurrency; - - type Timestamp: UnixTime; - - /// The minimum amount transferred to call `vested_transfer`. - #[pallet::constant] - type MinVestedTransfer: Get>; - - /// The maximum length of schedule is allowed. - #[pallet::constant] - type MaxScheduleLength: Get; - - type WeightInfo: crate::weights::WeightInfo; - } - - /// Information regarding the vesting of a given account. - #[pallet::storage] - #[pallet::getter(fn vesting_balance)] - pub(super) type VestingBalances = - StorageMap<_, Blake2_128Concat, T::AccountId, BalanceOf>; - - /// Information regarding the vesting of a given account. - #[pallet::storage] - #[pallet::getter(fn vesting_schedule)] - pub(super) type VestingSchedule = StorageValue< - _, - // The schedule is UTC. - BoundedVec<(Percent, Schedule), T::MaxScheduleLength>, - ValueQuery, - DefaultVestingSchedule, - >; - - #[pallet::type_value] - pub(super) fn DefaultVestingSchedule( - ) -> BoundedVec<(Percent, Schedule), T::MaxScheduleLength> { - BoundedVec::try_from(sp_std::vec![ - // 1639094400 = 2021-12-10 00:00:00(UTC) - (Percent::from_percent(45), 1639094400u64), - // 1641340800 = 2022-01-05 00:00:00(UTC) - (Percent::from_percent(11), 1641340800u64), - // 1646179200 = 2022-03-02 00:00:00(UTC) - (Percent::from_percent(11), 1646179200u64), - // 1651017600 = 2022-04-27 00:00:00(UTC) - (Percent::from_percent(11), 1651017600u64), - // 1655856000 = 2022-06-22 00:00:00(UTC) - (Percent::from_percent(11), 1655856000u64), - // 1660694400 = 2022-08-17 00:00:00(UTC) - (Percent::from_percent(11), 1660694400u64), - ]) - .unwrap_or_default() - } - - #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] - pub struct Pallet(_); - - #[pallet::event] - #[pallet::generate_deposit(pub(super) fn deposit_event)] - pub enum Event { - /// The amount vested has been updated. This could indicate more funds are available. - /// The balance given is the amount which is left unvested (and thus locked). - /// \[account, unvested\] - VestingUpdated(T::AccountId, BalanceOf), - /// An \[account\] has become fully vested. No further vesting can happen. - VestingCompleted(T::AccountId), - /// Update a vesting schedule. - /// \[new_schedule\] - VestingScheduleUpdated(BoundedVec), - } - - /// Error for the vesting pallet. - #[pallet::error] - pub enum Error { - /// The account given is not vesting. - NotVesting, - /// An existing vesting schedule already exists for this account that cannot be clobbered. - ExistingVestingSchedule, - /// Amount being transferred is too low to create a vesting schedule. - AmountLow, - /// Not enough tokens for vesting. - BalanceLow, - /// Cannot input - InvalidSchedule, - /// The length of new schedule cannot be bigger/smaller than 6. - InvalidScheduleLength, - /// The new schedule should be sorted. - UnsortedSchedule, - /// The first round of vesting is not done yet. - ClaimTooEarly, - } - - #[pallet::call] - impl Pallet { - /// Update vesting schedule. - /// - /// - `new_schedule`: New schedule for vesting. - #[pallet::weight(T::WeightInfo::update_vesting_schedule())] - pub fn update_vesting_schedule( - origin: OriginFor, - new_schedule: BoundedVec, - ) -> DispatchResult { - ensure_root(origin)?; - - // We have only 6 rounds of schedule. - let old_schedule = VestingSchedule::::get(); - ensure!( - new_schedule.len() == old_schedule.len(), - Error::::InvalidScheduleLength - ); - - // Ensure the new schedule should be sorted. - ensure!( - new_schedule.as_slice().windows(2).all(|w| w[0] < w[1]), - Error::::UnsortedSchedule - ); - - let now = T::Timestamp::now().as_secs(); - for (n, o) in new_schedule.iter().zip(old_schedule.iter()) { - // n == o means we will partialy update vesting schedule. - // n > o means new schedule is future schedule. - // n < o && n > now, also fine. - if o.1 <= now { - // Check partialy updating vesting schedule. - // We don't change past schedule, just skip it. - ensure!(*n == o.1, Error::::InvalidSchedule); - } else { - // New schedule should future time. - ensure!(*n >= now, Error::::InvalidSchedule); - } - } - - VestingSchedule::::mutate(|schedule| { - for (schedule, newer_schedule) in - schedule.as_mut().iter_mut().zip(new_schedule.iter()) - { - schedule.1 = *newer_schedule; - } - }); - - Self::deposit_event(Event::VestingScheduleUpdated(new_schedule)); - Ok(()) - } - - /// Unlock vested balance according to the schedule. - /// - /// The dispatch origin for this call must be _Signed_ and the sender must have funds still - /// locked under this pallet. - /// - /// Emits either `VestingCompleted` or `VestingUpdated`. - #[pallet::weight(T::WeightInfo::vest())] - pub fn vest(origin: OriginFor) -> DispatchResult { - let who = ensure_signed(origin)?; - - let now = T::Timestamp::now().as_secs(); - // Ensure signer can claim once time is up to schedule. - ensure!( - Some(now) >= VestingSchedule::::get().first().map(|v| v.1), - Error::::ClaimTooEarly - ); - - Self::update_lock(&who) - } - - /// Create a vested transfer: send `target` balance with the vesting schedule. - /// - /// The dispatch origin for this call must be _Signed_. - /// - /// - `target`: The account receiving the vested funds. - /// - `locked_amount`: How much tokens will be transfered. - #[pallet::weight(T::WeightInfo::vested_transfer())] - pub fn vested_transfer( - origin: OriginFor, - target: ::Source, - #[pallet::compact] locked_amount: BalanceOf, - ) -> DispatchResult { - let transactor = ensure_signed(origin)?; - ensure!( - locked_amount >= T::MinVestedTransfer::get(), - Error::::AmountLow - ); - - ensure!( - T::Currency::free_balance(&transactor) >= locked_amount, - Error::::BalanceLow - ); - - let who = T::Lookup::lookup(target)?; - ensure!( - !VestingBalances::::contains_key(&who), - Error::::ExistingVestingSchedule - ); - - T::Currency::transfer( - &transactor, - &who, - locked_amount, - ExistenceRequirement::AllowDeath, - )?; - - Self::new_vesting_account(&who, locked_amount)?; - - Ok(()) - } - } + use super::*; + + #[pallet::config] + pub trait Config: frame_system::Config { + /// The overarching event type. + type Event: From> + IsType<::Event>; + + /// The currency trait. + type Currency: LockableCurrency; + + type Timestamp: UnixTime; + + /// The minimum amount transferred to call `vested_transfer`. + #[pallet::constant] + type MinVestedTransfer: Get>; + + /// The maximum length of schedule is allowed. + #[pallet::constant] + type MaxScheduleLength: Get; + + type WeightInfo: crate::weights::WeightInfo; + } + + /// Information regarding the vesting of a given account. + #[pallet::storage] + #[pallet::getter(fn vesting_balance)] + pub(super) type VestingBalances = + StorageMap<_, Blake2_128Concat, T::AccountId, BalanceOf>; + + /// Information regarding the vesting of a given account. + #[pallet::storage] + #[pallet::getter(fn vesting_schedule)] + pub(super) type VestingSchedule = StorageValue< + _, + // The schedule is UTC. + BoundedVec<(Percent, Schedule), T::MaxScheduleLength>, + ValueQuery, + DefaultVestingSchedule, + >; + + #[pallet::type_value] + pub(super) fn DefaultVestingSchedule( + ) -> BoundedVec<(Percent, Schedule), T::MaxScheduleLength> { + BoundedVec::try_from(sp_std::vec![ + // 1639094400 = 2021-12-10 00:00:00(UTC) + (Percent::from_percent(45), 1639094400u64), + // 1641340800 = 2022-01-05 00:00:00(UTC) + (Percent::from_percent(11), 1641340800u64), + // 1646179200 = 2022-03-02 00:00:00(UTC) + (Percent::from_percent(11), 1646179200u64), + // 1651017600 = 2022-04-27 00:00:00(UTC) + (Percent::from_percent(11), 1651017600u64), + // 1655856000 = 2022-06-22 00:00:00(UTC) + (Percent::from_percent(11), 1655856000u64), + // 1660694400 = 2022-08-17 00:00:00(UTC) + (Percent::from_percent(11), 1660694400u64), + ]) + .unwrap_or_default() + } + + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + #[pallet::without_storage_info] + pub struct Pallet(_); + + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { + /// The amount vested has been updated. This could indicate more funds are available. + /// The balance given is the amount which is left unvested (and thus locked). + /// \[account, unvested\] + VestingUpdated(T::AccountId, BalanceOf), + /// An \[account\] has become fully vested. No further vesting can happen. + VestingCompleted(T::AccountId), + /// Update a vesting schedule. + /// \[new_schedule\] + VestingScheduleUpdated(BoundedVec), + } + + /// Error for the vesting pallet. + #[pallet::error] + pub enum Error { + /// The account given is not vesting. + NotVesting, + /// An existing vesting schedule already exists for this account that cannot be clobbered. + ExistingVestingSchedule, + /// Amount being transferred is too low to create a vesting schedule. + AmountLow, + /// Not enough tokens for vesting. + BalanceLow, + /// Cannot input + InvalidSchedule, + /// The length of new schedule cannot be bigger/smaller than 6. + InvalidScheduleLength, + /// The new schedule should be sorted. + UnsortedSchedule, + /// The first round of vesting is not done yet. + ClaimTooEarly, + } + + #[pallet::call] + impl Pallet { + /// Update vesting schedule. + /// + /// - `new_schedule`: New schedule for vesting. + #[pallet::weight(T::WeightInfo::update_vesting_schedule())] + pub fn update_vesting_schedule( + origin: OriginFor, + new_schedule: BoundedVec, + ) -> DispatchResult { + ensure_root(origin)?; + + // We have only 6 rounds of schedule. + let old_schedule = VestingSchedule::::get(); + ensure!( + new_schedule.len() == old_schedule.len(), + Error::::InvalidScheduleLength + ); + + // Ensure the new schedule should be sorted. + ensure!( + new_schedule.as_slice().windows(2).all(|w| w[0] < w[1]), + Error::::UnsortedSchedule + ); + + let now = T::Timestamp::now().as_secs(); + for (n, o) in new_schedule.iter().zip(old_schedule.iter()) { + // n == o means we will partialy update vesting schedule. + // n > o means new schedule is future schedule. + // n < o && n > now, also fine. + if o.1 <= now { + // Check partialy updating vesting schedule. + // We don't change past schedule, just skip it. + ensure!(*n == o.1, Error::::InvalidSchedule); + } else { + // New schedule should future time. + ensure!(*n >= now, Error::::InvalidSchedule); + } + } + + VestingSchedule::::mutate(|schedule| { + for (schedule, newer_schedule) in + schedule.as_mut().iter_mut().zip(new_schedule.iter()) + { + schedule.1 = *newer_schedule; + } + }); + + Self::deposit_event(Event::VestingScheduleUpdated(new_schedule)); + Ok(()) + } + + /// Unlock vested balance according to the schedule. + /// + /// The dispatch origin for this call must be _Signed_ and the sender must have funds still + /// locked under this pallet. + /// + /// Emits either `VestingCompleted` or `VestingUpdated`. + #[pallet::weight(T::WeightInfo::vest())] + pub fn vest(origin: OriginFor) -> DispatchResult { + let who = ensure_signed(origin)?; + + let now = T::Timestamp::now().as_secs(); + // Ensure signer can claim once time is up to schedule. + ensure!( + Some(now) >= VestingSchedule::::get().first().map(|v| v.1), + Error::::ClaimTooEarly + ); + + Self::update_lock(&who) + } + + /// Create a vested transfer: send `target` balance with the vesting schedule. + /// + /// The dispatch origin for this call must be _Signed_. + /// + /// - `target`: The account receiving the vested funds. + /// - `locked_amount`: How much tokens will be transfered. + #[pallet::weight(T::WeightInfo::vested_transfer())] + pub fn vested_transfer( + origin: OriginFor, + target: ::Source, + #[pallet::compact] locked_amount: BalanceOf, + ) -> DispatchResult { + let transactor = ensure_signed(origin)?; + ensure!( + locked_amount >= T::MinVestedTransfer::get(), + Error::::AmountLow + ); + + ensure!( + T::Currency::free_balance(&transactor) >= locked_amount, + Error::::BalanceLow + ); + + let who = T::Lookup::lookup(target)?; + ensure!( + !VestingBalances::::contains_key(&who), + Error::::ExistingVestingSchedule + ); + + T::Currency::transfer( + &transactor, + &who, + locked_amount, + ExistenceRequirement::AllowDeath, + )?; + + Self::new_vesting_account(&who, locked_amount)?; + + Ok(()) + } + } } impl Pallet { - /// (Re)set pallet's currency lock on `who`'s account in accordance with their - /// current unvested amount. - fn update_lock(who: &T::AccountId) -> DispatchResult { - let vesting = Self::vesting_balance(&who).ok_or(Error::::NotVesting)?; - let now = T::Timestamp::now().as_secs(); - - // compute the vested portion - let mut portion = Percent::default(); - for (percentage, timestamp) in VestingSchedule::::get() { - if now < timestamp { - break; - } else { - portion = portion.saturating_add(percentage); - } - } - - let unvested = (Percent::from_percent(100) - portion) * vesting; - - if unvested.is_zero() { - T::Currency::remove_lock(VESTING_ID, who); - VestingBalances::::remove(&who); - Self::deposit_event(Event::::VestingCompleted(who.clone())); - } else { - let reasons = WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE; - T::Currency::set_lock(VESTING_ID, who, unvested, reasons); - Self::deposit_event(Event::::VestingUpdated(who.clone(), unvested)); - } - Ok(()) - } - - /// Adds a vesting schedule to a given account. - fn new_vesting_account(who: &T::AccountId, locked: BalanceOf) -> DispatchResult { - if locked.is_zero() { - return Ok(()); - } - - // Ensure current user doesn't have any vested token. - ensure!( - !VestingBalances::::contains_key(&who), - Error::::ExistingVestingSchedule - ); - - VestingBalances::::insert(&who, locked); - // it can't fail, but even if somehow it did, we don't really care. - Self::update_lock(who) - } + /// (Re)set pallet's currency lock on `who`'s account in accordance with their + /// current unvested amount. + fn update_lock(who: &T::AccountId) -> DispatchResult { + let vesting = Self::vesting_balance(&who).ok_or(Error::::NotVesting)?; + let now = T::Timestamp::now().as_secs(); + + // compute the vested portion + let mut portion = Percent::default(); + for (percentage, timestamp) in VestingSchedule::::get() { + if now < timestamp { + break; + } else { + portion = portion.saturating_add(percentage); + } + } + + let unvested = (Percent::from_percent(100) - portion) * vesting; + + if unvested.is_zero() { + T::Currency::remove_lock(VESTING_ID, who); + VestingBalances::::remove(&who); + Self::deposit_event(Event::::VestingCompleted(who.clone())); + } else { + let reasons = WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE; + T::Currency::set_lock(VESTING_ID, who, unvested, reasons); + Self::deposit_event(Event::::VestingUpdated(who.clone(), unvested)); + } + Ok(()) + } + + /// Adds a vesting schedule to a given account. + fn new_vesting_account(who: &T::AccountId, locked: BalanceOf) -> DispatchResult { + if locked.is_zero() { + return Ok(()); + } + + // Ensure current user doesn't have any vested token. + ensure!( + !VestingBalances::::contains_key(&who), + Error::::ExistingVestingSchedule + ); + + VestingBalances::::insert(&who, locked); + // it can't fail, but even if somehow it did, we don't really care. + Self::update_lock(who) + } } diff --git a/pallets/vesting/src/mock.rs b/pallets/vesting/src/mock.rs index 7949388ea..ef3987554 100644 --- a/pallets/vesting/src/mock.rs +++ b/pallets/vesting/src/mock.rs @@ -15,13 +15,13 @@ // along with Manta. If not, see . use frame_support::{ - parameter_types, - traits::{ConstU32, ConstU64}, + parameter_types, + traits::{ConstU32, ConstU64}, }; use sp_core::H256; use sp_runtime::{ - testing::Header, - traits::{BlakeTwo256, IdentityLookup}, + testing::Header, + traits::{BlakeTwo256, IdentityLookup}, }; use super::*; @@ -39,123 +39,123 @@ pub const BOB: AccountId = 2; pub const ALICE_DEPOSIT: Balance = 10_000; frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - System: frame_system::{Pallet, Call, Config, Storage, Event}, - Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, - Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - CalamariVesting: calamari_vesting::{Pallet, Call, Storage, Event}, - } + pub enum Test where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Config, Storage, Event}, + Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, + CalamariVesting: calamari_vesting::{Pallet, Call, Storage, Event}, + } ); parameter_types! { - pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1024); + pub BlockWeights: frame_system::limits::BlockWeights = + frame_system::limits::BlockWeights::simple_max(1024); } impl frame_system::Config for Test { - type AccountData = pallet_balances::AccountData; - type AccountId = AccountId; - type BaseCallFilter = frame_support::traits::Everything; - type BlockHashCount = ConstU64<250>; - type BlockLength = (); - type BlockNumber = BlockNumber; - type BlockWeights = (); - type Call = Call; - type DbWeight = (); - type Event = Event; - type Hash = H256; - type Hashing = BlakeTwo256; - type Header = Header; - type Index = u64; - type Lookup = IdentityLookup; - type OnKilledAccount = (); - type OnNewAccount = (); - type OnSetCode = (); - type Origin = Origin; - type PalletInfo = PalletInfo; - type SS58Prefix = (); - type SystemWeightInfo = (); - type Version = (); - type MaxConsumers = frame_support::traits::ConstU32<16>; + type AccountData = pallet_balances::AccountData; + type AccountId = AccountId; + type BaseCallFilter = frame_support::traits::Everything; + type BlockHashCount = ConstU64<250>; + type BlockLength = (); + type BlockNumber = BlockNumber; + type BlockWeights = (); + type Call = Call; + type DbWeight = (); + type Event = Event; + type Hash = H256; + type Hashing = BlakeTwo256; + type Header = Header; + type Index = u64; + type Lookup = IdentityLookup; + type OnKilledAccount = (); + type OnNewAccount = (); + type OnSetCode = (); + type Origin = Origin; + type PalletInfo = PalletInfo; + type SS58Prefix = (); + type SystemWeightInfo = (); + type Version = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; } impl pallet_balances::Config for Test { - type AccountStore = System; - type Balance = Balance; - type DustRemoval = (); - type Event = Event; - type ExistentialDeposit = ExistentialDeposit; - type MaxLocks = ConstU32<10>; - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type WeightInfo = (); + type AccountStore = System; + type Balance = Balance; + type DustRemoval = (); + type Event = Event; + type ExistentialDeposit = ExistentialDeposit; + type MaxLocks = ConstU32<10>; + type MaxReserves = (); + type ReserveIdentifier = [u8; 8]; + type WeightInfo = (); } parameter_types! { - pub const MinimumPeriod: u64 = 12_000 / 2; + pub const MinimumPeriod: u64 = 12_000 / 2; } impl pallet_timestamp::Config for Test { - type Moment = u64; - type OnTimestampSet = (); - type MinimumPeriod = MinimumPeriod; - type WeightInfo = (); + type Moment = u64; + type OnTimestampSet = (); + type MinimumPeriod = MinimumPeriod; + type WeightInfo = (); } parameter_types! { - pub const MinVestedTransfer: Balance = 2; - pub static ExistentialDeposit: Balance = 1; + pub const MinVestedTransfer: Balance = 2; + pub static ExistentialDeposit: Balance = 1; } impl Config for Test { - type Currency = Balances; - type Event = Event; - type Timestamp = Timestamp; - type MinVestedTransfer = MinVestedTransfer; - type MaxScheduleLength = ConstU32<6>; - type WeightInfo = (); + type Currency = Balances; + type Event = Event; + type Timestamp = Timestamp; + type MinVestedTransfer = MinVestedTransfer; + type MaxScheduleLength = ConstU32<6>; + type WeightInfo = (); } pub struct ExtBuilder { - existential_deposit: Balance, + existential_deposit: Balance, } impl Default for ExtBuilder { - fn default() -> Self { - Self { - existential_deposit: 1, - } - } + fn default() -> Self { + Self { + existential_deposit: 1, + } + } } impl ExtBuilder { - pub fn existential_deposit(mut self, existential_deposit: Balance) -> Self { - self.existential_deposit = existential_deposit; - self - } - - pub fn build(self) -> sp_io::TestExternalities { - EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = self.existential_deposit); - let mut t = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); - pallet_balances::GenesisConfig:: { - balances: vec![(ALICE, ALICE_DEPOSIT * self.existential_deposit)], - } - .assimilate_storage(&mut t) - .unwrap(); - - let mut ext = sp_io::TestExternalities::new(t); - ext.execute_with(|| { - // Set current time more early than the first schedule. - Timestamp::set_timestamp(VestingSchedule::::get()[0].1 * 1000 - 3 * 6000); - System::set_block_number(1); - }); - ext - } + pub fn existential_deposit(mut self, existential_deposit: Balance) -> Self { + self.existential_deposit = existential_deposit; + self + } + + pub fn build(self) -> sp_io::TestExternalities { + EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = self.existential_deposit); + let mut t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); + pallet_balances::GenesisConfig:: { + balances: vec![(ALICE, ALICE_DEPOSIT * self.existential_deposit)], + } + .assimilate_storage(&mut t) + .unwrap(); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| { + // Set current time more early than the first schedule. + Timestamp::set_timestamp(VestingSchedule::::get()[0].1 * 1000 - 3 * 6000); + System::set_block_number(1); + }); + ext + } } pub(crate) fn run_to_block(n: u64) { - System::set_block_number(n); + System::set_block_number(n); } diff --git a/pallets/vesting/src/tests.rs b/pallets/vesting/src/tests.rs index e52cacef3..5986726a7 100644 --- a/pallets/vesting/src/tests.rs +++ b/pallets/vesting/src/tests.rs @@ -21,511 +21,512 @@ use mock::{Event as MockEvent, *}; #[test] fn alice_vesting_for_bob_should_work() { - ExtBuilder::default() - .existential_deposit(1) - .build() - .execute_with(|| { - // Cannot vest tokens that is less than expected. - assert_noop!( - CalamariVesting::vested_transfer( - Origin::signed(ALICE), - BOB, - MinVestedTransfer::get() - 1 - ), - Error::::AmountLow - ); - - // Signer cannot vest tokens that exceeds all he has. - assert_noop!( - CalamariVesting::vested_transfer(Origin::signed(ALICE), BOB, ALICE_DEPOSIT + 1), - Error::::BalanceLow - ); - - let unvested = 100; - assert_ok!(CalamariVesting::vested_transfer( - Origin::signed(ALICE), - BOB, - unvested - )); - - // Cannot vest tokens the same user more than twice. - assert_noop!( - CalamariVesting::vested_transfer(Origin::signed(ALICE), BOB, unvested), - Error::::ExistingVestingSchedule - ); - - assert_eq!(Balances::free_balance(ALICE), ALICE_DEPOSIT - unvested); - assert_eq!(Balances::free_balance(BOB), unvested); - assert_eq!(VestingBalances::::get(BOB), Some(unvested)); - - // Now Bob cannot claim any token. - assert_noop!( - CalamariVesting::vest(Origin::signed(BOB)), - Error::::ClaimTooEarly, - ); - - // Check event - System::assert_has_event(MockEvent::CalamariVesting(PalletEvent::VestingUpdated( - BOB, unvested, - ))); - - run_to_block(3); - // Ensure current timestamp is bigger than the 1th round of schedule. - // Now Bob can claim 1th round vested tokens. - let first_round = 0; - let now = VestingSchedule::::get()[first_round].1 * 1000 + 1; - Timestamp::set_timestamp(now); - - assert_ok!(CalamariVesting::vest(Origin::signed(BOB))); - assert_eq!(Balances::free_balance(BOB), unvested); - - // BOB cannot transfer more than 1th round of vested tokens. - // Bacause the rest of tokens are locked. - let vested = VestingSchedule::::get()[first_round].0 * unvested; - // Check event - System::assert_has_event(MockEvent::CalamariVesting(PalletEvent::VestingUpdated( - BOB, - unvested - vested, - ))); - - assert_noop!( - Balances::transfer(Origin::signed(BOB), ALICE, vested + 1), - pallet_balances::Error::::LiquidityRestrictions, - ); - - assert_ok!(Balances::transfer(Origin::signed(BOB), ALICE, vested)); - assert_eq!( - Balances::free_balance(ALICE), - ALICE_DEPOSIT - unvested + vested - ); - assert_eq!(Balances::free_balance(BOB), unvested - vested); - - // Ensure current timestamp is bigger than the 6th round of schedule. - // Now Bob can claim 6th round vested tokens. - let last_round = 5; - let now = VestingSchedule::::get()[last_round].1 * 1000 + 1; - Timestamp::set_timestamp(now); - - assert_ok!(CalamariVesting::vest(Origin::signed(BOB))); - assert_eq!(Balances::free_balance(BOB), unvested - vested); - - // Check vested done event - System::assert_has_event(MockEvent::CalamariVesting(PalletEvent::VestingCompleted( - BOB, - ))); - - // Now, Bob can transfer all his tokens. - assert_ok!(Balances::transfer( - Origin::signed(BOB), - ALICE, - unvested - vested - )); - assert_eq!(Balances::free_balance(ALICE), ALICE_DEPOSIT); - assert_eq!(Balances::free_balance(BOB), 0); - - // Ensure vesting info is removed once vesting is done. - assert_eq!(VestingBalances::::get(BOB), None); - }); + ExtBuilder::default() + .existential_deposit(1) + .build() + .execute_with(|| { + // Cannot vest tokens that is less than expected. + assert_noop!( + CalamariVesting::vested_transfer( + Origin::signed(ALICE), + BOB, + MinVestedTransfer::get() - 1 + ), + Error::::AmountLow + ); + + // Signer cannot vest tokens that exceeds all he has. + assert_noop!( + CalamariVesting::vested_transfer(Origin::signed(ALICE), BOB, ALICE_DEPOSIT + 1), + Error::::BalanceLow + ); + + let unvested = 100; + assert_ok!(CalamariVesting::vested_transfer( + Origin::signed(ALICE), + BOB, + unvested + )); + + // Cannot vest tokens the same user more than twice. + assert_noop!( + CalamariVesting::vested_transfer(Origin::signed(ALICE), BOB, unvested), + Error::::ExistingVestingSchedule + ); + + assert_eq!(Balances::free_balance(ALICE), ALICE_DEPOSIT - unvested); + assert_eq!(Balances::free_balance(BOB), unvested); + assert_eq!(VestingBalances::::get(BOB), Some(unvested)); + + // Now Bob cannot claim any token. + assert_noop!( + CalamariVesting::vest(Origin::signed(BOB)), + Error::::ClaimTooEarly, + ); + + // Check event + System::assert_has_event(MockEvent::CalamariVesting(PalletEvent::VestingUpdated( + BOB, unvested, + ))); + + run_to_block(3); + // Ensure current timestamp is bigger than the 1th round of schedule. + // Now Bob can claim 1th round vested tokens. + let first_round = 0; + let now = VestingSchedule::::get()[first_round].1 * 1000 + 1; + Timestamp::set_timestamp(now); + + assert_ok!(CalamariVesting::vest(Origin::signed(BOB))); + assert_eq!(Balances::free_balance(BOB), unvested); + + // BOB cannot transfer more than 1th round of vested tokens. + // Bacause the rest of tokens are locked. + let vested = VestingSchedule::::get()[first_round].0 * unvested; + // Check event + System::assert_has_event(MockEvent::CalamariVesting(PalletEvent::VestingUpdated( + BOB, + unvested - vested, + ))); + + assert_noop!( + Balances::transfer(Origin::signed(BOB), ALICE, vested + 1), + pallet_balances::Error::::LiquidityRestrictions, + ); + + assert_ok!(Balances::transfer(Origin::signed(BOB), ALICE, vested)); + assert_eq!( + Balances::free_balance(ALICE), + ALICE_DEPOSIT - unvested + vested + ); + assert_eq!(Balances::free_balance(BOB), unvested - vested); + + // Ensure current timestamp is bigger than the 6th round of schedule. + // Now Bob can claim 6th round vested tokens. + let last_round = 5; + let now = VestingSchedule::::get()[last_round].1 * 1000 + 1; + Timestamp::set_timestamp(now); + + assert_ok!(CalamariVesting::vest(Origin::signed(BOB))); + assert_eq!(Balances::free_balance(BOB), unvested - vested); + + // Check vested done event + System::assert_has_event(MockEvent::CalamariVesting(PalletEvent::VestingCompleted( + BOB, + ))); + + // Now, Bob can transfer all his tokens. + assert_ok!(Balances::transfer( + Origin::signed(BOB), + ALICE, + unvested - vested + )); + assert_eq!(Balances::free_balance(ALICE), ALICE_DEPOSIT); + assert_eq!(Balances::free_balance(BOB), 0); + + // Ensure vesting info is removed once vesting is done. + assert_eq!(VestingBalances::::get(BOB), None); + }); } #[test] fn alice_vesting_for_bob_claim_slowly_should_work() { - ExtBuilder::default() - .existential_deposit(1) - .build() - .execute_with(|| { - let unvested = 100; - assert_ok!(CalamariVesting::vested_transfer( - Origin::signed(ALICE), - BOB, - unvested - )); - assert_eq!(Balances::free_balance(ALICE), ALICE_DEPOSIT - unvested); - assert_eq!(Balances::free_balance(BOB), unvested); - assert_eq!(VestingBalances::::get(BOB), Some(unvested)); - - // Now Bob cannot claim any token. - assert_noop!( - CalamariVesting::vest(Origin::signed(BOB)), - Error::::ClaimTooEarly, - ); - - // Check event - System::assert_has_event(MockEvent::CalamariVesting(PalletEvent::VestingUpdated( - BOB, unvested, - ))); - - // Ensure current timestamp is bigger than the 4th round of schedule. - // Now Bob can claim 4th round vested tokens. - let fourth_round = 3; - let now = VestingSchedule::::get()[fourth_round].1 * 1000 + 1; - Timestamp::set_timestamp(now); - - assert_ok!(CalamariVesting::vest(Origin::signed(BOB))); - assert_eq!(Balances::free_balance(BOB), unvested); - - // Calculate how many tokens that have been vested. - let vested = VestingSchedule::::get()[..=fourth_round] - .iter() - .map(|s| s.0) - .fold(Percent::from_percent(0), |acc, p| acc.saturating_add(p)) - * unvested; - assert_noop!( - Balances::transfer(Origin::signed(BOB), ALICE, vested + 1), - pallet_balances::Error::::LiquidityRestrictions, - ); - - assert_ok!(Balances::transfer(Origin::signed(BOB), ALICE, vested)); - assert_eq!( - Balances::free_balance(ALICE), - ALICE_DEPOSIT - unvested + vested - ); - assert_eq!(Balances::free_balance(BOB), unvested - vested); - }); + ExtBuilder::default() + .existential_deposit(1) + .build() + .execute_with(|| { + let unvested = 100; + assert_ok!(CalamariVesting::vested_transfer( + Origin::signed(ALICE), + BOB, + unvested + )); + assert_eq!(Balances::free_balance(ALICE), ALICE_DEPOSIT - unvested); + assert_eq!(Balances::free_balance(BOB), unvested); + assert_eq!(VestingBalances::::get(BOB), Some(unvested)); + + // Now Bob cannot claim any token. + assert_noop!( + CalamariVesting::vest(Origin::signed(BOB)), + Error::::ClaimTooEarly, + ); + + // Check event + System::assert_has_event(MockEvent::CalamariVesting(PalletEvent::VestingUpdated( + BOB, unvested, + ))); + + // Ensure current timestamp is bigger than the 4th round of schedule. + // Now Bob can claim 4th round vested tokens. + let fourth_round = 3; + let now = VestingSchedule::::get()[fourth_round].1 * 1000 + 1; + Timestamp::set_timestamp(now); + + assert_ok!(CalamariVesting::vest(Origin::signed(BOB))); + assert_eq!(Balances::free_balance(BOB), unvested); + + // Calculate how many tokens that have been vested. + let vested = VestingSchedule::::get()[..=fourth_round] + .iter() + .map(|s| s.0) + .fold(Percent::from_percent(0), |acc, p| acc.saturating_add(p)) + * unvested; + assert_noop!( + Balances::transfer(Origin::signed(BOB), ALICE, vested + 1), + pallet_balances::Error::::LiquidityRestrictions, + ); + + assert_ok!(Balances::transfer(Origin::signed(BOB), ALICE, vested)); + assert_eq!( + Balances::free_balance(ALICE), + ALICE_DEPOSIT - unvested + vested + ); + assert_eq!(Balances::free_balance(BOB), unvested - vested); + }); } #[test] fn alice_vesting_for_bob_claim_arbitrarily_should_work() { - ExtBuilder::default() - .existential_deposit(1) - .build() - .execute_with(|| { - let unvested = 100; - assert_ok!(CalamariVesting::vested_transfer( - Origin::signed(ALICE), - BOB, - unvested - )); - assert_eq!(Balances::free_balance(ALICE), ALICE_DEPOSIT - unvested); - assert_eq!(Balances::free_balance(BOB), unvested); - assert_eq!(VestingBalances::::get(BOB), Some(unvested)); - - run_to_block(3); - // Ensure current timestamp is bigger than the 1th round of schedule. - // Now Bob can claim 1th round vested tokens. - let first_round = 0; - let now = VestingSchedule::::get()[first_round].1 * 1000 + 1; - Timestamp::set_timestamp(now); - - assert_ok!(CalamariVesting::vest(Origin::signed(BOB))); - assert_eq!(Balances::free_balance(BOB), unvested); - - // BOB cannot transfer more than 1th round of vested tokens. - // Bacause the rest of tokens are locked. - let vested_1 = VestingSchedule::::get()[first_round].0 * unvested; - // Check event - System::assert_has_event(MockEvent::CalamariVesting(PalletEvent::VestingUpdated( - BOB, - unvested - vested_1, - ))); - - assert_noop!( - Balances::transfer(Origin::signed(BOB), ALICE, vested_1 + 1), - pallet_balances::Error::::LiquidityRestrictions, - ); - - assert_ok!(Balances::transfer(Origin::signed(BOB), ALICE, vested_1)); - assert_eq!( - Balances::free_balance(ALICE), - ALICE_DEPOSIT - unvested + vested_1 - ); - assert_eq!(Balances::free_balance(BOB), unvested - vested_1); - - // Ensure current timestamp is bigger than the 5th round of schedule. - // Now Bob can claim 5th round vested tokens. - let sixth_round = 4; - let now = VestingSchedule::::get()[sixth_round].1 * 1000 + 1; - Timestamp::set_timestamp(now); - - assert_ok!(CalamariVesting::vest(Origin::signed(BOB))); - - // All vested for 5th round. - let vested_0_to_4 = VestingSchedule::::get()[..=sixth_round] - .iter() - .map(|s| s.0) - .fold(Percent::from_percent(0), |acc, p| acc.saturating_add(p)) - * unvested; - assert_noop!( - Balances::transfer(Origin::signed(BOB), ALICE, vested_0_to_4 + 1 - vested_1), - pallet_balances::Error::::LiquidityRestrictions, - ); - - // Vested only 6th round. - let vested_5 = VestingSchedule::::get()[sixth_round].0 * unvested; - - // Check event - System::assert_has_event(MockEvent::CalamariVesting(PalletEvent::VestingUpdated( - BOB, 11, - ))); - assert_eq!( - Balances::free_balance(BOB), - vested_0_to_4 + vested_5 - vested_1 - ); - - assert_ok!(Balances::transfer( - Origin::signed(BOB), - ALICE, - vested_0_to_4 - vested_1 - )); - assert_eq!(Balances::free_balance(ALICE), ALICE_DEPOSIT - vested_5); - assert_eq!(Balances::free_balance(BOB), vested_5); - }); + ExtBuilder::default() + .existential_deposit(1) + .build() + .execute_with(|| { + let unvested = 100; + assert_ok!(CalamariVesting::vested_transfer( + Origin::signed(ALICE), + BOB, + unvested + )); + assert_eq!(Balances::free_balance(ALICE), ALICE_DEPOSIT - unvested); + assert_eq!(Balances::free_balance(BOB), unvested); + assert_eq!(VestingBalances::::get(BOB), Some(unvested)); + + run_to_block(3); + // Ensure current timestamp is bigger than the 1th round of schedule. + // Now Bob can claim 1th round vested tokens. + let first_round = 0; + let now = VestingSchedule::::get()[first_round].1 * 1000 + 1; + Timestamp::set_timestamp(now); + + assert_ok!(CalamariVesting::vest(Origin::signed(BOB))); + assert_eq!(Balances::free_balance(BOB), unvested); + + // BOB cannot transfer more than 1th round of vested tokens. + // Bacause the rest of tokens are locked. + let vested_1 = VestingSchedule::::get()[first_round].0 * unvested; + // Check event + System::assert_has_event(MockEvent::CalamariVesting(PalletEvent::VestingUpdated( + BOB, + unvested - vested_1, + ))); + + assert_noop!( + Balances::transfer(Origin::signed(BOB), ALICE, vested_1 + 1), + pallet_balances::Error::::LiquidityRestrictions, + ); + + assert_ok!(Balances::transfer(Origin::signed(BOB), ALICE, vested_1)); + assert_eq!( + Balances::free_balance(ALICE), + ALICE_DEPOSIT - unvested + vested_1 + ); + assert_eq!(Balances::free_balance(BOB), unvested - vested_1); + + // Ensure current timestamp is bigger than the 5th round of schedule. + // Now Bob can claim 5th round vested tokens. + let sixth_round = 4; + let now = VestingSchedule::::get()[sixth_round].1 * 1000 + 1; + Timestamp::set_timestamp(now); + + assert_ok!(CalamariVesting::vest(Origin::signed(BOB))); + + // All vested for 5th round. + let vested_0_to_4 = VestingSchedule::::get()[..=sixth_round] + .iter() + .map(|s| s.0) + .fold(Percent::from_percent(0), |acc, p| acc.saturating_add(p)) + * unvested; + assert_noop!( + Balances::transfer(Origin::signed(BOB), ALICE, vested_0_to_4 + 1 - vested_1), + pallet_balances::Error::::LiquidityRestrictions, + ); + + // Vested only 6th round. + let vested_5 = VestingSchedule::::get()[sixth_round].0 * unvested; + + // Check event + System::assert_has_event(MockEvent::CalamariVesting(PalletEvent::VestingUpdated( + BOB, 11, + ))); + assert_eq!( + Balances::free_balance(BOB), + vested_0_to_4 + vested_5 - vested_1 + ); + + assert_ok!(Balances::transfer( + Origin::signed(BOB), + ALICE, + vested_0_to_4 - vested_1 + )); + assert_eq!(Balances::free_balance(ALICE), ALICE_DEPOSIT - vested_5); + assert_eq!(Balances::free_balance(BOB), vested_5); + }); } #[test] fn vesting_complete_should_work() { - ExtBuilder::default() - .existential_deposit(1) - .build() - .execute_with(|| { - let unvested = 100; - assert_ok!(CalamariVesting::vested_transfer( - Origin::signed(ALICE), - BOB, - unvested - )); - assert_eq!(Balances::free_balance(ALICE), ALICE_DEPOSIT - unvested); - assert_eq!(VestingBalances::::get(BOB), Some(unvested)); - - // Now Bob cannot claim any token. - assert_noop!( - CalamariVesting::vest(Origin::signed(BOB)), - Error::::ClaimTooEarly, - ); - - // Check event - System::assert_has_event(MockEvent::CalamariVesting(PalletEvent::VestingUpdated( - BOB, unvested, - ))); - - // Now Bob cannot transfer locked tokens. - assert_noop!( - Balances::transfer(Origin::signed(BOB), ALICE, 1), - pallet_balances::Error::::LiquidityRestrictions, - ); - - // Ensure current timestamp is bigger than the 6th round of schedule. - // Now Bob can claim 6th round vested tokens. - let last_round = 5; - let now = VestingSchedule::::get()[last_round].1 * 1000 + 1; - Timestamp::set_timestamp(now); - - assert_ok!(CalamariVesting::vest(Origin::signed(BOB))); - assert_eq!(Balances::free_balance(BOB), unvested); - - // Check vested done event - System::assert_has_event(MockEvent::CalamariVesting(PalletEvent::VestingCompleted( - BOB, - ))); - let vested = unvested; - - // Now, Bob can transfer all his tokens. - assert_ok!(Balances::transfer(Origin::signed(BOB), ALICE, vested)); - assert_eq!(Balances::free_balance(ALICE), ALICE_DEPOSIT); - assert_eq!(Balances::free_balance(BOB), 0); - - // Ensure vesting info is removed once vesting is done. - assert_eq!(VestingBalances::::get(BOB), None); - }); + ExtBuilder::default() + .existential_deposit(1) + .build() + .execute_with(|| { + let unvested = 100; + assert_ok!(CalamariVesting::vested_transfer( + Origin::signed(ALICE), + BOB, + unvested + )); + assert_eq!(Balances::free_balance(ALICE), ALICE_DEPOSIT - unvested); + assert_eq!(VestingBalances::::get(BOB), Some(unvested)); + + // Now Bob cannot claim any token. + assert_noop!( + CalamariVesting::vest(Origin::signed(BOB)), + Error::::ClaimTooEarly, + ); + + // Check event + System::assert_has_event(MockEvent::CalamariVesting(PalletEvent::VestingUpdated( + BOB, unvested, + ))); + + // Now Bob cannot transfer locked tokens. + assert_noop!( + Balances::transfer(Origin::signed(BOB), ALICE, 1), + pallet_balances::Error::::LiquidityRestrictions, + ); + + // Ensure current timestamp is bigger than the 6th round of schedule. + // Now Bob can claim 6th round vested tokens. + let last_round = 5; + let now = VestingSchedule::::get()[last_round].1 * 1000 + 1; + Timestamp::set_timestamp(now); + + assert_ok!(CalamariVesting::vest(Origin::signed(BOB))); + assert_eq!(Balances::free_balance(BOB), unvested); + + // Check vested done event + System::assert_has_event(MockEvent::CalamariVesting(PalletEvent::VestingCompleted( + BOB, + ))); + let vested = unvested; + + // Now, Bob can transfer all his tokens. + assert_ok!(Balances::transfer(Origin::signed(BOB), ALICE, vested)); + assert_eq!(Balances::free_balance(ALICE), ALICE_DEPOSIT); + assert_eq!(Balances::free_balance(BOB), 0); + + // Ensure vesting info is removed once vesting is done. + assert_eq!(VestingBalances::::get(BOB), None); + }); } #[test] fn partially_update_vesting_schedule_should_work() { - ExtBuilder::default() - .existential_deposit(1) - .build() - .execute_with(|| { - // Ensure current timestamp is bigger than the 1th round of schedule. - // Now Bob can claim 1th round vested tokens. - let frist_round = 0; - let now = VestingSchedule::::get()[frist_round].1 * 1000 + 1; - Timestamp::set_timestamp(now); - - // skip 2 round of old schedule. - let skipped_count = 2; - let new_schedule = BoundedVec::try_from({ - let mut new_schedule = vec![]; - for (index, (_, schedule)) in VestingSchedule::::get().iter().enumerate() { - if index < skipped_count { - // Do not change old schedule - new_schedule.push(*schedule); - continue; - } - // odd means more early than old schedle but still later than now. - // even means more late than old schedle but still later than now. - if index % 2 == 0 { - new_schedule.push(*schedule + 1); - } else { - new_schedule.push(*schedule - 1); - } - } - new_schedule - }) - .unwrap_or_default(); - - assert_ok!(CalamariVesting::update_vesting_schedule( - Origin::root(), - new_schedule.clone() - )); - // Check storage - assert_eq!( - VestingSchedule::::get() - .iter() - .map(|(_, s)| *s) - .collect::>(), - *new_schedule - ); - // Check event - System::assert_has_event(MockEvent::CalamariVesting( - PalletEvent::VestingScheduleUpdated(new_schedule), - )); - }); + ExtBuilder::default() + .existential_deposit(1) + .build() + .execute_with(|| { + // Ensure current timestamp is bigger than the 1th round of schedule. + // Now Bob can claim 1th round vested tokens. + let frist_round = 0; + let now = VestingSchedule::::get()[frist_round].1 * 1000 + 1; + Timestamp::set_timestamp(now); + + // skip 2 round of old schedule. + let skipped_count = 2; + let new_schedule = BoundedVec::try_from({ + let mut new_schedule = vec![]; + for (index, (_, schedule)) in VestingSchedule::::get().iter().enumerate() { + if index < skipped_count { + // Do not change old schedule + new_schedule.push(*schedule); + continue; + } + // odd means more early than old schedle but still later than now. + // even means more late than old schedle but still later than now. + if index % 2 == 0 { + new_schedule.push(*schedule + 1); + } else { + new_schedule.push(*schedule - 1); + } + } + new_schedule + }) + .unwrap_or_default(); + + assert_ok!(CalamariVesting::update_vesting_schedule( + Origin::root(), + new_schedule.clone() + )); + // Check storage + assert_eq!( + VestingSchedule::::get() + .iter() + .map(|(_, s)| *s) + .collect::>(), + *new_schedule + ); + // Check event + System::assert_has_event(MockEvent::CalamariVesting( + PalletEvent::VestingScheduleUpdated(new_schedule), + )); + }); } #[test] fn update_brand_new_vesting_schedule_should_work() { - ExtBuilder::default() - .existential_deposit(1) - .build() - .execute_with(|| { - // Ensure current timestamp is bigger than the 1th round of schedule. - // Now Bob can claim 1th round vested tokens. - let frist_round = 0; - let now = VestingSchedule::::get()[frist_round].1 * 1000 - 1; - Timestamp::set_timestamp(now); - - let new_schedule = BoundedVec::try_from( - VestingSchedule::::get() - .iter() - .map(|(_, s)| s + 1) - .collect::>(), - ) - .unwrap_or_default(); - assert_ok!(CalamariVesting::update_vesting_schedule( - Origin::root(), - new_schedule.clone() - )); - // Check storage - assert_eq!( - VestingSchedule::::get() - .iter() - .map(|(_, s)| *s) - .collect::>(), - *new_schedule - ); - // Check event - System::assert_has_event(MockEvent::CalamariVesting( - PalletEvent::VestingScheduleUpdated(new_schedule), - )); - }); + ExtBuilder::default() + .existential_deposit(1) + .build() + .execute_with(|| { + // Ensure current timestamp is bigger than the 1th round of schedule. + // Now Bob can claim 1th round vested tokens. + let frist_round = 0; + let now = VestingSchedule::::get()[frist_round].1 * 1000 - 1; + Timestamp::set_timestamp(now); + + let new_schedule = BoundedVec::try_from( + VestingSchedule::::get() + .iter() + .map(|(_, s)| s + 1) + .collect::>(), + ) + .unwrap_or_default(); + assert_ok!(CalamariVesting::update_vesting_schedule( + Origin::root(), + new_schedule.clone() + )); + // Check storage + assert_eq!( + VestingSchedule::::get() + .iter() + .map(|(_, s)| *s) + .collect::>(), + *new_schedule + ); + // Check event + System::assert_has_event(MockEvent::CalamariVesting( + PalletEvent::VestingScheduleUpdated(new_schedule), + )); + }); } #[test] fn invalid_schedule_should_not_be_updated() { - ExtBuilder::default() - .existential_deposit(1) - .build() - .execute_with(|| { - // Cannot update the length of schedule is bigger than 6 or smaller than 6. - let wrong_length_schedule: BoundedVec::MaxScheduleLength> = - BoundedVec::try_from(vec![1, 2, 3, 4, 5, 6, 7]).unwrap_or_default(); - assert_noop!( - CalamariVesting::update_vesting_schedule(Origin::root(), wrong_length_schedule), - Error::::InvalidScheduleLength, - ); - - // We have only 6 rounds of schedule. - let wrong_length_schedule: BoundedVec::MaxScheduleLength> = - BoundedVec::try_from(vec![1, 2, 3, 4, 5]).unwrap_or_default(); - assert_noop!( - CalamariVesting::update_vesting_schedule(Origin::root(), wrong_length_schedule), - Error::::InvalidScheduleLength, - ); - - // The new schedule should be a sorted array. - let invalid_schedule: BoundedVec::MaxScheduleLength> = - BoundedVec::try_from(vec![1, 2, 9, 4, 8, 6]).unwrap_or_default(); - assert_noop!( - CalamariVesting::update_vesting_schedule(Origin::root(), invalid_schedule), - Error::::UnsortedSchedule, - ); - - // Check updating invalid partial schedule should not work. - let next_round = 3; - // now is between 3th round and 4th round. - let now = (VestingSchedule::::get()[next_round].1 - 1) * 1000; - Timestamp::set_timestamp(now); - - let invalid_schedule = BoundedVec::try_from({ - let mut new_schedule = vec![]; - for (index, (_, schedule)) in VestingSchedule::::get().iter().enumerate() { - if index < next_round { - // Do not change old schedule - new_schedule.push(*schedule); - continue; - } - // Set one schedule that is past time. - // This schedule is earlier than now. - if index == next_round { - new_schedule.push((now - 2) / 1000); - continue; - } - // Do not change the rest of future schedule; - new_schedule.push(*schedule); - } - new_schedule - }) - .unwrap_or_default(); - - assert_noop!( - CalamariVesting::update_vesting_schedule(Origin::root(), invalid_schedule), - Error::::InvalidSchedule, - ); - }); + ExtBuilder::default() + .existential_deposit(1) + .build() + .execute_with(|| { + // Cannot update the length of schedule is bigger than 6 or smaller than 6. + let wrong_length_schedule: BoundedVec::MaxScheduleLength> = + BoundedVec::try_from(vec![1, 2, 3, 4, 5, 6, 7]).unwrap_or_default(); + assert_noop!( + CalamariVesting::update_vesting_schedule(Origin::root(), wrong_length_schedule), + Error::::InvalidScheduleLength, + ); + + // We have only 6 rounds of schedule. + let wrong_length_schedule: BoundedVec::MaxScheduleLength> = + BoundedVec::try_from(vec![1, 2, 3, 4, 5]).unwrap_or_default(); + assert_noop!( + CalamariVesting::update_vesting_schedule(Origin::root(), wrong_length_schedule), + Error::::InvalidScheduleLength, + ); + + // The new schedule should be a sorted array. + let invalid_schedule: BoundedVec::MaxScheduleLength> = + BoundedVec::try_from(vec![1, 2, 9, 4, 8, 6]).unwrap_or_default(); + assert_noop!( + CalamariVesting::update_vesting_schedule(Origin::root(), invalid_schedule), + Error::::UnsortedSchedule, + ); + + // Check updating invalid partial schedule should not work. + let next_round = 3; + // now is between 3th round and 4th round. + let now = (VestingSchedule::::get()[next_round].1 - 1) * 1000; + Timestamp::set_timestamp(now); + + let invalid_schedule = BoundedVec::try_from({ + let mut new_schedule = vec![]; + for (index, (_, schedule)) in VestingSchedule::::get().iter().enumerate() { + if index < next_round { + // Do not change old schedule + new_schedule.push(*schedule); + continue; + } + // Set one schedule that is past time. + // This schedule is earlier than now. + if index == next_round { + new_schedule.push((now - 2) / 1000); + continue; + } + // Do not change the rest of future schedule; + new_schedule.push(*schedule); + } + new_schedule + }) + .unwrap_or_default(); + + assert_noop!( + CalamariVesting::update_vesting_schedule(Origin::root(), invalid_schedule), + Error::::InvalidSchedule, + ); + }); } #[test] fn check_vesting_schedule() { - #[rustfmt::skip] - let default_schedule: [(Percent, (i32, u32, u32, u32, u32, u32), &'static str); 6] = [ - // (Percentage, (timestamp), date) - (Percent::from_percent(45), (2021, 12, 10, 0, 0, 0), "2021-12-10 00:00:00"), - (Percent::from_percent(11), (2022, 01, 05, 0, 0, 0), "2022-01-05 00:00:00"), - (Percent::from_percent(11), (2022, 03, 02, 0, 0, 0), "2022-03-02 00:00:00"), - (Percent::from_percent(11), (2022, 04, 27, 0, 0, 0), "2022-04-27 00:00:00"), - (Percent::from_percent(11), (2022, 06, 22, 0, 0, 0), "2022-06-22 00:00:00"), - (Percent::from_percent(11), (2022, 08, 17, 0, 0, 0), "2022-08-17 00:00:00"), - ]; - - ExtBuilder::default() - .existential_deposit(1) - .build() - .execute_with(|| { - // Check current schedule. - let schedule = VestingSchedule::::get(); - let schedule_len: u32 = ::MaxScheduleLength::get(); - assert_eq!(schedule.len(), schedule_len as usize); - - //Check percentage. - assert_eq!( - schedule - .iter() - .map(|(p, _)| p) - .fold(Percent::from_percent(0), |acc, p| acc.saturating_add(*p)), - Percent::from_percent(100) - ); - - for ((p, s), ds) in schedule.iter().zip(default_schedule.iter()) { - let dt = Utc - .ymd(ds.1 .0, ds.1 .1, ds.1 .2) - .and_hms(ds.1 .3, ds.1 .4, ds.1 .5); - - // Check each percentage is correct. - assert_eq!(ds.0, *p); - // Check datetime is correct. - assert_eq!(dt.format("%Y-%m-%d %H:%M:%S").to_string(), ds.2); - // Check timestamp is correct. - assert_eq!(dt.timestamp() as u64, *s); - } - }); + type Timestamp = (i32, u32, u32, u32, u32, u32); + #[rustfmt::skip] + let default_schedule: [(Percent,Timestamp, &'static str); 6] = [ + // (Percentage, (timestamp), date) + (Percent::from_percent(45), (2021, 12, 10, 0, 0, 0), "2021-12-10 00:00:00"), + (Percent::from_percent(11), (2022, 1, 5, 0, 0, 0), "2022-01-05 00:00:00"), + (Percent::from_percent(11), (2022, 3, 2, 0, 0, 0), "2022-03-02 00:00:00"), + (Percent::from_percent(11), (2022, 4, 27, 0, 0, 0), "2022-04-27 00:00:00"), + (Percent::from_percent(11), (2022, 6, 22, 0, 0, 0), "2022-06-22 00:00:00"), + (Percent::from_percent(11), (2022, 8, 17, 0, 0, 0), "2022-08-17 00:00:00"), + ]; + + ExtBuilder::default() + .existential_deposit(1) + .build() + .execute_with(|| { + // Check current schedule. + let schedule = VestingSchedule::::get(); + let schedule_len: u32 = ::MaxScheduleLength::get(); + assert_eq!(schedule.len(), schedule_len as usize); + + //Check percentage. + assert_eq!( + schedule + .iter() + .map(|(p, _)| p) + .fold(Percent::from_percent(0), |acc, p| acc.saturating_add(*p)), + Percent::from_percent(100) + ); + + for ((p, s), ds) in schedule.iter().zip(default_schedule.iter()) { + let dt = Utc + .ymd(ds.1 .0, ds.1 .1, ds.1 .2) + .and_hms(ds.1 .3, ds.1 .4, ds.1 .5); + + // Check each percentage is correct. + assert_eq!(ds.0, *p); + // Check datetime is correct. + assert_eq!(dt.format("%Y-%m-%d %H:%M:%S").to_string(), ds.2); + // Check timestamp is correct. + assert_eq!(dt.timestamp() as u64, *s); + } + }); } diff --git a/pallets/vesting/src/weights.rs b/pallets/vesting/src/weights.rs index 7d089a4c9..a11c57771 100644 --- a/pallets/vesting/src/weights.rs +++ b/pallets/vesting/src/weights.rs @@ -44,70 +44,70 @@ use sp_std::marker::PhantomData; /// Weight functions needed for calamari_vesting. pub trait WeightInfo { - fn update_vesting_schedule() -> Weight; - fn vest() -> Weight; - fn vested_transfer() -> Weight; + fn update_vesting_schedule() -> Weight; + fn vest() -> Weight; + fn vested_transfer() -> Weight; } /// Weights for calamari_vesting using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { - // Storage: CalamariVesting VestingSchedule (r:1 w:1) - // Storage: Timestamp Now (r:1 w:0) - fn update_vesting_schedule() -> Weight { - (47_829_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Timestamp Now (r:1 w:0) - // Storage: CalamariVesting VestingSchedule (r:1 w:0) - // Storage: CalamariVesting VestingBalances (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn vest() -> Weight { - (110_048_000 as Weight) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: CalamariVesting VestingBalances (r:1 w:1) - // Storage: System Account (r:1 w:1) - // Storage: Timestamp Now (r:1 w:0) - // Storage: CalamariVesting VestingSchedule (r:1 w:0) - // Storage: Balances Locks (r:1 w:1) - fn vested_transfer() -> Weight { - (216_897_000 as Weight) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } + // Storage: CalamariVesting VestingSchedule (r:1 w:1) + // Storage: Timestamp Now (r:1 w:0) + fn update_vesting_schedule() -> Weight { + (47_829_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Timestamp Now (r:1 w:0) + // Storage: CalamariVesting VestingSchedule (r:1 w:0) + // Storage: CalamariVesting VestingBalances (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn vest() -> Weight { + (110_048_000 as Weight) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: CalamariVesting VestingBalances (r:1 w:1) + // Storage: System Account (r:1 w:1) + // Storage: Timestamp Now (r:1 w:0) + // Storage: CalamariVesting VestingSchedule (r:1 w:0) + // Storage: Balances Locks (r:1 w:1) + fn vested_transfer() -> Weight { + (216_897_000 as Weight) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: CalamariVesting VestingSchedule (r:1 w:1) - // Storage: Timestamp Now (r:1 w:0) - fn update_vesting_schedule() -> Weight { - (47_829_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Timestamp Now (r:1 w:0) - // Storage: CalamariVesting VestingSchedule (r:1 w:0) - // Storage: CalamariVesting VestingBalances (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn vest() -> Weight { - (110_048_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: CalamariVesting VestingBalances (r:1 w:1) - // Storage: System Account (r:1 w:1) - // Storage: Timestamp Now (r:1 w:0) - // Storage: CalamariVesting VestingSchedule (r:1 w:0) - // Storage: Balances Locks (r:1 w:1) - fn vested_transfer() -> Weight { - (216_897_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } + // Storage: CalamariVesting VestingSchedule (r:1 w:1) + // Storage: Timestamp Now (r:1 w:0) + fn update_vesting_schedule() -> Weight { + (47_829_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Timestamp Now (r:1 w:0) + // Storage: CalamariVesting VestingSchedule (r:1 w:0) + // Storage: CalamariVesting VestingBalances (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn vest() -> Weight { + (110_048_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: CalamariVesting VestingBalances (r:1 w:1) + // Storage: System Account (r:1 w:1) + // Storage: Timestamp Now (r:1 w:0) + // Storage: CalamariVesting VestingSchedule (r:1 w:0) + // Storage: Balances Locks (r:1 w:1) + fn vested_transfer() -> Weight { + (216_897_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } } diff --git a/primitives/Cargo.toml b/primitives/Cargo.toml index e083204f4..5080da9fc 100644 --- a/primitives/Cargo.toml +++ b/primitives/Cargo.toml @@ -1,59 +1,59 @@ [package] authors = ['Manta Network'] -name = "manta-primitives" -version = '3.2.0' edition = "2021" homepage = 'https://manta.network' license = 'GPL-3.0' +name = "manta-primitives" repository = 'https://github.com/Manta-Network/Manta/' +version = '3.2.0' [package.metadata.docs.rs] targets = ['x86_64-unknown-linux-gnu'] [dependencies] codec = { package = "parity-scale-codec", version = '3.0.0', default-features = false } -scale-info = { version = "2.0.0", default-features = false, features = [ "derive" ] } -smallvec = "1.8.0" log = "0.4.16" +scale-info = { version = "2.0.0", default-features = false, features = ["derive"] } +smallvec = "1.8.0" # manta-rs dependencies manta-accounting = { git = "https://github.com/manta-network/manta-rs.git", tag = "v0.5.0", default-features = false } # Substrate primitives +frame-benchmarking = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18", default-features = false, optional = true } frame-support = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } frame-system = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } -frame-benchmarking = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18", default-features = false, optional = true } sp-consensus-aura = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } sp-core = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } -sp-std = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } sp-io = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } sp-runtime = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } -xcm-executor = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } +sp-std = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } xcm = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } xcm-builder = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } +xcm-executor = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } [features] default = ["std"] +runtime-benchmarks = [ + "frame-benchmarking", + 'frame-support/runtime-benchmarks', + 'frame-system/runtime-benchmarks', + 'xcm-builder/runtime-benchmarks', +] std = [ - 'codec/std', - 'sp-consensus-aura/std', - 'scale-info/std', - 'sp-io/std', - 'sp-std/std', - 'manta-accounting/std', - 'log/std', - 'frame-support/std', - 'frame-system/std', - 'sp-consensus-aura/std', - 'sp-core/std', - 'sp-runtime/std', - 'xcm-executor/std', - 'xcm-builder/std', - 'xcm/std', + 'codec/std', + 'sp-consensus-aura/std', + 'scale-info/std', + 'sp-io/std', + 'sp-std/std', + 'manta-accounting/std', + 'log/std', + 'frame-support/std', + 'frame-system/std', + 'sp-consensus-aura/std', + 'sp-core/std', + 'sp-runtime/std', + 'xcm-executor/std', + 'xcm-builder/std', + 'xcm/std', ] -runtime-benchmarks = [ - "frame-benchmarking", - 'frame-support/runtime-benchmarks', - 'frame-system/runtime-benchmarks', - 'xcm-builder/runtime-benchmarks', -] \ No newline at end of file diff --git a/primitives/src/assets.rs b/primitives/src/assets.rs index 219379dcf..651523564 100644 --- a/primitives/src/assets.rs +++ b/primitives/src/assets.rs @@ -16,169 +16,169 @@ ///! Manta/Calamari/Dolphin Asset use crate::{ - constants::DEFAULT_ASSET_ED, - types::{AssetId, Balance}, + constants::DEFAULT_ASSET_ED, + types::{AssetId, Balance}, }; use codec::{Codec, Decode, Encode}; use frame_support::{ - pallet_prelude::Get, - traits::tokens::{ - currency::Currency, - fungible::Inspect as FungibleInspect, - fungibles::{Inspect as FungiblesInspect, Mutate, Transfer}, - DepositConsequence, ExistenceRequirement, WithdrawConsequence, - }, - Parameter, + pallet_prelude::Get, + traits::tokens::{ + currency::Currency, + fungible::Inspect as FungibleInspect, + fungibles::{Inspect as FungiblesInspect, Mutate, Transfer}, + DepositConsequence, ExistenceRequirement, WithdrawConsequence, + }, + Parameter, }; use scale_info::TypeInfo; use sp_core::H160; use sp_runtime::{traits::Member, DispatchError, DispatchResult}; use sp_std::{borrow::Borrow, marker::PhantomData, prelude::Vec}; use xcm::{ - v1::{Junctions, MultiLocation}, - VersionedMultiLocation, + v1::{Junctions, MultiLocation}, + VersionedMultiLocation, }; /// The minimal interface of asset metadata pub trait AssetMetadata { - /// Returns the minimum balance to hold this asset - fn min_balance(&self) -> Balance; + /// Returns the minimum balance to hold this asset + fn min_balance(&self) -> Balance; - /// Returns a boolean value indicating whether this asset needs an existential deposit - fn is_sufficient(&self) -> bool; + /// Returns a boolean value indicating whether this asset needs an existential deposit + fn is_sufficient(&self) -> bool; } /// The registrar trait: defines the interface of creating an asset in the asset implementation /// layer. We may revisit this interface design (e.g. add change asset interface). However, change /// in StorageMetadata should be rare. pub trait AssetRegistrar> { - /// Create an new asset. - /// - /// * `asset_id`: the asset id to be created - /// * `min_balance`: the minimum balance to hold this asset - /// * `metadata`: the metadata that the implementation layer stores - /// * `is_sufficient`: whether this asset can be used as reserve asset, - /// to the first approximation. More specifically, Whether a non-zero balance of this asset - /// is deposit of sufficient value to account for the state bloat associated with its - /// balance storage. If set to `true`, then non-zero balances may be stored without a - /// `consumer` reference (and thus an ED in the Balances pallet or whatever else is used to - /// control user-account state growth). - fn create_asset( - asset_id: AssetId, - min_balance: Balance, - metadata: T::StorageMetadata, - is_sufficient: bool, - ) -> DispatchResult; - - /// Update asset metadata by `AssetId`. - /// - /// * `asset_id`: the asset id to be created. - /// * `metadata`: the metadata that the implementation layer stores. - fn update_asset_metadata(asset_id: AssetId, metadata: T::StorageMetadata) -> DispatchResult; + /// Create an new asset. + /// + /// * `asset_id`: the asset id to be created + /// * `min_balance`: the minimum balance to hold this asset + /// * `metadata`: the metadata that the implementation layer stores + /// * `is_sufficient`: whether this asset can be used as reserve asset, + /// to the first approximation. More specifically, Whether a non-zero balance of this asset + /// is deposit of sufficient value to account for the state bloat associated with its + /// balance storage. If set to `true`, then non-zero balances may be stored without a + /// `consumer` reference (and thus an ED in the Balances pallet or whatever else is used to + /// control user-account state growth). + fn create_asset( + asset_id: AssetId, + min_balance: Balance, + metadata: T::StorageMetadata, + is_sufficient: bool, + ) -> DispatchResult; + + /// Update asset metadata by `AssetId`. + /// + /// * `asset_id`: the asset id to be created. + /// * `metadata`: the metadata that the implementation layer stores. + fn update_asset_metadata(asset_id: AssetId, metadata: T::StorageMetadata) -> DispatchResult; } pub trait AssetConfig: 'static + Eq + Clone where - C: frame_system::Config, + C: frame_system::Config, { - /// The AssetId that the non-native asset starts from. - /// A typical configuration is 8, so that asset 0 - 7 is reserved. - type StartNonNativeAssetId: Get; + /// The AssetId that the non-native asset starts from. + /// A typical configuration is 8, so that asset 0 - 7 is reserved. + type StartNonNativeAssetId: Get; - /// Dummy Asset ID, a typical configuration is 0. - type DummyAssetId: Get; + /// Dummy Asset ID, a typical configuration is 0. + type DummyAssetId: Get; - /// The Native Asset Id, a typical configuration is 1. - type NativeAssetId: Get; + /// The Native Asset Id, a typical configuration is 1. + type NativeAssetId: Get; - /// Native Asset Location - type NativeAssetLocation: Get; + /// Native Asset Location + type NativeAssetLocation: Get; - /// Native Asset Metadata - type NativeAssetMetadata: Get; + /// Native Asset Metadata + type NativeAssetMetadata: Get; - /// The trait we use to register Assets and mint assets - type AssetRegistrar: AssetRegistrar; + /// The trait we use to register Assets and mint assets + type AssetRegistrar: AssetRegistrar; - /// Metadata type that required in token storage: e.g. AssetMetadata in Pallet-Assets. - type StorageMetadata: Member + Parameter + Default + From; + /// Metadata type that required in token storage: e.g. AssetMetadata in Pallet-Assets. + type StorageMetadata: Member + Parameter + Default + From; - /// The Asset Metadata type stored in this pallet. - type AssetRegistrarMetadata: Member + Parameter + Codec + Default + AssetMetadata; + /// The Asset Metadata type stored in this pallet. + type AssetRegistrarMetadata: Member + Parameter + Codec + Default + AssetMetadata; - /// The AssetLocation type: could be just a thin wrapper of MultiLocation - type AssetLocation: Member - + Parameter - + Default - + TypeInfo - + From - + Into>; + /// The AssetLocation type: could be just a thin wrapper of MultiLocation + type AssetLocation: Member + + Parameter + + Default + + TypeInfo + + From + + Into>; - /// The Fungible ledger implementation of this trait - type FungibleLedger: FungibleLedger; + /// The Fungible ledger implementation of this trait + type FungibleLedger: FungibleLedger; } /// The metadata of a Manta Asset #[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)] pub struct AssetRegistrarMetadata { - pub name: Vec, - pub symbol: Vec, - pub decimals: u8, - pub evm_address: Option, - pub is_frozen: bool, - pub min_balance: Balance, - /// `is_sufficient`: Whether a non-zero balance of this asset is deposit of sufficient - /// value to account for the state bloat associated with its balance storage. If set to - /// `true`, then non-zero balances may be stored without a `consumer` reference (and thus - /// an ED in the Balances pallet or whatever else is used to control user-account state - /// growth). - /// For example, if is_sufficient set to `false`, a fresh account cannot receive XCM tokens. - pub is_sufficient: bool, + pub name: Vec, + pub symbol: Vec, + pub decimals: u8, + pub evm_address: Option, + pub is_frozen: bool, + pub min_balance: Balance, + /// `is_sufficient`: Whether a non-zero balance of this asset is deposit of sufficient + /// value to account for the state bloat associated with its balance storage. If set to + /// `true`, then non-zero balances may be stored without a `consumer` reference (and thus + /// an ED in the Balances pallet or whatever else is used to control user-account state + /// growth). + /// For example, if is_sufficient set to `false`, a fresh account cannot receive XCM tokens. + pub is_sufficient: bool, } impl Default for AssetRegistrarMetadata { - fn default() -> Self { - Self { - name: b"Dolphin".to_vec(), - symbol: b"DOL".to_vec(), - decimals: 12, - evm_address: None, - is_frozen: false, - min_balance: DEFAULT_ASSET_ED, - is_sufficient: true, - } - } + fn default() -> Self { + Self { + name: b"Dolphin".to_vec(), + symbol: b"DOL".to_vec(), + decimals: 12, + evm_address: None, + is_frozen: false, + min_balance: DEFAULT_ASSET_ED, + is_sufficient: true, + } + } } impl AssetMetadata for AssetRegistrarMetadata { - fn min_balance(&self) -> Balance { - self.min_balance - } + fn min_balance(&self) -> Balance { + self.min_balance + } - fn is_sufficient(&self) -> bool { - self.is_sufficient - } + fn is_sufficient(&self) -> bool { + self.is_sufficient + } } /// Asset storage metadata /// Currently, `AssetStorageMetadata` is stored at `pallet-asset`. #[derive(Clone, Default, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)] pub struct AssetStorageMetadata { - pub name: Vec, - pub symbol: Vec, - pub decimals: u8, - pub is_frozen: bool, + pub name: Vec, + pub symbol: Vec, + pub decimals: u8, + pub is_frozen: bool, } impl From for AssetStorageMetadata { - fn from(source: AssetRegistrarMetadata) -> Self { - Self { - name: source.name, - symbol: source.symbol, - decimals: source.decimals, - is_frozen: source.is_frozen, - } - } + fn from(source: AssetRegistrarMetadata) -> Self { + Self { + name: source.name, + symbol: source.symbol, + decimals: source.decimals, + is_frozen: source.is_frozen, + } + } } /// Asset Location @@ -186,154 +186,154 @@ impl From for AssetStorageMetadata { pub struct AssetLocation(pub VersionedMultiLocation); impl Default for AssetLocation { - fn default() -> Self { - Self(VersionedMultiLocation::V1(MultiLocation { - parents: 0, - interior: Junctions::Here, - })) - } + fn default() -> Self { + Self(VersionedMultiLocation::V1(MultiLocation { + parents: 0, + interior: Junctions::Here, + })) + } } impl From for AssetLocation { - /// Converts a [`MultiLocation`] into an [`AssetLocation`]. - /// - /// # Safety - /// - /// This method does not guarantee that the output [`AssetLocation`] is registered, i.e. has a - /// valid [`AssetId`]. - fn from(location: MultiLocation) -> Self { - AssetLocation(VersionedMultiLocation::V1(location)) - } + /// Converts a [`MultiLocation`] into an [`AssetLocation`]. + /// + /// # Safety + /// + /// This method does not guarantee that the output [`AssetLocation`] is registered, i.e. has a + /// valid [`AssetId`]. + fn from(location: MultiLocation) -> Self { + AssetLocation(VersionedMultiLocation::V1(location)) + } } impl From for Option { - /// Converts an [`AssetLocation`] into an optional [`MultiLocation`], returning `None` if it - /// represents a native asset. - fn from(location: AssetLocation) -> Self { - match location { - AssetLocation(VersionedMultiLocation::V1(location)) => Some(location), - _ => None, - } - } + /// Converts an [`AssetLocation`] into an optional [`MultiLocation`], returning `None` if it + /// represents a native asset. + fn from(location: AssetLocation) -> Self { + match location { + AssetLocation(VersionedMultiLocation::V1(location)) => Some(location), + _ => None, + } + } } /// Defines the trait to obtain a generic AssetId pub trait AssetIdLocationGetter { - /// Gets the [`AssetLocation`] from [`AssetId`]. - fn get_asset_location(asset_id: AssetId) -> Option; + /// Gets the [`AssetLocation`] from [`AssetId`]. + fn get_asset_location(asset_id: AssetId) -> Option; - /// Gets the [`AssetId`] from [`AssetLocation`]. - fn get_asset_id(loc: &AssetLocation) -> Option; + /// Gets the [`AssetId`] from [`AssetLocation`]. + fn get_asset_id(loc: &AssetLocation) -> Option; } /// Defines the units per second charged given an `AssetId`. pub trait UnitsToWeightRatio { - /// Get units per second from asset id - fn get_units_per_second(asset_id: AssetId) -> Option; + /// Get units per second from asset id + fn get_units_per_second(asset_id: AssetId) -> Option; } /// Converter struct implementing `Convert`. /// This enforce the `AssetInfoGetter` implements `AssetIdLocationGetter` pub struct AssetIdLocationConvert( - PhantomData<(AssetLocation, AssetInfoGetter)>, + PhantomData<(AssetLocation, AssetInfoGetter)>, ); impl xcm_executor::traits::Convert - for AssetIdLocationConvert + for AssetIdLocationConvert where - AssetLocation: From + Into> + Clone, - AssetInfoGetter: AssetIdLocationGetter, + AssetLocation: From + Into> + Clone, + AssetInfoGetter: AssetIdLocationGetter, { - fn convert_ref(loc: impl Borrow) -> Result { - AssetInfoGetter::get_asset_id(&loc.borrow().clone().into()).ok_or(()) - } - - fn reverse_ref(id: impl Borrow) -> Result { - AssetInfoGetter::get_asset_location(*id.borrow()) - .and_then(Into::into) - .ok_or(()) - } + fn convert_ref(loc: impl Borrow) -> Result { + AssetInfoGetter::get_asset_id(&loc.borrow().clone().into()).ok_or(()) + } + + fn reverse_ref(id: impl Borrow) -> Result { + AssetInfoGetter::get_asset_location(*id.borrow()) + .and_then(Into::into) + .ok_or(()) + } } /// Fungible Ledger Error #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum FungibleLedgerError { - /// Invalid Asset Id - InvalidAssetId, + /// Invalid Asset Id + InvalidAssetId, - /// Deposit couldn't happen due to the amount being too low. This is usually because the - /// account doesn't yet exist and the deposit wouldn't bring it to at least the minimum needed - /// for existence. - BelowMinimum, + /// Deposit couldn't happen due to the amount being too low. This is usually because the + /// account doesn't yet exist and the deposit wouldn't bring it to at least the minimum needed + /// for existence. + BelowMinimum, - /// Deposit cannot happen since the account cannot be created (usually because it's a consumer - /// and there exists no provider reference). - CannotCreate, + /// Deposit cannot happen since the account cannot be created (usually because it's a consumer + /// and there exists no provider reference). + CannotCreate, - /// The asset is unknown. Usually because an `AssetId` has been presented which doesn't exist - /// on the system. - UnknownAsset, + /// The asset is unknown. Usually because an `AssetId` has been presented which doesn't exist + /// on the system. + UnknownAsset, - /// An overflow would occur. This is practically unexpected, but could happen in test systems - /// with extremely small balance types or balances that approach the max value of the balance - /// type. - Overflow, + /// An overflow would occur. This is practically unexpected, but could happen in test systems + /// with extremely small balance types or balances that approach the max value of the balance + /// type. + Overflow, - /// There has been an underflow in the system. This is indicative of a corrupt state and - /// likely unrecoverable. - Underflow, + /// There has been an underflow in the system. This is indicative of a corrupt state and + /// likely unrecoverable. + Underflow, - /// Account continued in existence. - /// Not enough of the funds in the account are unavailable for withdrawal. - Frozen, + /// Account continued in existence. + /// Not enough of the funds in the account are unavailable for withdrawal. + Frozen, - /// Account balance would reduce to zero, potentially destroying it. The parameter is the - /// amount of balance which is destroyed. - ReducedToZero(Balance), + /// Account balance would reduce to zero, potentially destroying it. The parameter is the + /// amount of balance which is destroyed. + ReducedToZero(Balance), - /// Withdraw could not happen since the amount to be withdrawn is less than the total funds in - /// the account. - NoFunds, + /// Withdraw could not happen since the amount to be withdrawn is less than the total funds in + /// the account. + NoFunds, - /// The withdraw would mean the account dying when it needs to exist (usually because it is a - /// provider and there are consumer references on it). - WouldDie, + /// The withdraw would mean the account dying when it needs to exist (usually because it is a + /// provider and there are consumer references on it). + WouldDie, - /// Unable to Mint an Asset - InvalidMint(DispatchError), + /// Unable to Mint an Asset + InvalidMint(DispatchError), - /// Unable to Transfer an Asset - InvalidTransfer(DispatchError), + /// Unable to Transfer an Asset + InvalidTransfer(DispatchError), } impl FungibleLedgerError { - /// Converts a deposit `consequence` into a [`FungibleLedgerError`] or into `Ok(())` when the - /// value of `consequence` is [`Success`](DepositConsequence::Success). - #[inline] - pub fn from_deposit(consequence: DepositConsequence) -> Result<(), Self> { - Err(match consequence { - DepositConsequence::BelowMinimum => Self::BelowMinimum, - DepositConsequence::CannotCreate => Self::CannotCreate, - DepositConsequence::Overflow => Self::Overflow, - DepositConsequence::UnknownAsset => Self::UnknownAsset, - DepositConsequence::Success => return Ok(()), - }) - } - - /// Converts a withdraw `consequence` into a [`FungibleLedgerError`] or into `Ok(())` when the - /// value of `consequence` is [`Success`](WithdrawConsequence::Success). - #[inline] - pub fn from_withdraw(consequence: WithdrawConsequence) -> Result<(), Self> { - Err(match consequence { - WithdrawConsequence::Frozen => Self::Frozen, - WithdrawConsequence::NoFunds => Self::NoFunds, - WithdrawConsequence::Overflow => Self::Overflow, - WithdrawConsequence::Underflow => Self::Underflow, - WithdrawConsequence::ReducedToZero(balance) => Self::ReducedToZero(balance), - WithdrawConsequence::UnknownAsset => Self::UnknownAsset, - WithdrawConsequence::WouldDie => Self::WouldDie, - WithdrawConsequence::Success => return Ok(()), - }) - } + /// Converts a deposit `consequence` into a [`FungibleLedgerError`] or into `Ok(())` when the + /// value of `consequence` is [`Success`](DepositConsequence::Success). + #[inline] + pub fn from_deposit(consequence: DepositConsequence) -> Result<(), Self> { + Err(match consequence { + DepositConsequence::BelowMinimum => Self::BelowMinimum, + DepositConsequence::CannotCreate => Self::CannotCreate, + DepositConsequence::Overflow => Self::Overflow, + DepositConsequence::UnknownAsset => Self::UnknownAsset, + DepositConsequence::Success => return Ok(()), + }) + } + + /// Converts a withdraw `consequence` into a [`FungibleLedgerError`] or into `Ok(())` when the + /// value of `consequence` is [`Success`](WithdrawConsequence::Success). + #[inline] + pub fn from_withdraw(consequence: WithdrawConsequence) -> Result<(), Self> { + Err(match consequence { + WithdrawConsequence::Frozen => Self::Frozen, + WithdrawConsequence::NoFunds => Self::NoFunds, + WithdrawConsequence::Overflow => Self::Overflow, + WithdrawConsequence::Underflow => Self::Underflow, + WithdrawConsequence::ReducedToZero(balance) => Self::ReducedToZero(balance), + WithdrawConsequence::UnknownAsset => Self::UnknownAsset, + WithdrawConsequence::WouldDie => Self::WouldDie, + WithdrawConsequence::Success => return Ok(()), + }) + } } /// Unified Interface for Fungible Assets @@ -344,136 +344,136 @@ impl FungibleLedgerError { /// [`fungibles`]: frame_support::traits::tokens::fungibles pub trait FungibleLedger where - C: frame_system::Config, + C: frame_system::Config, { - /// Checks if an asset id is valid and returning and [`Error`](FungibleLedgerError) otherwise. - fn ensure_valid(asset_id: AssetId) -> Result<(), FungibleLedgerError>; - - /// Check whether `account` can increase its balance by `amount` in the given `asset_id`. - fn can_deposit( - asset_id: AssetId, - account: &C::AccountId, - amount: Balance, - ) -> Result<(), FungibleLedgerError>; - - /// Check whether `account` can decrease its balance by `amount` in the given `asset_id`. - fn can_withdraw( - asset_id: AssetId, - account: &C::AccountId, - amount: Balance, - ) -> Result<(), FungibleLedgerError>; - - /// Mints `amount` of an asset with the given `asset_id` to `beneficiary`. - fn mint( - asset_id: AssetId, - beneficiary: &C::AccountId, - amount: Balance, - ) -> Result<(), FungibleLedgerError>; - - /// Performs a transfer from `source` to `destination` of - fn transfer( - asset_id: AssetId, - source: &C::AccountId, - destination: &C::AccountId, - amount: Balance, - ) -> Result<(), FungibleLedgerError>; + /// Checks if an asset id is valid and returning and [`Error`](FungibleLedgerError) otherwise. + fn ensure_valid(asset_id: AssetId) -> Result<(), FungibleLedgerError>; + + /// Check whether `account` can increase its balance by `amount` in the given `asset_id`. + fn can_deposit( + asset_id: AssetId, + account: &C::AccountId, + amount: Balance, + ) -> Result<(), FungibleLedgerError>; + + /// Check whether `account` can decrease its balance by `amount` in the given `asset_id`. + fn can_withdraw( + asset_id: AssetId, + account: &C::AccountId, + amount: Balance, + ) -> Result<(), FungibleLedgerError>; + + /// Mints `amount` of an asset with the given `asset_id` to `beneficiary`. + fn mint( + asset_id: AssetId, + beneficiary: &C::AccountId, + amount: Balance, + ) -> Result<(), FungibleLedgerError>; + + /// Performs a transfer from `source` to `destination` of + fn transfer( + asset_id: AssetId, + source: &C::AccountId, + destination: &C::AccountId, + amount: Balance, + ) -> Result<(), FungibleLedgerError>; } /// Concrete Fungible Ledger Implementation pub struct ConcreteFungibleLedger { - /// Type Parameter Marker - __: PhantomData<(C, A, Native, NonNative)>, + /// Type Parameter Marker + __: PhantomData<(C, A, Native, NonNative)>, } impl FungibleLedger for ConcreteFungibleLedger where - C: frame_system::Config, - A: AssetConfig, - Native: FungibleInspect - + Currency, - NonNative: FungiblesInspect - + Mutate - + Transfer, + C: frame_system::Config, + A: AssetConfig, + Native: FungibleInspect + + Currency, + NonNative: FungiblesInspect + + Mutate + + Transfer, { - #[inline] - fn ensure_valid(asset_id: AssetId) -> Result<(), FungibleLedgerError> { - if asset_id >= A::StartNonNativeAssetId::get() || asset_id == A::NativeAssetId::get() { - Ok(()) - } else { - Err(FungibleLedgerError::InvalidAssetId) - } - } - - #[inline] - fn can_deposit( - asset_id: AssetId, - account: &C::AccountId, - amount: Balance, - ) -> Result<(), FungibleLedgerError> { - Self::ensure_valid(asset_id)?; - FungibleLedgerError::from_deposit(if asset_id == A::NativeAssetId::get() { - >::can_deposit(account, amount) - } else { - >::can_deposit(asset_id, account, amount) - }) - } - - #[inline] - fn can_withdraw( - asset_id: AssetId, - account: &C::AccountId, - amount: Balance, - ) -> Result<(), FungibleLedgerError> { - Self::ensure_valid(asset_id)?; - FungibleLedgerError::from_withdraw(if asset_id == A::NativeAssetId::get() { - >::can_withdraw(account, amount) - } else { - >::can_withdraw(asset_id, account, amount) - }) - } - - #[inline] - fn mint( - asset_id: AssetId, - beneficiary: &C::AccountId, - amount: Balance, - ) -> Result<(), FungibleLedgerError> { - Self::ensure_valid(asset_id)?; - Self::can_deposit(asset_id, beneficiary, amount)?; - if asset_id == A::NativeAssetId::get() { - >::deposit_creating(beneficiary, amount); - } else { - >::mint_into(asset_id, beneficiary, amount) - .map_err(FungibleLedgerError::InvalidMint)?; - } - Ok(()) - } - - #[inline] - fn transfer( - asset_id: AssetId, - source: &C::AccountId, - destination: &C::AccountId, - amount: Balance, - ) -> Result<(), FungibleLedgerError> { - Self::ensure_valid(asset_id)?; - if asset_id == A::NativeAssetId::get() { - >::transfer( - source, - destination, - amount, - ExistenceRequirement::KeepAlive, - ) - } else { - >::transfer( - asset_id, - source, - destination, - amount, - true, - ) - .map(|_| ()) - } - .map_err(FungibleLedgerError::InvalidTransfer) - } + #[inline] + fn ensure_valid(asset_id: AssetId) -> Result<(), FungibleLedgerError> { + if asset_id >= A::StartNonNativeAssetId::get() || asset_id == A::NativeAssetId::get() { + Ok(()) + } else { + Err(FungibleLedgerError::InvalidAssetId) + } + } + + #[inline] + fn can_deposit( + asset_id: AssetId, + account: &C::AccountId, + amount: Balance, + ) -> Result<(), FungibleLedgerError> { + Self::ensure_valid(asset_id)?; + FungibleLedgerError::from_deposit(if asset_id == A::NativeAssetId::get() { + >::can_deposit(account, amount) + } else { + >::can_deposit(asset_id, account, amount) + }) + } + + #[inline] + fn can_withdraw( + asset_id: AssetId, + account: &C::AccountId, + amount: Balance, + ) -> Result<(), FungibleLedgerError> { + Self::ensure_valid(asset_id)?; + FungibleLedgerError::from_withdraw(if asset_id == A::NativeAssetId::get() { + >::can_withdraw(account, amount) + } else { + >::can_withdraw(asset_id, account, amount) + }) + } + + #[inline] + fn mint( + asset_id: AssetId, + beneficiary: &C::AccountId, + amount: Balance, + ) -> Result<(), FungibleLedgerError> { + Self::ensure_valid(asset_id)?; + Self::can_deposit(asset_id, beneficiary, amount)?; + if asset_id == A::NativeAssetId::get() { + >::deposit_creating(beneficiary, amount); + } else { + >::mint_into(asset_id, beneficiary, amount) + .map_err(FungibleLedgerError::InvalidMint)?; + } + Ok(()) + } + + #[inline] + fn transfer( + asset_id: AssetId, + source: &C::AccountId, + destination: &C::AccountId, + amount: Balance, + ) -> Result<(), FungibleLedgerError> { + Self::ensure_valid(asset_id)?; + if asset_id == A::NativeAssetId::get() { + >::transfer( + source, + destination, + amount, + ExistenceRequirement::KeepAlive, + ) + } else { + >::transfer( + asset_id, + source, + destination, + amount, + true, + ) + .map(|_| ()) + } + .map_err(FungibleLedgerError::InvalidTransfer) + } } diff --git a/primitives/src/constants.rs b/primitives/src/constants.rs index fc82e2feb..4f22bf8b2 100644 --- a/primitives/src/constants.rs +++ b/primitives/src/constants.rs @@ -33,20 +33,20 @@ pub const DOLPHIN_TOKEN_SYMBOL: &str = "DOL"; /// Manta parachain time-related pub mod time { - use crate::types::{BlockNumber, Moment}; - /// This determines the average expected block time that we are targeting. Blocks will be - /// produced at a minimum duration defined by `SLOT_DURATION`. `SLOT_DURATION` is picked up by - /// `pallet_timestamp` which is in turn picked up by `pallet_aura` to implement `fn - /// slot_duration()`. - /// - /// Change this to adjust the block time. - pub const MILLISECS_PER_BLOCK: Moment = 12_000; // 12s - pub const SLOT_DURATION: Moment = MILLISECS_PER_BLOCK; - - // Time is measured by number of blocks. - pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber); - pub const HOURS: BlockNumber = MINUTES * 60; - pub const DAYS: BlockNumber = HOURS * 24; + use crate::types::{BlockNumber, Moment}; + /// This determines the average expected block time that we are targeting. Blocks will be + /// produced at a minimum duration defined by `SLOT_DURATION`. `SLOT_DURATION` is picked up by + /// `pallet_timestamp` which is in turn picked up by `pallet_aura` to implement `fn + /// slot_duration()`. + /// + /// Change this to adjust the block time. + pub const MILLISECS_PER_BLOCK: Moment = 12_000; // 12s + pub const SLOT_DURATION: Moment = MILLISECS_PER_BLOCK; + + // Time is measured by number of blocks. + pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber); + pub const HOURS: BlockNumber = MINUTES * 60; + pub const DAYS: BlockNumber = HOURS * 24; } pub const ASSET_STRING_LIMIT: u32 = 50; diff --git a/primitives/src/helpers.rs b/primitives/src/helpers.rs index 73f5836b4..9cb5fdea9 100644 --- a/primitives/src/helpers.rs +++ b/primitives/src/helpers.rs @@ -20,16 +20,16 @@ use sp_runtime::traits::{IdentifyAccount, Verify}; /// Helper function to generate a crypto pair from seed pub fn get_pair_from_seed(seed: &str) -> ::Public { - TPublic::Pair::from_string(&format!("//{}", seed), None) - .expect("static values are valid; qed") - .public() + TPublic::Pair::from_string(&format!("//{}", seed), None) + .expect("static values are valid; qed") + .public() } /// Generate collator keys from seed. /// /// This function's return type must always match the session keys of the chain in tuple format. pub fn get_collator_keys_from_seed(seed: &str) -> AuraId { - get_pair_from_seed::(seed) + get_pair_from_seed::(seed) } type AccountPublic = ::Signer; @@ -37,7 +37,7 @@ type AccountPublic = ::Signer; /// Helper function to generate an account ID from seed pub fn get_account_id_from_seed(seed: &str) -> AccountId where - AccountPublic: From<::Public>, + AccountPublic: From<::Public>, { - AccountPublic::from(get_pair_from_seed::(seed)).into_account() + AccountPublic::from(get_pair_from_seed::(seed)).into_account() } diff --git a/primitives/src/xcm.rs b/primitives/src/xcm.rs index fe02d8fc8..0e2806db2 100644 --- a/primitives/src/xcm.rs +++ b/primitives/src/xcm.rs @@ -18,278 +18,278 @@ use sp_runtime::traits::{CheckedConversion, Convert, Zero}; use sp_std::marker::PhantomData; use frame_support::{ - pallet_prelude::Get, - traits::fungibles::Mutate, - weights::{constants::WEIGHT_PER_SECOND, Weight}, + pallet_prelude::Get, + traits::fungibles::Mutate, + weights::{constants::WEIGHT_PER_SECOND, Weight}, }; use crate::assets::{AssetIdLocationGetter, UnitsToWeightRatio}; use xcm::{ - latest::{prelude::Concrete, Error as XcmError}, - v1::{ - AssetId as xcmAssetId, Fungibility, - Fungibility::*, - Junction::{AccountId32, Parachain}, - Junctions::*, - MultiAsset, MultiLocation, NetworkId, - }, + latest::{prelude::Concrete, Error as XcmError}, + v1::{ + AssetId as xcmAssetId, Fungibility, + Fungibility::*, + Junction::{AccountId32, Parachain}, + Junctions::*, + MultiAsset, MultiLocation, NetworkId, + }, }; use xcm_builder::TakeRevenue; use xcm_executor::traits::{FilterAssetLocation, MatchesFungible, MatchesFungibles, WeightTrader}; pub trait Reserve { - /// Returns assets reserve location. - fn reserve(&self) -> Option; + /// Returns assets reserve location. + fn reserve(&self) -> Option; } // Takes the chain part of a MultiAsset impl Reserve for MultiAsset { - fn reserve(&self) -> Option { - // We only care about concrete location now. - if let xcmAssetId::Concrete(location) = self.id.clone() { - let first_interior = location.first_interior(); - let parents = location.parent_count(); - match (parents, first_interior) { - (0, Some(Parachain(id))) => Some(MultiLocation::new(0, X1(Parachain(*id)))), - (1, Some(Parachain(id))) => Some(MultiLocation::new(1, X1(Parachain(*id)))), - (1, _) => Some(MultiLocation::parent()), - _ => None, - } - } else { - None - } - } + fn reserve(&self) -> Option { + // We only care about concrete location now. + if let xcmAssetId::Concrete(location) = self.id.clone() { + let first_interior = location.first_interior(); + let parents = location.parent_count(); + match (parents, first_interior) { + (0, Some(Parachain(id))) => Some(MultiLocation::new(0, X1(Parachain(*id)))), + (1, Some(Parachain(id))) => Some(MultiLocation::new(1, X1(Parachain(*id)))), + (1, _) => Some(MultiLocation::parent()), + _ => None, + } + } else { + None + } + } } /// A `FilterAssetLocation` implementation. Filters multi native assets whose /// reserve is same with `origin`. pub struct MultiNativeAsset; impl FilterAssetLocation for MultiNativeAsset { - fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool { - asset.reserve().map(|r| r == *origin).unwrap_or(false) - } + fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool { + asset.reserve().map(|r| r == *origin).unwrap_or(false) + } } pub struct AccountIdToMultiLocation(PhantomData); impl Convert for AccountIdToMultiLocation where - AccountId: Into<[u8; 32]> + Clone, + AccountId: Into<[u8; 32]> + Clone, { - fn convert(account: AccountId) -> MultiLocation { - MultiLocation { - parents: 0, - interior: X1(AccountId32 { - network: NetworkId::Any, - id: account.into(), - }), - } - } + fn convert(account: AccountId) -> MultiLocation { + MultiLocation { + parents: 0, + interior: X1(AccountId32 { + network: NetworkId::Any, + id: account.into(), + }), + } + } } // This trader defines how to charge a XCM call. // This takes the first fungible asset, and takes UnitPerSecondGetter that implements // UnitToWeightRatio trait. pub struct FirstAssetTrader< - AssetId: Clone, - AssetLocation: From + Clone, - AssetIdInfoGetter: UnitsToWeightRatio + AssetIdLocationGetter, - R: TakeRevenue, + AssetId: Clone, + AssetLocation: From + Clone, + AssetIdInfoGetter: UnitsToWeightRatio + AssetIdLocationGetter, + R: TakeRevenue, > { - weight: Weight, - refund_cache: Option<(MultiLocation, u128, u128)>, - __: sp_std::marker::PhantomData<(AssetId, AssetLocation, AssetIdInfoGetter, R)>, + weight: Weight, + refund_cache: Option<(MultiLocation, u128, u128)>, + __: sp_std::marker::PhantomData<(AssetId, AssetLocation, AssetIdInfoGetter, R)>, } impl< - AssetId: Clone, - AssetLocation: From + Clone, - AssetIdInfoGetter: UnitsToWeightRatio + AssetIdLocationGetter, - R: TakeRevenue, - > WeightTrader for FirstAssetTrader + AssetId: Clone, + AssetLocation: From + Clone, + AssetIdInfoGetter: UnitsToWeightRatio + AssetIdLocationGetter, + R: TakeRevenue, + > WeightTrader for FirstAssetTrader { - fn new() -> Self { - FirstAssetTrader { - weight: Zero::zero(), - refund_cache: None, - __: sp_std::marker::PhantomData, - } - } + fn new() -> Self { + FirstAssetTrader { + weight: Zero::zero(), + refund_cache: None, + __: sp_std::marker::PhantomData, + } + } - /// buy weight for XCM execution. We always return `TooExpensive` error if this fails. - fn buy_weight( - &mut self, - weight: Weight, - payment: xcm_executor::Assets, - ) -> Result { - log::debug!( - target: "FirstAssetTrader::buy_weight", - "weight: {:?}, payment: {:?}", - weight, - payment - ); + /// buy weight for XCM execution. We always return `TooExpensive` error if this fails. + fn buy_weight( + &mut self, + weight: Weight, + payment: xcm_executor::Assets, + ) -> Result { + log::debug!( + target: "FirstAssetTrader::buy_weight", + "weight: {:?}, payment: {:?}", + weight, + payment + ); - let first_asset = payment.fungible_assets_iter().next().ok_or({ - log::debug!( - target: "FirstAssetTrader::buy_weight", - "no assets in payment: {:?}", - payment, - ); - XcmError::TooExpensive - })?; + let first_asset = payment.fungible_assets_iter().next().ok_or({ + log::debug!( + target: "FirstAssetTrader::buy_weight", + "no assets in payment: {:?}", + payment, + ); + XcmError::TooExpensive + })?; - // Check the first asset - match (first_asset.id, first_asset.fun) { - (xcmAssetId::Concrete(id), Fungibility::Fungible(_)) => { - let asset_loc: AssetLocation = id.clone().into(); + // Check the first asset + match (first_asset.id, first_asset.fun) { + (xcmAssetId::Concrete(id), Fungibility::Fungible(_)) => { + let asset_loc: AssetLocation = id.clone().into(); - let asset_id = AssetIdInfoGetter::get_asset_id(&asset_loc).ok_or({ - log::debug!( - target: "FirstAssetTrader::buy_weight", - "asset_id missing for asset_loc with id: {:?}", - id, - ); - XcmError::TooExpensive - })?; + let asset_id = AssetIdInfoGetter::get_asset_id(&asset_loc).ok_or({ + log::debug!( + target: "FirstAssetTrader::buy_weight", + "asset_id missing for asset_loc with id: {:?}", + id, + ); + XcmError::TooExpensive + })?; - let units_per_second = - AssetIdInfoGetter::get_units_per_second(asset_id).ok_or({ - log::debug!( - target: "FirstAssetTrader::buy_weight", - "units_per_second missing for asset with id: {:?}", - id, - ); - XcmError::TooExpensive - })?; + let units_per_second = + AssetIdInfoGetter::get_units_per_second(asset_id).ok_or({ + log::debug!( + target: "FirstAssetTrader::buy_weight", + "units_per_second missing for asset with id: {:?}", + id, + ); + XcmError::TooExpensive + })?; - let amount = units_per_second * (weight as u128) / (WEIGHT_PER_SECOND as u128); - // we don't need to proceed if amount is zero. - // This is very useful in tests. - if amount.is_zero() { - return Ok(payment); - } - let required = MultiAsset { - fun: Fungibility::Fungible(amount), - id: xcmAssetId::Concrete(id.clone()), - }; + let amount = units_per_second * (weight as u128) / (WEIGHT_PER_SECOND as u128); + // we don't need to proceed if amount is zero. + // This is very useful in tests. + if amount.is_zero() { + return Ok(payment); + } + let required = MultiAsset { + fun: Fungibility::Fungible(amount), + id: xcmAssetId::Concrete(id.clone()), + }; - log::debug!( - target: "FirstAssetTrader::buy_weight", - "payment: {:?}, required: {:?}", - payment, - required, - ); - let unused = payment.checked_sub(required).map_err(|_| { - log::debug!( - target: "FirstAssetTrader::buy_weight", - "not enough required assets in payment", - ); - XcmError::TooExpensive - })?; - self.weight = self.weight.saturating_add(weight); + log::debug!( + target: "FirstAssetTrader::buy_weight", + "payment: {:?}, required: {:?}", + payment, + required, + ); + let unused = payment.checked_sub(required).map_err(|_| { + log::debug!( + target: "FirstAssetTrader::buy_weight", + "not enough required assets in payment", + ); + XcmError::TooExpensive + })?; + self.weight = self.weight.saturating_add(weight); - // In case the asset matches the one the trader already stored before, add - // to later refund + // In case the asset matches the one the trader already stored before, add + // to later refund - // Else we are always going to subtract the weight if we can, but we latter do - // not refund it + // Else we are always going to subtract the weight if we can, but we latter do + // not refund it - // In short, we only refund on the asset the trader first successfully was able - // to pay for an execution - let new_asset = match self.refund_cache.clone() { - Some((prev_id, prev_amount, units_per_second)) => { - if prev_id == id { - Some((id, prev_amount.saturating_add(amount), units_per_second)) - } else { - None - } - } - None => Some((id, amount, units_per_second)), - }; + // In short, we only refund on the asset the trader first successfully was able + // to pay for an execution + let new_asset = match self.refund_cache.clone() { + Some((prev_id, prev_amount, units_per_second)) => { + if prev_id == id { + Some((id, prev_amount.saturating_add(amount), units_per_second)) + } else { + None + } + } + None => Some((id, amount, units_per_second)), + }; - // Due to the trait bound, we can only refund one asset. - if let Some(new_asset) = new_asset { - self.weight = self.weight.saturating_add(weight); - self.refund_cache = Some(new_asset); - }; - Ok(unused) - } - _ => { - log::debug!( - target: "FirstAssetTrader::buy_weight", - "no matching xcmAssetId for first_asset in payment: {:?}", - payment, - ); + // Due to the trait bound, we can only refund one asset. + if let Some(new_asset) = new_asset { + self.weight = self.weight.saturating_add(weight); + self.refund_cache = Some(new_asset); + }; + Ok(unused) + } + _ => { + log::debug!( + target: "FirstAssetTrader::buy_weight", + "no matching xcmAssetId for first_asset in payment: {:?}", + payment, + ); - Err(XcmError::TooExpensive) - } - } - } + Err(XcmError::TooExpensive) + } + } + } - fn refund_weight(&mut self, weight: Weight) -> Option { - if let Some((id, prev_amount, units_per_second)) = self.refund_cache.clone() { - let weight = weight.min(self.weight); - self.weight -= weight; - let amount = units_per_second * (weight as u128) / (WEIGHT_PER_SECOND as u128); - self.refund_cache = Some(( - id.clone(), - prev_amount.saturating_sub(amount), - units_per_second, - )); - Some(MultiAsset { - fun: Fungibility::Fungible(amount), - id: xcmAssetId::Concrete(id), - }) - } else { - None - } - } + fn refund_weight(&mut self, weight: Weight) -> Option { + if let Some((id, prev_amount, units_per_second)) = self.refund_cache.clone() { + let weight = weight.min(self.weight); + self.weight -= weight; + let amount = units_per_second * (weight as u128) / (WEIGHT_PER_SECOND as u128); + self.refund_cache = Some(( + id.clone(), + prev_amount.saturating_sub(amount), + units_per_second, + )); + Some(MultiAsset { + fun: Fungibility::Fungible(amount), + id: xcmAssetId::Concrete(id), + }) + } else { + None + } + } } /// Handle spent fees, deposit them as defined by R impl< - AssetId: Clone, - AssetLocation: From + Clone, - AssetIdInfoGetter: UnitsToWeightRatio + AssetIdLocationGetter, - R: TakeRevenue, - > Drop for FirstAssetTrader + AssetId: Clone, + AssetLocation: From + Clone, + AssetIdInfoGetter: UnitsToWeightRatio + AssetIdLocationGetter, + R: TakeRevenue, + > Drop for FirstAssetTrader { - fn drop(&mut self) { - if let Some((id, amount, _)) = self.refund_cache.clone() { - R::take_revenue((id, amount).into()); - } - } + fn drop(&mut self) { + if let Some((id, amount, _)) = self.refund_cache.clone() { + R::take_revenue((id, amount).into()); + } + } } /// XCM fee depositor to which we implement the TakeRevenue trait /// It receives a fungibles::Mutate implemented argument, a matcher to convert MultiAsset into /// AssetId and amount, and the fee receiver account pub struct XcmFeesToAccount( - PhantomData<(Assets, Matcher, AccountId, ReceiverAccount)>, + PhantomData<(Assets, Matcher, AccountId, ReceiverAccount)>, ); impl< - Assets: Mutate, - Matcher: MatchesFungibles, - AccountId: Clone, - ReceiverAccount: Get, - > TakeRevenue for XcmFeesToAccount + Assets: Mutate, + Matcher: MatchesFungibles, + AccountId: Clone, + ReceiverAccount: Get, + > TakeRevenue for XcmFeesToAccount { - fn take_revenue(revenue: MultiAsset) { - match Matcher::matches_fungibles(&revenue) { - Ok((asset_id, amount)) => { - if !amount.is_zero() { - Assets::mint_into(asset_id, &ReceiverAccount::get(), amount) - .map_err( - |err| log::debug!(target: "manta-xcm", "mint_into failed with {:?}", err), - ) - .ok(); - } - } - Err(_) => log::debug!( - target: "manta-xcm", - "take revenue failed matching fungible" - ), - } - } + fn take_revenue(revenue: MultiAsset) { + match Matcher::matches_fungibles(&revenue) { + Ok((asset_id, amount)) => { + if !amount.is_zero() { + Assets::mint_into(asset_id, &ReceiverAccount::get(), amount) + .map_err( + |err| log::debug!(target: "manta-xcm", "mint_into failed with {:?}", err), + ) + .ok(); + } + } + Err(_) => log::debug!( + target: "manta-xcm", + "take revenue failed matching fungible" + ), + } + } } /// Manta's `MatchFungible` implementation. @@ -300,15 +300,15 @@ impl< pub struct IsNativeConcrete(PhantomData); impl MatchesFungible for IsNativeConcrete where - T: Get, - Balance: TryFrom, + T: Get, + Balance: TryFrom, { - fn matches_fungible(a: &MultiAsset) -> Option { - if let (Fungible(ref amount), Concrete(ref location)) = (&a.fun, &a.id) { - if location == &T::get() || MultiLocation::is_here(location) { - return CheckedConversion::checked_from(*amount); - } - } - None - } + fn matches_fungible(a: &MultiAsset) -> Option { + if let (Fungible(ref amount), Concrete(ref location)) = (&a.fun, &a.id) { + if location == &T::get() || MultiLocation::is_here(location) { + return CheckedConversion::checked_from(*amount); + } + } + None + } } diff --git a/runtime/calamari/Cargo.toml b/runtime/calamari/Cargo.toml index fad3aa01e..eeb496aa2 100644 --- a/runtime/calamari/Cargo.toml +++ b/runtime/calamari/Cargo.toml @@ -9,8 +9,8 @@ version = '3.2.0' [dependencies] codec = { package = "parity-scale-codec", version = '3.0.0', default-features = false, features = ["derive", "max-encoded-len"] } -log = { version = "0.4.16", default-features = false } hex-literal = { version = '0.3.4', optional = true } +log = { version = "0.4.16", default-features = false } scale-info = { version = "2.0.0", default-features = false, features = ["derive"] } serde = { version = '1.0.137', features = ['derive'], optional = true } smallvec = "1.8.0" @@ -32,62 +32,62 @@ sp-version = { git = 'https://github.com/paritytech/substrate.git', default-feat # Substrate frames frame-benchmarking = { git = 'https://github.com/paritytech/substrate.git', default-features = false, optional = true, branch = "polkadot-v0.9.18" } -frame-system-benchmarking = { git = 'https://github.com/paritytech/substrate.git', default-features = false, optional = true, branch = "polkadot-v0.9.18" } frame-executive = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } frame-support = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } frame-system = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } +frame-system-benchmarking = { git = 'https://github.com/paritytech/substrate.git', default-features = false, optional = true, branch = "polkadot-v0.9.18" } frame-system-rpc-runtime-api = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } frame-try-runtime = { git = "https://github.com/paritytech/substrate.git", default-features = false, optional = true, branch = "polkadot-v0.9.18" } # Substrate pallets +pallet-assets = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } pallet-aura = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } pallet-authorship = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } pallet-balances = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } -pallet-preimage = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } +pallet-collective = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } +pallet-democracy = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } +pallet-membership = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } pallet-multisig = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } +pallet-preimage = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } +pallet-scheduler = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } pallet-session = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } pallet-timestamp = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } pallet-transaction-payment = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } pallet-transaction-payment-rpc-runtime-api = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } -pallet-utility = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } -pallet-collective = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } -pallet-democracy = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } -pallet-scheduler = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } -pallet-membership = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } pallet-treasury = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } -pallet-assets = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } +pallet-utility = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } # Cumulus dependencies cumulus-pallet-aura-ext = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } +cumulus-pallet-dmp-queue = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } cumulus-pallet-parachain-system = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } +cumulus-pallet-session-benchmarking = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, optional = true, branch = "polkadot-v0.9.18" } +cumulus-pallet-xcm = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } +cumulus-pallet-xcmp-queue = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } cumulus-primitives-core = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } cumulus-primitives-timestamp = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } cumulus-primitives-utility = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } -cumulus-pallet-dmp-queue = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } -cumulus-pallet-session-benchmarking = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, optional = true, branch = "polkadot-v0.9.18" } -cumulus-pallet-xcmp-queue = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } -cumulus-pallet-xcm = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } parachain-info = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } # Polkadot dependencies +pallet-xcm = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } +polkadot-parachain = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } polkadot-primitives = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } polkadot-runtime-common = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } -polkadot-parachain = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } xcm = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } xcm-builder = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } xcm-executor = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } -pallet-xcm = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } # Third party (vendored) dependencies -orml-traits = { git = "https://github.com/manta-network/open-runtime-module-library.git", default-features = false, rev="7e2f985" } -orml-xtokens = { git = "https://github.com/manta-network/open-runtime-module-library.git", default-features = false, rev="7e2f985" } +orml-traits = { git = "https://github.com/manta-network/open-runtime-module-library.git", default-features = false, rev = "7e2f985" } +orml-xtokens = { git = "https://github.com/manta-network/open-runtime-module-library.git", default-features = false, rev = "7e2f985" } # Self dependencies -manta-primitives = { path = '../../primitives', default-features = false } calamari-vesting = { path = '../../pallets/vesting', default-features = false } manta-collator-selection = { path = '../../pallets/collator-selection', default-features = false } -pallet-tx-pause = { path = '../../pallets/tx-pause', default-features = false } +manta-primitives = { path = '../../primitives', default-features = false } pallet-asset-manager = { path = '../../pallets/asset-manager', default-features = false } +pallet-tx-pause = { path = '../../pallets/tx-pause', default-features = false } runtime-common = { path = '../common', default-features = false } [package.metadata.docs.rs] @@ -97,120 +97,120 @@ targets = ['x86_64-unknown-linux-gnu'] substrate-wasm-builder = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } [dev-dependencies] -serde_json = "1.0" reqwest = { version = "0.11", features = ["blocking"] } +serde_json = "1.0" [features] default = ['std'] -try-runtime = [ - 'frame-executive/try-runtime', - 'frame-try-runtime', - 'frame-system/try-runtime', - 'pallet-aura/try-runtime', - 'pallet-authorship/try-runtime', - 'pallet-balances/try-runtime', - 'pallet-preimage/try-runtime', - 'pallet-multisig/try-runtime', - 'pallet-session/try-runtime', - 'pallet-timestamp/try-runtime', - 'pallet-transaction-payment/try-runtime', - 'pallet-utility/try-runtime', - 'pallet-collective/try-runtime', - 'pallet-democracy/try-runtime', - 'pallet-scheduler/try-runtime', - 'pallet-membership/try-runtime', - 'pallet-treasury/try-runtime', - 'pallet-assets/try-runtime', - 'pallet-tx-pause/try-runtime', - 'pallet-asset-manager/try-runtime', -] runtime-benchmarks = [ - 'cumulus-pallet-session-benchmarking/runtime-benchmarks', - 'hex-literal', - 'sp-runtime/runtime-benchmarks', - 'xcm-builder/runtime-benchmarks', - 'frame-benchmarking', - 'frame-system-benchmarking', - 'frame-support/runtime-benchmarks', - 'frame-system/runtime-benchmarks', - 'pallet-balances/runtime-benchmarks', - 'pallet-multisig/runtime-benchmarks', - 'pallet-utility/runtime-benchmarks', - 'pallet-timestamp/runtime-benchmarks', - 'pallet-xcm/runtime-benchmarks', - 'manta-collator-selection/runtime-benchmarks', - 'pallet-collective/runtime-benchmarks', - 'pallet-democracy/runtime-benchmarks', - 'pallet-scheduler/runtime-benchmarks', - 'pallet-membership/runtime-benchmarks', - 'calamari-vesting/runtime-benchmarks', - 'pallet-tx-pause/runtime-benchmarks', - 'pallet-treasury/runtime-benchmarks', - 'pallet-preimage/runtime-benchmarks', - 'pallet-assets/runtime-benchmarks', - 'pallet-asset-manager/runtime-benchmarks', - 'cumulus-pallet-xcmp-queue/runtime-benchmarks', + 'cumulus-pallet-session-benchmarking/runtime-benchmarks', + 'hex-literal', + 'sp-runtime/runtime-benchmarks', + 'xcm-builder/runtime-benchmarks', + 'frame-benchmarking', + 'frame-system-benchmarking', + 'frame-support/runtime-benchmarks', + 'frame-system/runtime-benchmarks', + 'pallet-balances/runtime-benchmarks', + 'pallet-multisig/runtime-benchmarks', + 'pallet-utility/runtime-benchmarks', + 'pallet-timestamp/runtime-benchmarks', + 'pallet-xcm/runtime-benchmarks', + 'manta-collator-selection/runtime-benchmarks', + 'pallet-collective/runtime-benchmarks', + 'pallet-democracy/runtime-benchmarks', + 'pallet-scheduler/runtime-benchmarks', + 'pallet-membership/runtime-benchmarks', + 'calamari-vesting/runtime-benchmarks', + 'pallet-tx-pause/runtime-benchmarks', + 'pallet-treasury/runtime-benchmarks', + 'pallet-preimage/runtime-benchmarks', + 'pallet-assets/runtime-benchmarks', + 'pallet-asset-manager/runtime-benchmarks', + 'cumulus-pallet-xcmp-queue/runtime-benchmarks', +] +try-runtime = [ + 'frame-executive/try-runtime', + 'frame-try-runtime', + 'frame-system/try-runtime', + 'pallet-aura/try-runtime', + 'pallet-authorship/try-runtime', + 'pallet-balances/try-runtime', + 'pallet-preimage/try-runtime', + 'pallet-multisig/try-runtime', + 'pallet-session/try-runtime', + 'pallet-timestamp/try-runtime', + 'pallet-transaction-payment/try-runtime', + 'pallet-utility/try-runtime', + 'pallet-collective/try-runtime', + 'pallet-democracy/try-runtime', + 'pallet-scheduler/try-runtime', + 'pallet-membership/try-runtime', + 'pallet-treasury/try-runtime', + 'pallet-assets/try-runtime', + 'pallet-tx-pause/try-runtime', + 'pallet-asset-manager/try-runtime', ] # Set timing constants (e.g. session period) to faster versions to speed up testing. fast-runtime = [] std = [ - 'codec/std', - 'serde', - 'sp-consensus-aura/std', - 'pallet-aura/std', - 'sp-api/std', - 'sp-std/std', - 'sp-io/std', - 'sp-core/std', - 'sp-runtime/std', - 'sp-version/std', - 'sp-offchain/std', - 'sp-session/std', - 'sp-block-builder/std', - 'sp-transaction-pool/std', - 'sp-inherents/std', - 'frame-support/std', - 'frame-executive/std', - 'frame-system/std', - 'frame-system-rpc-runtime-api/std', - 'frame-try-runtime/std', - 'pallet-authorship/std', - 'pallet-balances/std', - 'pallet-multisig/std', - 'pallet-preimage/std', - 'pallet-utility/std', - 'pallet-transaction-payment-rpc-runtime-api/std', - 'pallet-timestamp/std', - 'pallet-session/std', - 'pallet-xcm/std', - 'pallet-transaction-payment/std', - 'pallet-treasury/std', - 'pallet-collective/std', - 'pallet-democracy/std', - 'pallet-scheduler/std', - 'pallet-membership/std', - 'manta-primitives/std', - 'runtime-common/std', - 'parachain-info/std', - "cumulus-pallet-aura-ext/std", - 'cumulus-pallet-parachain-system/std', - 'cumulus-pallet-dmp-queue/std', - "cumulus-pallet-xcmp-queue/std", - "cumulus-pallet-xcm/std", - "cumulus-primitives-core/std", - "cumulus-primitives-timestamp/std", - "cumulus-primitives-utility/std", - 'xcm/std', - 'xcm-builder/std', - 'xcm-executor/std', - 'polkadot-runtime-common/std', - 'polkadot-primitives/std', - 'manta-collator-selection/std', - 'calamari-vesting/std', - 'pallet-tx-pause/std', - 'pallet-treasury/std', - 'pallet-assets/std', - 'pallet-asset-manager/std', - 'orml-traits/std', - 'orml-xtokens/std', + 'codec/std', + 'serde', + 'sp-consensus-aura/std', + 'pallet-aura/std', + 'sp-api/std', + 'sp-std/std', + 'sp-io/std', + 'sp-core/std', + 'sp-runtime/std', + 'sp-version/std', + 'sp-offchain/std', + 'sp-session/std', + 'sp-block-builder/std', + 'sp-transaction-pool/std', + 'sp-inherents/std', + 'frame-support/std', + 'frame-executive/std', + 'frame-system/std', + 'frame-system-rpc-runtime-api/std', + 'frame-try-runtime/std', + 'pallet-authorship/std', + 'pallet-balances/std', + 'pallet-multisig/std', + 'pallet-preimage/std', + 'pallet-utility/std', + 'pallet-transaction-payment-rpc-runtime-api/std', + 'pallet-timestamp/std', + 'pallet-session/std', + 'pallet-xcm/std', + 'pallet-transaction-payment/std', + 'pallet-treasury/std', + 'pallet-collective/std', + 'pallet-democracy/std', + 'pallet-scheduler/std', + 'pallet-membership/std', + 'manta-primitives/std', + 'runtime-common/std', + 'parachain-info/std', + "cumulus-pallet-aura-ext/std", + 'cumulus-pallet-parachain-system/std', + 'cumulus-pallet-dmp-queue/std', + "cumulus-pallet-xcmp-queue/std", + "cumulus-pallet-xcm/std", + "cumulus-primitives-core/std", + "cumulus-primitives-timestamp/std", + "cumulus-primitives-utility/std", + 'xcm/std', + 'xcm-builder/std', + 'xcm-executor/std', + 'polkadot-runtime-common/std', + 'polkadot-primitives/std', + 'manta-collator-selection/std', + 'calamari-vesting/std', + 'pallet-tx-pause/std', + 'pallet-treasury/std', + 'pallet-assets/std', + 'pallet-asset-manager/std', + 'orml-traits/std', + 'orml-xtokens/std', ] diff --git a/runtime/calamari/build.rs b/runtime/calamari/build.rs index 46ffd8513..ebc6ed273 100644 --- a/runtime/calamari/build.rs +++ b/runtime/calamari/build.rs @@ -17,9 +17,9 @@ use substrate_wasm_builder::WasmBuilder; fn main() { - WasmBuilder::new() - .with_current_project() - .export_heap_base() - .import_memory() - .build() + WasmBuilder::new() + .with_current_project() + .export_heap_base() + .import_memory() + .build() } diff --git a/runtime/calamari/src/assets_config.rs b/runtime/calamari/src/assets_config.rs index ae4113116..602699210 100644 --- a/runtime/calamari/src/assets_config.rs +++ b/runtime/calamari/src/assets_config.rs @@ -15,17 +15,17 @@ // along with Manta. If not, see . use super::{ - weights, xcm_config::SelfReserve, AssetManager, Assets, Balances, Event, - NativeTokenExistentialDeposit, Origin, Runtime, + weights, xcm_config::SelfReserve, AssetManager, Assets, Balances, Event, + NativeTokenExistentialDeposit, Origin, Runtime, }; use manta_primitives::{ - assets::{ - AssetConfig, AssetLocation, AssetRegistrar, AssetRegistrarMetadata, AssetStorageMetadata, - ConcreteFungibleLedger, - }, - constants::{ASSET_MANAGER_PALLET_ID, CALAMARI_DECIMAL}, - types::{AccountId, AssetId, Balance}, + assets::{ + AssetConfig, AssetLocation, AssetRegistrar, AssetRegistrarMetadata, AssetStorageMetadata, + ConcreteFungibleLedger, + }, + constants::{ASSET_MANAGER_PALLET_ID, CALAMARI_DECIMAL}, + types::{AccountId, AssetId, Balance}, }; use frame_support::{pallet_prelude::DispatchResult, parameter_types, traits::ConstU32, PalletId}; @@ -35,110 +35,110 @@ use frame_system::EnsureRoot; use xcm::VersionedMultiLocation; parameter_types! { - // Does not really matter as this will be only called by root - pub const AssetDeposit: Balance = 0; - pub const AssetAccountDeposit: Balance = 0; - pub const ApprovalDeposit: Balance = 0; - pub const MetadataDepositBase: Balance = 0; - pub const MetadataDepositPerByte: Balance = 0; + // Does not really matter as this will be only called by root + pub const AssetDeposit: Balance = 0; + pub const AssetAccountDeposit: Balance = 0; + pub const ApprovalDeposit: Balance = 0; + pub const MetadataDepositBase: Balance = 0; + pub const MetadataDepositPerByte: Balance = 0; } impl pallet_assets::Config for Runtime { - type Event = Event; - type Balance = Balance; - type AssetId = AssetId; - type Currency = Balances; - type ForceOrigin = EnsureRoot; - type AssetDeposit = AssetDeposit; - type AssetAccountDeposit = AssetAccountDeposit; - type MetadataDepositBase = MetadataDepositBase; - type MetadataDepositPerByte = MetadataDepositPerByte; - type ApprovalDeposit = ApprovalDeposit; - type StringLimit = ConstU32<50>; - type Freezer = (); - type Extra = (); - type WeightInfo = weights::pallet_assets::SubstrateWeight; + type Event = Event; + type Balance = Balance; + type AssetId = AssetId; + type Currency = Balances; + type ForceOrigin = EnsureRoot; + type AssetDeposit = AssetDeposit; + type AssetAccountDeposit = AssetAccountDeposit; + type MetadataDepositBase = MetadataDepositBase; + type MetadataDepositPerByte = MetadataDepositPerByte; + type ApprovalDeposit = ApprovalDeposit; + type StringLimit = ConstU32<50>; + type Freezer = (); + type Extra = (); + type WeightInfo = weights::pallet_assets::SubstrateWeight; } pub struct CalamariAssetRegistrar; impl AssetRegistrar for CalamariAssetRegistrar { - fn create_asset( - asset_id: AssetId, - min_balance: Balance, - metadata: AssetStorageMetadata, - is_sufficient: bool, - ) -> DispatchResult { - Assets::force_create( - Origin::root(), - asset_id, - sp_runtime::MultiAddress::Id(AssetManager::account_id()), - is_sufficient, - min_balance, - )?; + fn create_asset( + asset_id: AssetId, + min_balance: Balance, + metadata: AssetStorageMetadata, + is_sufficient: bool, + ) -> DispatchResult { + Assets::force_create( + Origin::root(), + asset_id, + sp_runtime::MultiAddress::Id(AssetManager::account_id()), + is_sufficient, + min_balance, + )?; - Assets::force_set_metadata( - Origin::root(), - asset_id, - metadata.name, - metadata.symbol, - metadata.decimals, - metadata.is_frozen, - ) - } + Assets::force_set_metadata( + Origin::root(), + asset_id, + metadata.name, + metadata.symbol, + metadata.decimals, + metadata.is_frozen, + ) + } - fn update_asset_metadata(asset_id: AssetId, metadata: AssetStorageMetadata) -> DispatchResult { - Assets::force_set_metadata( - Origin::root(), - asset_id, - metadata.name, - metadata.symbol, - metadata.decimals, - metadata.is_frozen, - ) - } + fn update_asset_metadata(asset_id: AssetId, metadata: AssetStorageMetadata) -> DispatchResult { + Assets::force_set_metadata( + Origin::root(), + asset_id, + metadata.name, + metadata.symbol, + metadata.decimals, + metadata.is_frozen, + ) + } } parameter_types! { - pub const DummyAssetId: AssetId = 0; - pub const NativeAssetId: AssetId = 1; - pub const StartNonNativeAssetId: AssetId = 8; - pub NativeAssetLocation: AssetLocation = AssetLocation( - VersionedMultiLocation::V1(SelfReserve::get())); - pub NativeAssetMetadata: AssetRegistrarMetadata = AssetRegistrarMetadata { - name: b"Calamari".to_vec(), - symbol: b"KMA".to_vec(), - decimals: CALAMARI_DECIMAL, - min_balance: NativeTokenExistentialDeposit::get(), - evm_address: None, - is_frozen: false, - is_sufficient: true, - }; - pub const AssetManagerPalletId: PalletId = ASSET_MANAGER_PALLET_ID; + pub const DummyAssetId: AssetId = 0; + pub const NativeAssetId: AssetId = 1; + pub const StartNonNativeAssetId: AssetId = 8; + pub NativeAssetLocation: AssetLocation = AssetLocation( + VersionedMultiLocation::V1(SelfReserve::get())); + pub NativeAssetMetadata: AssetRegistrarMetadata = AssetRegistrarMetadata { + name: b"Calamari".to_vec(), + symbol: b"KMA".to_vec(), + decimals: CALAMARI_DECIMAL, + min_balance: NativeTokenExistentialDeposit::get(), + evm_address: None, + is_frozen: false, + is_sufficient: true, + }; + pub const AssetManagerPalletId: PalletId = ASSET_MANAGER_PALLET_ID; } pub type CalamariConcreteFungibleLedger = - ConcreteFungibleLedger; + ConcreteFungibleLedger; #[derive(Clone, Eq, PartialEq)] pub struct CalamariAssetConfig; impl AssetConfig for CalamariAssetConfig { - type DummyAssetId = DummyAssetId; - type NativeAssetId = NativeAssetId; - type StartNonNativeAssetId = StartNonNativeAssetId; - type AssetRegistrarMetadata = AssetRegistrarMetadata; - type NativeAssetLocation = NativeAssetLocation; - type NativeAssetMetadata = NativeAssetMetadata; - type StorageMetadata = AssetStorageMetadata; - type AssetLocation = AssetLocation; - type AssetRegistrar = CalamariAssetRegistrar; - type FungibleLedger = CalamariConcreteFungibleLedger; + type DummyAssetId = DummyAssetId; + type NativeAssetId = NativeAssetId; + type StartNonNativeAssetId = StartNonNativeAssetId; + type AssetRegistrarMetadata = AssetRegistrarMetadata; + type NativeAssetLocation = NativeAssetLocation; + type NativeAssetMetadata = NativeAssetMetadata; + type StorageMetadata = AssetStorageMetadata; + type AssetLocation = AssetLocation; + type AssetRegistrar = CalamariAssetRegistrar; + type FungibleLedger = CalamariConcreteFungibleLedger; } impl pallet_asset_manager::Config for Runtime { - type Event = Event; - type AssetConfig = CalamariAssetConfig; - type ModifierOrigin = EnsureRoot; - type PalletId = AssetManagerPalletId; - type WeightInfo = weights::pallet_asset_manager::SubstrateWeight; + type Event = Event; + type AssetConfig = CalamariAssetConfig; + type ModifierOrigin = EnsureRoot; + type PalletId = AssetManagerPalletId; + type WeightInfo = weights::pallet_asset_manager::SubstrateWeight; } diff --git a/runtime/calamari/src/currency.rs b/runtime/calamari/src/currency.rs index 6a5b95765..b4f37b69c 100644 --- a/runtime/calamari/src/currency.rs +++ b/runtime/calamari/src/currency.rs @@ -23,5 +23,5 @@ pub const mKMA: Balance = KMA / 1_000; // 9 decimal, milli-MA pub const uKMA: Balance = KMA / 1_000_000; // 6 decimal, micro-MA pub const fn deposit(items: u32, bytes: u32) -> Balance { - items as Balance * 15 * mKMA + (bytes as Balance) * 6 * mKMA // TODO: revisit the storage cost here + items as Balance * 15 * mKMA + (bytes as Balance) * 6 * mKMA // TODO: revisit the storage cost here } diff --git a/runtime/calamari/src/fee.rs b/runtime/calamari/src/fee.rs index ea5871d4e..f7033e1a6 100644 --- a/runtime/calamari/src/fee.rs +++ b/runtime/calamari/src/fee.rs @@ -15,7 +15,7 @@ // along with Manta. If not, see . use frame_support::weights::{ - WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial, + WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial, }; use manta_primitives::types::Balance; use smallvec::smallvec; @@ -42,197 +42,199 @@ pub const TIPS_PERCENTAGE_TO_TREASURY: u8 = 0; /// - Setting it to `1` will cause the literal `#[weight = x]` values to be charged. pub struct WeightToFee; impl WeightToFeePolynomial for WeightToFee { - type Balance = Balance; - fn polynomial() -> WeightToFeeCoefficients { - // Refer to the congested_chain_simulation() test for how to come up with the coefficient. - smallvec![WeightToFeeCoefficient { - coeff_integer: 5000u32.into(), - coeff_frac: Perbill::zero(), - negative: false, - degree: 1, - }] - } + type Balance = Balance; + fn polynomial() -> WeightToFeeCoefficients { + // Refer to the congested_chain_simulation() test for how to come up with the coefficient. + smallvec![WeightToFeeCoefficient { + coeff_integer: 5000u32.into(), + coeff_frac: Perbill::zero(), + negative: false, + degree: 1, + }] + } } #[cfg(test)] mod multiplier_tests { - use crate::{ - Call, Runtime, RuntimeBlockWeights as BlockWeights, System, TransactionPayment, KMA, - }; - use codec::Encode; - use frame_support::weights::{DispatchClass, Weight, WeightToFeePolynomial}; - use frame_system::WeightInfo; - use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment}; - use polkadot_runtime_common::{AdjustmentVariable, MinimumMultiplier, TargetBlockFullness}; - use sp_runtime::{ - traits::{Convert, One}, - FixedPointNumber, - }; - - fn run_with_system_weight(w: Weight, mut assertions: F) - where - F: FnMut() -> (), - { - let mut t: sp_io::TestExternalities = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap() - .into(); - t.execute_with(|| { - System::set_block_consumed_resources(w, 0); - assertions() - }); - } - - // update based on runtime impl. - fn runtime_multiplier_update(fm: Multiplier) -> Multiplier { - TargetedFeeAdjustment::< - Runtime, - TargetBlockFullness, - AdjustmentVariable, - MinimumMultiplier, - >::convert(fm) - } - - fn fetch_kma_price() -> Result { - let body = reqwest::blocking::get( - "https://api.coingecko.com/api/v3/simple/price?ids=calamari-network&vs_currencies=usd", - ) - .unwrap(); - let json_reply: serde_json::Value = serde_json::from_reader(body).unwrap(); - if let Some(price) = json_reply["calamari-network"]["usd"].as_f64() { - // CG API return: {"calamari-network":{"usd": 0.01092173}} - Ok(price as f32) - } else { - Err("KMA price not found in reply from Coingecko. API changed? Check https://www.coingecko.com/en/api/documentation") - } - } - - // Consider the daily cost to fully congest our network to be defined as: - // `target_daily_congestion_cost_usd = inclusion_fee * blocks_per_day * kma_price` - // Where: - // `inclusion_fee = fee_adjustment * (weight_to_fee_coeff * (block_weight ^ degree)) + base_fee + (weight_to_fee_coeff * length_fee)` - // Where: - // `fee_adjustment` and `weight_to_fee_coeff` are configurable in a runtime via `FeeMultiplierUpdate` and `WeightToFee` - // `fee_adjustment` is also variable depending on previous block's fullness - // We are also assuming `length_fee` is negligible for small TXs like a remark or a transfer. - // This test loops 1 day of parachain blocks (7200) and calculates accumulated fee if every block is almost full - #[test] - fn congested_chain_simulation() { - // Configure the target cost depending on the current state of the network. - let target_daily_congestion_cost_usd = 250000; - let kma_price = fetch_kma_price().unwrap(); - println!("KMA/USD price as read from CoinGecko = {}", kma_price); - let target_daily_congestion_cost_kma = - (target_daily_congestion_cost_usd as f32 * kma_price * KMA as f32) as u128; - - // `cargo test --package calamari-runtime --lib -- fee::multiplier_tests::congested_chain_simulation --exact --nocapture` to get some insight. - // almost full. The entire quota of normal transactions is taken. - let block_weight = BlockWeights::get() - .get(DispatchClass::Normal) - .max_total - .unwrap() - 10; - - // remark extrinsic is chosen arbitrarily for benchmark as a small, constant size TX. - let remark = Call::System(frame_system::Call::::remark_with_event { - remark: vec![1, 2, 3], - }); - let len: u32 = remark.clone().encode().len() as u32; - let remark_weight: Weight = - ::SystemWeightInfo::remark(len); - let max_number_of_remarks_per_block = (block_weight / remark_weight) as u128; - let per_byte = ::TransactionByteFee::get(); - // length fee. this is not adjusted. - let len_fee = - max_number_of_remarks_per_block.saturating_mul(per_byte.saturating_mul(len as u128)); - - let base_fee = max_number_of_remarks_per_block - * ::WeightToFee::calc( - &frame_support::weights::constants::ExtrinsicBaseWeight::get(), - ); - - run_with_system_weight(block_weight, || { - // initial value configured on module - let mut fee_adjustment = Multiplier::one(); - assert_eq!(fee_adjustment, TransactionPayment::next_fee_multiplier()); - let mut accumulated_fee: u128 = 0; - // Simulates 1 day of parachain blocks (12 seconds each) - for iteration in 0..7200 { - let next = runtime_multiplier_update(fee_adjustment); - // if no change or less, panic. This should never happen in this case. - if fee_adjustment >= next { - println!("final fee_adjustment: {}", fee_adjustment); - println!("final next: {}", next); - panic!("The fee should ever increase"); - } - fee_adjustment = next; - let fee = ::WeightToFee::calc( - &block_weight, - ); - - // base_fee and len_fee are not adjusted - let adjusted_fee = fee_adjustment.saturating_mul_acc_int(fee) + base_fee + len_fee; - accumulated_fee += adjusted_fee; - println!( - "Iteration {}, New fee_adjustment = {:?}. Adjusted Fee: {} KMA, Total Fee: {} KMA, Dollar Value: {}", - iteration, - fee_adjustment, - adjusted_fee / KMA, - accumulated_fee / KMA, - (accumulated_fee / KMA) as f32 * kma_price, - ); - } - - if accumulated_fee < target_daily_congestion_cost_kma { - panic!("The cost to fully congest our network should be over the target_daily_congestion_cost_kma after 1 day."); - } - }); - } - - #[test] - fn multiplier_can_grow_from_zero() { - let minimum_multiplier = polkadot_runtime_common::MinimumMultiplier::get(); - let target = polkadot_runtime_common::TargetBlockFullness::get() - * BlockWeights::get() - .get(DispatchClass::Normal) - .max_total - .unwrap(); - // if the min is too small, then this will not change, and we are doomed forever. - // the weight is 1/100th bigger than target. - run_with_system_weight(target * 101 / 100, || { - let next = polkadot_runtime_common::SlowAdjustingFeeUpdate::::convert( - minimum_multiplier, - ); - assert!( - next > minimum_multiplier, - "{:?} !>= {:?}", - next, - minimum_multiplier - ); - }) - } - - #[test] - #[ignore] // test runs for a very long time - fn multiplier_growth_simulator() { - // assume the multiplier is initially set to its minimum. We update it with values twice the - //target (target is 25%, thus 50%) and we see at which point it reaches 1. - let mut multiplier = polkadot_runtime_common::MinimumMultiplier::get(); - let block_weight = polkadot_runtime_common::TargetBlockFullness::get() - * BlockWeights::get() - .get(DispatchClass::Normal) - .max_total - .unwrap() * 2; - let mut blocks = 0; - while multiplier <= Multiplier::one() { - run_with_system_weight(block_weight, || { - let next = - polkadot_runtime_common::SlowAdjustingFeeUpdate::::convert(multiplier); - // ensure that it is growing as well. - assert!(next > multiplier, "{:?} !>= {:?}", next, multiplier); - multiplier = next; - }); - blocks += 1; - println!("block = {} multiplier {:?}", blocks, multiplier); - } - } + use crate::{ + Call, Runtime, RuntimeBlockWeights as BlockWeights, System, TransactionPayment, KMA, + }; + use codec::Encode; + use frame_support::weights::{DispatchClass, Weight, WeightToFeePolynomial}; + use frame_system::WeightInfo; + use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment}; + use polkadot_runtime_common::{AdjustmentVariable, MinimumMultiplier, TargetBlockFullness}; + use sp_runtime::{ + traits::{Convert, One}, + FixedPointNumber, + }; + + fn run_with_system_weight(w: Weight, mut assertions: F) + where + F: FnMut(), + { + let mut t: sp_io::TestExternalities = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap() + .into(); + t.execute_with(|| { + System::set_block_consumed_resources(w, 0); + assertions() + }); + } + + // update based on runtime impl. + fn runtime_multiplier_update(fm: Multiplier) -> Multiplier { + TargetedFeeAdjustment::< + Runtime, + TargetBlockFullness, + AdjustmentVariable, + MinimumMultiplier, + >::convert(fm) + } + + fn fetch_kma_price() -> Result { + let body = reqwest::blocking::get( + "https://api.coingecko.com/api/v3/simple/price?ids=calamari-network&vs_currencies=usd", + ) + .unwrap(); + let json_reply: serde_json::Value = serde_json::from_reader(body).unwrap(); + if let Some(price) = json_reply["calamari-network"]["usd"].as_f64() { + // CG API return: {"calamari-network":{"usd": 0.01092173}} + Ok(price as f32) + } else { + Err("KMA price not found in reply from Coingecko. API changed? Check https://www.coingecko.com/en/api/documentation") + } + } + + // Consider the daily cost to fully congest our network to be defined as: + // `target_daily_congestion_cost_usd = inclusion_fee * blocks_per_day * kma_price` + // Where: + // `inclusion_fee = fee_adjustment * (weight_to_fee_coeff * (block_weight ^ degree)) + base_fee + (weight_to_fee_coeff * length_fee)` + // Where: + // `fee_adjustment` and `weight_to_fee_coeff` are configurable in a runtime via `FeeMultiplierUpdate` and `WeightToFee` + // `fee_adjustment` is also variable depending on previous block's fullness + // We are also assuming `length_fee` is negligible for small TXs like a remark or a transfer. + // This test loops 1 day of parachain blocks (7200) and calculates accumulated fee if every block is almost full + #[test] + fn congested_chain_simulation() { + // Configure the target cost depending on the current state of the network. + let target_daily_congestion_cost_usd = 250000; + let kma_price = fetch_kma_price().unwrap(); + println!("KMA/USD price as read from CoinGecko = {}", kma_price); + let target_daily_congestion_cost_kma = + (target_daily_congestion_cost_usd as f32 * kma_price * KMA as f32) as u128; + + // `cargo test --package calamari-runtime --lib -- fee::multiplier_tests::congested_chain_simulation --exact --nocapture` to get some insight. + // almost full. The entire quota of normal transactions is taken. + let block_weight = BlockWeights::get() + .get(DispatchClass::Normal) + .max_total + .unwrap() + - 10; + + // remark extrinsic is chosen arbitrarily for benchmark as a small, constant size TX. + let remark = Call::System(frame_system::Call::::remark_with_event { + remark: vec![1, 2, 3], + }); + let len: u32 = remark.encode().len() as u32; + let remark_weight: Weight = + ::SystemWeightInfo::remark(len); + let max_number_of_remarks_per_block = (block_weight / remark_weight) as u128; + let per_byte = ::TransactionByteFee::get(); + // length fee. this is not adjusted. + let len_fee = + max_number_of_remarks_per_block.saturating_mul(per_byte.saturating_mul(len as u128)); + + let base_fee = max_number_of_remarks_per_block + * ::WeightToFee::calc( + &frame_support::weights::constants::ExtrinsicBaseWeight::get(), + ); + + run_with_system_weight(block_weight, || { + // initial value configured on module + let mut fee_adjustment = Multiplier::one(); + assert_eq!(fee_adjustment, TransactionPayment::next_fee_multiplier()); + let mut accumulated_fee: u128 = 0; + // Simulates 1 day of parachain blocks (12 seconds each) + for iteration in 0..7200 { + let next = runtime_multiplier_update(fee_adjustment); + // if no change or less, panic. This should never happen in this case. + if fee_adjustment >= next { + println!("final fee_adjustment: {}", fee_adjustment); + println!("final next: {}", next); + panic!("The fee should ever increase"); + } + fee_adjustment = next; + let fee = ::WeightToFee::calc( + &block_weight, + ); + + // base_fee and len_fee are not adjusted + let adjusted_fee = fee_adjustment.saturating_mul_acc_int(fee) + base_fee + len_fee; + accumulated_fee += adjusted_fee; + println!( + "Iteration {}, New fee_adjustment = {:?}. Adjusted Fee: {} KMA, Total Fee: {} KMA, Dollar Value: {}", + iteration, + fee_adjustment, + adjusted_fee / KMA, + accumulated_fee / KMA, + (accumulated_fee / KMA) as f32 * kma_price, + ); + } + + if accumulated_fee < target_daily_congestion_cost_kma { + panic!("The cost to fully congest our network should be over the target_daily_congestion_cost_kma after 1 day."); + } + }); + } + + #[test] + fn multiplier_can_grow_from_zero() { + let minimum_multiplier = polkadot_runtime_common::MinimumMultiplier::get(); + let target = polkadot_runtime_common::TargetBlockFullness::get() + * BlockWeights::get() + .get(DispatchClass::Normal) + .max_total + .unwrap(); + // if the min is too small, then this will not change, and we are doomed forever. + // the weight is 1/100th bigger than target. + run_with_system_weight(target * 101 / 100, || { + let next = polkadot_runtime_common::SlowAdjustingFeeUpdate::::convert( + minimum_multiplier, + ); + assert!( + next > minimum_multiplier, + "{:?} !>= {:?}", + next, + minimum_multiplier + ); + }) + } + + #[test] + #[ignore] // test runs for a very long time + fn multiplier_growth_simulator() { + // assume the multiplier is initially set to its minimum. We update it with values twice the + //target (target is 25%, thus 50%) and we see at which point it reaches 1. + let mut multiplier = polkadot_runtime_common::MinimumMultiplier::get(); + let block_weight = polkadot_runtime_common::TargetBlockFullness::get() + * BlockWeights::get() + .get(DispatchClass::Normal) + .max_total + .unwrap() + * 2; + let mut blocks = 0; + while multiplier <= Multiplier::one() { + run_with_system_weight(block_weight, || { + let next = + polkadot_runtime_common::SlowAdjustingFeeUpdate::::convert(multiplier); + // ensure that it is growing as well. + assert!(next > multiplier, "{:?} !>= {:?}", next, multiplier); + multiplier = next; + }); + blocks += 1; + println!("block = {} multiplier {:?}", blocks, multiplier); + } + } } diff --git a/runtime/calamari/src/impls.rs b/runtime/calamari/src/impls.rs index 13c623ecd..89c24a9da 100644 --- a/runtime/calamari/src/impls.rs +++ b/runtime/calamari/src/impls.rs @@ -15,43 +15,43 @@ // along with Manta. If not, see . use crate::{ - fee::{ - FEES_PERCENTAGE_TO_AUTHOR, FEES_PERCENTAGE_TO_TREASURY, TIPS_PERCENTAGE_TO_AUTHOR, - TIPS_PERCENTAGE_TO_TREASURY, - }, - Authorship, Balances, NegativeImbalance, Treasury, + fee::{ + FEES_PERCENTAGE_TO_AUTHOR, FEES_PERCENTAGE_TO_TREASURY, TIPS_PERCENTAGE_TO_AUTHOR, + TIPS_PERCENTAGE_TO_TREASURY, + }, + Authorship, Balances, NegativeImbalance, Treasury, }; use frame_support::traits::{Currency, Imbalance, OnUnbalanced}; pub struct Author; impl OnUnbalanced for Author { - fn on_nonzero_unbalanced(amount: NegativeImbalance) { - if let Some(author) = Authorship::author() { - Balances::resolve_creating(&author, amount); - } - } + fn on_nonzero_unbalanced(amount: NegativeImbalance) { + if let Some(author) = Authorship::author() { + Balances::resolve_creating(&author, amount); + } + } } pub struct DealWithFees; impl OnUnbalanced for DealWithFees { - fn on_unbalanceds(mut fees_then_tips: impl Iterator) { - if let Some(fees) = fees_then_tips.next() { - // for fees, 40% to treasury, 60% to author - let mut split = fees.ration( - FEES_PERCENTAGE_TO_TREASURY.into(), - FEES_PERCENTAGE_TO_AUTHOR.into(), - ); - if let Some(tips) = fees_then_tips.next() { - // for tips, 100% to block author. - tips.ration_merge_into( - TIPS_PERCENTAGE_TO_TREASURY.into(), - TIPS_PERCENTAGE_TO_AUTHOR.into(), - &mut split, - ); - } + fn on_unbalanceds(mut fees_then_tips: impl Iterator) { + if let Some(fees) = fees_then_tips.next() { + // for fees, 40% to treasury, 60% to author + let mut split = fees.ration( + FEES_PERCENTAGE_TO_TREASURY.into(), + FEES_PERCENTAGE_TO_AUTHOR.into(), + ); + if let Some(tips) = fees_then_tips.next() { + // for tips, 100% to block author. + tips.ration_merge_into( + TIPS_PERCENTAGE_TO_TREASURY.into(), + TIPS_PERCENTAGE_TO_AUTHOR.into(), + &mut split, + ); + } - Treasury::on_unbalanced(split.0); - Author::on_unbalanced(split.1); - } - } + Treasury::on_unbalanced(split.0); + Author::on_unbalanced(split.1); + } + } } diff --git a/runtime/calamari/src/lib.rs b/runtime/calamari/src/lib.rs index e7fd52259..36724f06b 100644 --- a/runtime/calamari/src/lib.rs +++ b/runtime/calamari/src/lib.rs @@ -16,6 +16,7 @@ //! Calamari Parachain runtime. +#![allow(clippy::identity_op)] // keep e.g. 1 * DAYS for legibility #![cfg_attr(not(feature = "std"), no_std)] #![recursion_limit = "256"] @@ -26,10 +27,10 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, - traits::{AccountIdLookup, BlakeTwo256, Block as BlockT}, - transaction_validity::{TransactionSource, TransactionValidity}, - ApplyExtrinsicResult, + create_runtime_str, generic, impl_opaque_keys, + traits::{AccountIdLookup, BlakeTwo256, Block as BlockT}, + transaction_validity::{TransactionSource, TransactionValidity}, + ApplyExtrinsicResult, }; use sp_std::{cmp::Ordering, prelude::*}; #[cfg(feature = "std")] @@ -37,21 +38,21 @@ use sp_version::NativeVersion; use sp_version::RuntimeVersion; use frame_support::{ - construct_runtime, parameter_types, - traits::{ConstU16, ConstU32, ConstU8, Contains, Currency, EnsureOneOf, PrivilegeCmp}, - weights::{ - constants::{BlockExecutionWeight, ExtrinsicBaseWeight, WEIGHT_PER_SECOND}, - DispatchClass, Weight, - }, - PalletId, + construct_runtime, parameter_types, + traits::{ConstU16, ConstU32, ConstU8, Contains, Currency, EnsureOneOf, PrivilegeCmp}, + weights::{ + constants::{BlockExecutionWeight, ExtrinsicBaseWeight, WEIGHT_PER_SECOND}, + DispatchClass, Weight, + }, + PalletId, }; use frame_system::{ - limits::{BlockLength, BlockWeights}, - EnsureRoot, + limits::{BlockLength, BlockWeights}, + EnsureRoot, }; use manta_primitives::{ - constants::{time::*, STAKING_PALLET_ID, TREASURY_PALLET_ID}, - types::{AccountId, AuraId, Balance, BlockNumber, Hash, Header, Index, Signature}, + constants::{time::*, STAKING_PALLET_ID, TREASURY_PALLET_ID}, + types::{AccountId, AuraId, Balance, BlockNumber, Hash, Header, Index, Signature}, }; use runtime_common::prod_or_fast; use sp_runtime::{Perbill, Permill}; @@ -81,19 +82,19 @@ pub type NegativeImbalance = >::NegativeImbalanc /// of data like extrinsics, allowing for them to continue syncing the network through upgrades /// to even the core data structures. pub mod opaque { - use super::*; - pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic; - /// Opaque block header type. - pub type Header = generic::Header; - /// Opaque block type. - pub type Block = generic::Block; - /// Opaque block identifier type. - pub type BlockId = generic::BlockId; - impl_opaque_keys! { - pub struct SessionKeys { - pub aura: Aura, - } - } + use super::*; + pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic; + /// Opaque block header type. + pub type Header = generic::Header; + /// Opaque block type. + pub type Block = generic::Block; + /// Opaque block identifier type. + pub type BlockId = generic::BlockId; + impl_opaque_keys! { + pub struct SessionKeys { + pub aura: Aura, + } + } } // Weights used in the runtime. @@ -101,25 +102,24 @@ mod weights; #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("calamari"), - impl_name: create_runtime_str!("calamari"), - authoring_version: 1, - spec_version: 3200, - impl_version: 1, - apis: RUNTIME_API_VERSIONS, - transaction_version: 5, - state_version: 0, + spec_name: create_runtime_str!("calamari"), + impl_name: create_runtime_str!("calamari"), + authoring_version: 1, + spec_version: 3200, + impl_version: 1, + apis: RUNTIME_API_VERSIONS, + transaction_version: 5, + state_version: 0, }; /// The version information used to identify this runtime when compiled natively. #[cfg(feature = "std")] pub fn native_version() -> NativeVersion { - NativeVersion { - runtime_version: VERSION, - can_author_with: Default::default(), - } + NativeVersion { + runtime_version: VERSION, + can_author_with: Default::default(), + } } - /// We assume that ~10% of the block weight is consumed by `on_initialize` handlers. This is /// used to limit the maximal weight of a single extrinsic. pub const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10); @@ -131,583 +131,596 @@ pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(70); pub const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2; parameter_types! { - pub const Version: RuntimeVersion = VERSION; - pub RuntimeBlockLength: BlockLength = - BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); - pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder() - .base_block(BlockExecutionWeight::get()) - .for_class(DispatchClass::all(), |weights| { - weights.base_extrinsic = ExtrinsicBaseWeight::get(); - }) - .for_class(DispatchClass::Normal, |weights| { - weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); - }) - .for_class(DispatchClass::Operational, |weights| { - weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT); - // Operational transactions have some extra reserved space, so that they - // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`. - weights.reserved = Some( - MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT - ); - }) - .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) - .build_or_panic(); - pub const SS58Prefix: u8 = manta_primitives::constants::CALAMARI_SS58PREFIX; + pub const Version: RuntimeVersion = VERSION; + pub RuntimeBlockLength: BlockLength = + BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); + pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder() + .base_block(BlockExecutionWeight::get()) + .for_class(DispatchClass::all(), |weights| { + weights.base_extrinsic = ExtrinsicBaseWeight::get(); + }) + .for_class(DispatchClass::Normal, |weights| { + weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); + }) + .for_class(DispatchClass::Operational, |weights| { + weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT); + // Operational transactions have some extra reserved space, so that they + // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`. + weights.reserved = Some( + MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT + ); + }) + .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) + .build_or_panic(); + pub const SS58Prefix: u8 = manta_primitives::constants::CALAMARI_SS58PREFIX; } impl pallet_tx_pause::Config for Runtime { - type Event = Event; - type UpdateOrigin = EnsureOneOf< - EnsureRoot, - pallet_collective::EnsureProportionMoreThan, - >; - type WeightInfo = weights::pallet_tx_pause::SubstrateWeight; + type Event = Event; + type UpdateOrigin = EnsureOneOf< + EnsureRoot, + pallet_collective::EnsureProportionMoreThan, + >; + type WeightInfo = weights::pallet_tx_pause::SubstrateWeight; } // Don't allow permission-less asset creation. pub struct BaseFilter; impl Contains for BaseFilter { - fn contains(call: &Call) -> bool { - if matches!( - call, - Call::Timestamp(_) | Call::ParachainSystem(_) | Call::System(_) - ) { - // always allow core call - // pallet-timestamp and parachainSystem could not be filtered because - // they are used in communication between relaychain and parachain. - return true; - } - - if pallet_tx_pause::PausedTransactionFilter::::contains(call) { - // no paused call - return false; - } - - match call { - | Call::Authorship(_) - | Call::Multisig(_) - // For now disallow public proposal workflows, treasury workflows, - // as well as external_propose and external_propose_majority. - // The following are filtered out: - // pallet_democracy::Call::propose(_) - // pallet_democracy::Call::second(_, _) - // pallet_democracy::Call::cancel_proposal(_) - // pallet_democracy::Call::clear_public_proposals() - // pallet_democracy::Call::external_propose(_) - // pallet_democracy::Call::external_propose_majority(_) - | Call::Democracy(pallet_democracy::Call::vote {..} - | pallet_democracy::Call::emergency_cancel {..} - | pallet_democracy::Call::external_propose_default {..} - | pallet_democracy::Call::fast_track {..} - | pallet_democracy::Call::veto_external {..} - | pallet_democracy::Call::cancel_referendum {..} - | pallet_democracy::Call::cancel_queued {..} - | pallet_democracy::Call::delegate {..} - | pallet_democracy::Call::undelegate {..} - | pallet_democracy::Call::note_preimage {..} - | pallet_democracy::Call::note_preimage_operational {..} - | pallet_democracy::Call::note_imminent_preimage {..} - | pallet_democracy::Call::note_imminent_preimage_operational {..} - | pallet_democracy::Call::reap_preimage {..} - | pallet_democracy::Call::unlock {..} - | pallet_democracy::Call::remove_vote {..} - | pallet_democracy::Call::remove_other_vote {..} - | pallet_democracy::Call::enact_proposal {..} - | pallet_democracy::Call::blacklist {..}) - | Call::Council(_) - | Call::TechnicalCommittee(_) - | Call::CouncilMembership(_) - | Call::TechnicalMembership(_) - // Treasury calls are filtered while it is accumulating funds. - //| Call::Treasury(_) - | Call::Scheduler(_) - | Call::CalamariVesting(_) - | Call::Session(_) // User must be able to set their session key when applying for a collator - | Call::CollatorSelection( - manta_collator_selection::Call::set_invulnerables{..} - | manta_collator_selection::Call::set_desired_candidates{..} - | manta_collator_selection::Call::set_candidacy_bond{..} - | manta_collator_selection::Call::set_eviction_baseline{..} - | manta_collator_selection::Call::set_eviction_tolerance{..} - | manta_collator_selection::Call::register_candidate{..} - // Currently, we filter `register_as_candidate` as this call is not yet ready for community. - | manta_collator_selection::Call::remove_collator{..} - | manta_collator_selection::Call::leave_intent{..}) - | Call::Balances(_) - | Call::Preimage(_) - // Everything except transfer() is filtered out until it is practically needed: - // orml_xtokens::Call::transfer_with_fee {..} - // orml_xtokens::Call::transfer_multiasset {..} - // orml_xtokens::Call::transfer_multiasset_with_fee {..} - // orml_xtokens::Call::transfer_multicurrencies {..} - // orml_xtokens::Call::transfer_multiassets {..} - | Call::XTokens(orml_xtokens::Call::transfer {..}) - | Call::Utility(_) => true, - | Call::XcmpQueue(_) | Call::PolkadotXcm(_) | Call::DmpQueue(_) // Filter callables from XCM pallets - | _ => false - } - } + fn contains(call: &Call) -> bool { + if matches!( + call, + Call::Timestamp(_) | Call::ParachainSystem(_) | Call::System(_) + ) { + // always allow core call + // pallet-timestamp and parachainSystem could not be filtered because + // they are used in communication between relaychain and parachain. + return true; + } + + if pallet_tx_pause::PausedTransactionFilter::::contains(call) { + // no paused call + return false; + } + + #[allow(clippy::match_like_matches_macro)] + // keep CallFilter with explicit true/false for documentation + match call { + // Explicitly DISALLOWED calls + | Call::Assets(_) // Filter Assets. Assets should only be accessed by AssetManager. + | Call::AssetManager(_) // AssetManager is also filtered because all of its extrinsics + // are callable only by Root, and Root calls skip this whole filter. + // Currently, we filter `register_as_candidate` as this call is not yet ready for community. + | Call::CollatorSelection( manta_collator_selection::Call::register_as_candidate{..}) + // For now disallow public proposal workflows, treasury workflows, + // as well as external_propose and external_propose_majority. + // The following are filtered out: + | Call::Democracy( + pallet_democracy::Call::propose {..} + | pallet_democracy::Call::second {..} + | pallet_democracy::Call::cancel_proposal {..} + | pallet_democracy::Call::clear_public_proposals {..} + | pallet_democracy::Call::external_propose {..} + | pallet_democracy::Call::external_propose_majority {..}) + | Call::Treasury(_) // Treasury calls are filtered while it is accumulating funds. + // Everything except transfer() is filtered out until it is practically needed: + | Call::XTokens( + orml_xtokens::Call::transfer_with_fee {..} + | orml_xtokens::Call::transfer_multiasset {..} + | orml_xtokens::Call::transfer_multiasset_with_fee {..} + | orml_xtokens::Call::transfer_multicurrencies {..} + | orml_xtokens::Call::transfer_multiassets {..}) + // Filter callables from XCM pallets, we use XTokens exclusively + | Call::XcmpQueue(_) | Call::PolkadotXcm(_) | Call::DmpQueue(_) => false, + + // Explicitly ALLOWED calls + | Call::Authorship(_) + | Call::Multisig(_) + | Call::Democracy(pallet_democracy::Call::vote {..} + | pallet_democracy::Call::emergency_cancel {..} + | pallet_democracy::Call::external_propose_default {..} + | pallet_democracy::Call::fast_track {..} + | pallet_democracy::Call::veto_external {..} + | pallet_democracy::Call::cancel_referendum {..} + | pallet_democracy::Call::cancel_queued {..} + | pallet_democracy::Call::delegate {..} + | pallet_democracy::Call::undelegate {..} + | pallet_democracy::Call::note_preimage {..} + | pallet_democracy::Call::note_preimage_operational {..} + | pallet_democracy::Call::note_imminent_preimage {..} + | pallet_democracy::Call::note_imminent_preimage_operational {..} + | pallet_democracy::Call::reap_preimage {..} + | pallet_democracy::Call::unlock {..} + | pallet_democracy::Call::remove_vote {..} + | pallet_democracy::Call::remove_other_vote {..} + | pallet_democracy::Call::enact_proposal {..} + | pallet_democracy::Call::blacklist {..}) + | Call::Council(_) + | Call::TechnicalCommittee(_) + | Call::CouncilMembership(_) + | Call::TechnicalMembership(_) + | Call::Scheduler(_) + | Call::CalamariVesting(_) + | Call::Session(_) // User must be able to set their session key when applying for a collator + | Call::CollatorSelection( + manta_collator_selection::Call::set_invulnerables{..} + | manta_collator_selection::Call::set_desired_candidates{..} + | manta_collator_selection::Call::set_candidacy_bond{..} + | manta_collator_selection::Call::set_eviction_baseline{..} + | manta_collator_selection::Call::set_eviction_tolerance{..} + | manta_collator_selection::Call::register_candidate{..} + | manta_collator_selection::Call::remove_collator{..} + | manta_collator_selection::Call::leave_intent{..}) + | Call::Balances(_) + | Call::Preimage(_) + | Call::XTokens(orml_xtokens::Call::transfer {..}) + | Call::Utility(_) => true, + + // DISALLOW anything else + | _ => false + } + } } // Configure FRAME pallets to include in runtime. impl frame_system::Config for Runtime { - type BaseCallFilter = BaseFilter; // Let filter activate. - type BlockWeights = RuntimeBlockWeights; - type BlockLength = RuntimeBlockLength; - type AccountId = AccountId; - type Call = Call; - type Lookup = AccountIdLookup; - type Index = Index; - type BlockNumber = BlockNumber; - type Hash = Hash; - type Hashing = BlakeTwo256; - type Header = Header; - type Event = Event; - type Origin = Origin; - type BlockHashCount = BlockHashCount; - type DbWeight = RocksDbWeight; - type Version = Version; - type PalletInfo = PalletInfo; - type OnNewAccount = (); - type OnKilledAccount = (); - type AccountData = pallet_balances::AccountData; - type SystemWeightInfo = weights::frame_system::SubstrateWeight; - type SS58Prefix = SS58Prefix; - type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; - type MaxConsumers = ConstU32<16>; + type BaseCallFilter = BaseFilter; // Let filter activate. + type BlockWeights = RuntimeBlockWeights; + type BlockLength = RuntimeBlockLength; + type AccountId = AccountId; + type Call = Call; + type Lookup = AccountIdLookup; + type Index = Index; + type BlockNumber = BlockNumber; + type Hash = Hash; + type Hashing = BlakeTwo256; + type Header = Header; + type Event = Event; + type Origin = Origin; + type BlockHashCount = BlockHashCount; + type DbWeight = RocksDbWeight; + type Version = Version; + type PalletInfo = PalletInfo; + type OnNewAccount = (); + type OnKilledAccount = (); + type AccountData = pallet_balances::AccountData; + type SystemWeightInfo = weights::frame_system::SubstrateWeight; + type SS58Prefix = SS58Prefix; + type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; + type MaxConsumers = ConstU32<16>; } parameter_types! { - pub const MinimumPeriod: u64 = SLOT_DURATION / 2; + pub const MinimumPeriod: u64 = SLOT_DURATION / 2; } impl pallet_timestamp::Config for Runtime { - /// A timestamp: milliseconds since the unix epoch. - type Moment = u64; - type OnTimestampSet = (); - type MinimumPeriod = MinimumPeriod; - type WeightInfo = weights::pallet_timestamp::SubstrateWeight; + /// A timestamp: milliseconds since the unix epoch. + type Moment = u64; + type OnTimestampSet = (); + type MinimumPeriod = MinimumPeriod; + type WeightInfo = weights::pallet_timestamp::SubstrateWeight; } impl pallet_authorship::Config for Runtime { - type FindAuthor = pallet_session::FindAccountFromAuthorIndex; - type UncleGenerations = ConstU32<0>; - type FilterUncle = (); - type EventHandler = (CollatorSelection,); + type FindAuthor = pallet_session::FindAccountFromAuthorIndex; + type UncleGenerations = ConstU32<0>; + type FilterUncle = (); + type EventHandler = (CollatorSelection,); } parameter_types! { - pub const NativeTokenExistentialDeposit: u128 = 10 * cKMA; // 0.1 KMA + pub const NativeTokenExistentialDeposit: u128 = 10 * cKMA; // 0.1 KMA } impl pallet_balances::Config for Runtime { - type MaxLocks = ConstU32<50>; - type MaxReserves = ConstU32<50>; - type ReserveIdentifier = [u8; 8]; - type Balance = Balance; - type DustRemoval = (); - type Event = Event; - type ExistentialDeposit = NativeTokenExistentialDeposit; - type AccountStore = frame_system::Pallet; - type WeightInfo = weights::pallet_balances::SubstrateWeight; + type MaxLocks = ConstU32<50>; + type MaxReserves = ConstU32<50>; + type ReserveIdentifier = [u8; 8]; + type Balance = Balance; + type DustRemoval = (); + type Event = Event; + type ExistentialDeposit = NativeTokenExistentialDeposit; + type AccountStore = frame_system::Pallet; + type WeightInfo = weights::pallet_balances::SubstrateWeight; } parameter_types! { - /// Relay Chain `TransactionByteFee` / 10 - pub const TransactionByteFee: Balance = mKMA / 100; + /// Relay Chain `TransactionByteFee` / 10 + pub const TransactionByteFee: Balance = mKMA / 100; } impl pallet_transaction_payment::Config for Runtime { - type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter; - type TransactionByteFee = TransactionByteFee; - type WeightToFee = WeightToFee; - type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; - type OperationalFeeMultiplier = ConstU8<5>; + type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter; + type TransactionByteFee = TransactionByteFee; + type WeightToFee = WeightToFee; + type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; + type OperationalFeeMultiplier = ConstU8<5>; } parameter_types! { - // One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes. - pub const DepositBase: Balance = deposit(1, 88); - // Additional storage item size of 32 bytes. - pub const DepositFactor: Balance = deposit(0, 32); + // One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes. + pub const DepositBase: Balance = deposit(1, 88); + // Additional storage item size of 32 bytes. + pub const DepositFactor: Balance = deposit(0, 32); } impl pallet_multisig::Config for Runtime { - type Event = Event; - type Call = Call; - type Currency = Balances; - type DepositBase = DepositBase; - type DepositFactor = DepositFactor; - type MaxSignatories = ConstU16<100>; - type WeightInfo = weights::pallet_multisig::SubstrateWeight; + type Event = Event; + type Call = Call; + type Currency = Balances; + type DepositBase = DepositBase; + type DepositFactor = DepositFactor; + type MaxSignatories = ConstU16<100>; + type WeightInfo = weights::pallet_multisig::SubstrateWeight; } impl pallet_utility::Config for Runtime { - type Event = Event; - type Call = Call; - type PalletsOrigin = OriginCaller; - type WeightInfo = weights::pallet_utility::SubstrateWeight; + type Event = Event; + type Call = Call; + type PalletsOrigin = OriginCaller; + type WeightInfo = weights::pallet_utility::SubstrateWeight; } parameter_types! { - pub LaunchPeriod: BlockNumber = prod_or_fast!(7 * DAYS, 5 * MINUTES, "CALAMARI_LAUNCHPERIOD"); - pub VotingPeriod: BlockNumber = prod_or_fast!(7 * DAYS, 5 * MINUTES, "CALAMARI_VOTINGPERIOD"); - pub FastTrackVotingPeriod: BlockNumber = prod_or_fast!(3 * HOURS, 2 * MINUTES, "CALAMARI_FASTTRACKVOTINGPERIOD"); - pub const InstantAllowed: bool = true; - pub const MinimumDeposit: Balance = 1000 * KMA; - pub EnactmentPeriod: BlockNumber = prod_or_fast!(1 * DAYS, 2 * MINUTES, "CALAMARI_ENACTMENTPERIOD"); - pub CooloffPeriod: BlockNumber = prod_or_fast!(7 * DAYS, 2 * MINUTES, "CALAMARI_COOLOFFPERIOD"); - pub const PreimageByteDeposit: Balance = deposit(0, 1); + pub LaunchPeriod: BlockNumber = prod_or_fast!(7 * DAYS, 5 * MINUTES, "CALAMARI_LAUNCHPERIOD"); + pub VotingPeriod: BlockNumber = prod_or_fast!(7 * DAYS, 5 * MINUTES, "CALAMARI_VOTINGPERIOD"); + pub FastTrackVotingPeriod: BlockNumber = prod_or_fast!(3 * HOURS, 2 * MINUTES, "CALAMARI_FASTTRACKVOTINGPERIOD"); + pub const InstantAllowed: bool = true; + pub const MinimumDeposit: Balance = 1000 * KMA; + pub EnactmentPeriod: BlockNumber = prod_or_fast!(1 * DAYS, 2 * MINUTES, "CALAMARI_ENACTMENTPERIOD"); + pub CooloffPeriod: BlockNumber = prod_or_fast!(7 * DAYS, 2 * MINUTES, "CALAMARI_COOLOFFPERIOD"); + pub const PreimageByteDeposit: Balance = deposit(0, 1); } impl pallet_democracy::Config for Runtime { - type Proposal = Call; - type Event = Event; - type Currency = Balances; - type EnactmentPeriod = EnactmentPeriod; - type VoteLockingPeriod = EnactmentPeriod; - type LaunchPeriod = LaunchPeriod; - type VotingPeriod = VotingPeriod; - type MinimumDeposit = MinimumDeposit; - /// A straight majority of the council can decide what their next motion is. - type ExternalOrigin = - pallet_collective::EnsureProportionAtLeast; - /// A super-majority can have the next scheduled referendum be a straight majority-carries vote. - type ExternalMajorityOrigin = - pallet_collective::EnsureProportionAtLeast; - /// A unanimous council can have the next scheduled referendum be a straight default-carries - /// (NTB) vote. - type ExternalDefaultOrigin = - pallet_collective::EnsureProportionAtLeast; - /// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote - /// be tabled immediately and with a shorter voting/enactment period. - type FastTrackOrigin = - pallet_collective::EnsureProportionAtLeast; - type InstantOrigin = - pallet_collective::EnsureProportionAtLeast; - type InstantAllowed = InstantAllowed; - type FastTrackVotingPeriod = FastTrackVotingPeriod; - // To cancel a proposal which has been passed, 2/3 of the council must agree to it. - type CancellationOrigin = - pallet_collective::EnsureProportionAtLeast; - // To cancel a proposal before it has been passed, the technical committee must be unanimous or - // Root must agree. - type CancelProposalOrigin = EnsureOneOf< - EnsureRoot, - pallet_collective::EnsureProportionAtLeast, - >; - type BlacklistOrigin = EnsureRoot; - // Any single technical committee member may veto a coming council proposal, however they can - // only do it once and it lasts only for the cool-off period. - type VetoOrigin = pallet_collective::EnsureMember; - type CooloffPeriod = CooloffPeriod; - type PreimageByteDeposit = PreimageByteDeposit; - type OperationalPreimageOrigin = pallet_collective::EnsureMember; - type Slash = (); - type Scheduler = Scheduler; - type PalletsOrigin = OriginCaller; - type MaxVotes = ConstU32<100>; - type WeightInfo = weights::pallet_democracy::SubstrateWeight; - type MaxProposals = ConstU32<100>; + type Proposal = Call; + type Event = Event; + type Currency = Balances; + type EnactmentPeriod = EnactmentPeriod; + type VoteLockingPeriod = EnactmentPeriod; + type LaunchPeriod = LaunchPeriod; + type VotingPeriod = VotingPeriod; + type MinimumDeposit = MinimumDeposit; + /// A straight majority of the council can decide what their next motion is. + type ExternalOrigin = + pallet_collective::EnsureProportionAtLeast; + /// A super-majority can have the next scheduled referendum be a straight majority-carries vote. + type ExternalMajorityOrigin = + pallet_collective::EnsureProportionAtLeast; + /// A unanimous council can have the next scheduled referendum be a straight default-carries + /// (NTB) vote. + type ExternalDefaultOrigin = + pallet_collective::EnsureProportionAtLeast; + /// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote + /// be tabled immediately and with a shorter voting/enactment period. + type FastTrackOrigin = + pallet_collective::EnsureProportionAtLeast; + type InstantOrigin = + pallet_collective::EnsureProportionAtLeast; + type InstantAllowed = InstantAllowed; + type FastTrackVotingPeriod = FastTrackVotingPeriod; + // To cancel a proposal which has been passed, 2/3 of the council must agree to it. + type CancellationOrigin = + pallet_collective::EnsureProportionAtLeast; + // To cancel a proposal before it has been passed, the technical committee must be unanimous or + // Root must agree. + type CancelProposalOrigin = EnsureOneOf< + EnsureRoot, + pallet_collective::EnsureProportionAtLeast, + >; + type BlacklistOrigin = EnsureRoot; + // Any single technical committee member may veto a coming council proposal, however they can + // only do it once and it lasts only for the cool-off period. + type VetoOrigin = pallet_collective::EnsureMember; + type CooloffPeriod = CooloffPeriod; + type PreimageByteDeposit = PreimageByteDeposit; + type OperationalPreimageOrigin = pallet_collective::EnsureMember; + type Slash = (); + type Scheduler = Scheduler; + type PalletsOrigin = OriginCaller; + type MaxVotes = ConstU32<100>; + type WeightInfo = weights::pallet_democracy::SubstrateWeight; + type MaxProposals = ConstU32<100>; } parameter_types! { - /// The maximum amount of time (in blocks) for council members to vote on motions. - /// Motions may end in fewer blocks if enough votes are cast to determine the result. - pub const CouncilMotionDuration: BlockNumber = 3 * DAYS; + /// The maximum amount of time (in blocks) for council members to vote on motions. + /// Motions may end in fewer blocks if enough votes are cast to determine the result. + pub const CouncilMotionDuration: BlockNumber = 3 * DAYS; } type CouncilCollective = pallet_collective::Instance1; impl pallet_collective::Config for Runtime { - type Origin = Origin; - type Proposal = Call; - type Event = Event; - type MotionDuration = CouncilMotionDuration; - type MaxProposals = ConstU32<100>; - type MaxMembers = ConstU32<100>; - type DefaultVote = pallet_collective::PrimeDefaultVote; - type WeightInfo = weights::pallet_collective::SubstrateWeight; + type Origin = Origin; + type Proposal = Call; + type Event = Event; + type MotionDuration = CouncilMotionDuration; + type MaxProposals = ConstU32<100>; + type MaxMembers = ConstU32<100>; + type DefaultVote = pallet_collective::PrimeDefaultVote; + type WeightInfo = weights::pallet_collective::SubstrateWeight; } pub type EnsureRootOrThreeFourthsCouncil = EnsureOneOf< - EnsureRoot, - pallet_collective::EnsureProportionAtLeast, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast, >; type CouncilMembershipInstance = pallet_membership::Instance1; impl pallet_membership::Config for Runtime { - type Event = Event; - type AddOrigin = EnsureRootOrThreeFourthsCouncil; - type RemoveOrigin = EnsureRootOrThreeFourthsCouncil; - type SwapOrigin = EnsureRootOrThreeFourthsCouncil; - type ResetOrigin = EnsureRootOrThreeFourthsCouncil; - type PrimeOrigin = EnsureRootOrThreeFourthsCouncil; - type MembershipInitialized = Council; - type MembershipChanged = Council; - type MaxMembers = ConstU32<100>; - type WeightInfo = weights::pallet_membership::SubstrateWeight; + type Event = Event; + type AddOrigin = EnsureRootOrThreeFourthsCouncil; + type RemoveOrigin = EnsureRootOrThreeFourthsCouncil; + type SwapOrigin = EnsureRootOrThreeFourthsCouncil; + type ResetOrigin = EnsureRootOrThreeFourthsCouncil; + type PrimeOrigin = EnsureRootOrThreeFourthsCouncil; + type MembershipInitialized = Council; + type MembershipChanged = Council; + type MaxMembers = ConstU32<100>; + type WeightInfo = weights::pallet_membership::SubstrateWeight; } parameter_types! { - pub const TechnicalMotionDuration: BlockNumber = 3 * DAYS; + pub const TechnicalMotionDuration: BlockNumber = 3 * DAYS; } type TechnicalCollective = pallet_collective::Instance2; impl pallet_collective::Config for Runtime { - type Origin = Origin; - type Proposal = Call; - type Event = Event; - type MotionDuration = TechnicalMotionDuration; - type MaxProposals = ConstU32<100>; - type MaxMembers = ConstU32<100>; - type DefaultVote = pallet_collective::PrimeDefaultVote; - type WeightInfo = weights::pallet_collective::SubstrateWeight; + type Origin = Origin; + type Proposal = Call; + type Event = Event; + type MotionDuration = TechnicalMotionDuration; + type MaxProposals = ConstU32<100>; + type MaxMembers = ConstU32<100>; + type DefaultVote = pallet_collective::PrimeDefaultVote; + type WeightInfo = weights::pallet_collective::SubstrateWeight; } type TechnicalMembershipInstance = pallet_membership::Instance2; impl pallet_membership::Config for Runtime { - type Event = Event; - type AddOrigin = EnsureRootOrThreeFourthsCouncil; - type RemoveOrigin = EnsureRootOrThreeFourthsCouncil; - type SwapOrigin = EnsureRootOrThreeFourthsCouncil; - type ResetOrigin = EnsureRootOrThreeFourthsCouncil; - type PrimeOrigin = EnsureRootOrThreeFourthsCouncil; - type MembershipInitialized = TechnicalCommittee; - type MembershipChanged = TechnicalCommittee; - type MaxMembers = ConstU32<100>; - type WeightInfo = weights::pallet_membership::SubstrateWeight; + type Event = Event; + type AddOrigin = EnsureRootOrThreeFourthsCouncil; + type RemoveOrigin = EnsureRootOrThreeFourthsCouncil; + type SwapOrigin = EnsureRootOrThreeFourthsCouncil; + type ResetOrigin = EnsureRootOrThreeFourthsCouncil; + type PrimeOrigin = EnsureRootOrThreeFourthsCouncil; + type MembershipInitialized = TechnicalCommittee; + type MembershipChanged = TechnicalCommittee; + type MaxMembers = ConstU32<100>; + type WeightInfo = weights::pallet_membership::SubstrateWeight; } parameter_types! { - pub const ProposalBond: Permill = Permill::from_percent(1); - pub const ProposalBondMinimum: Balance = 500 * KMA; - pub const ProposalBondMaximum: Balance = 10_000 * KMA; - pub SpendPeriod: BlockNumber = prod_or_fast!(6 * DAYS, 2 * MINUTES, "CALAMARI_SPENDPERIOD"); - pub const Burn: Permill = Permill::from_percent(0); - pub const TreasuryPalletId: PalletId = TREASURY_PALLET_ID; + pub const ProposalBond: Permill = Permill::from_percent(1); + pub const ProposalBondMinimum: Balance = 500 * KMA; + pub const ProposalBondMaximum: Balance = 10_000 * KMA; + pub SpendPeriod: BlockNumber = prod_or_fast!(6 * DAYS, 2 * MINUTES, "CALAMARI_SPENDPERIOD"); + pub const Burn: Permill = Permill::from_percent(0); + pub const TreasuryPalletId: PalletId = TREASURY_PALLET_ID; } type EnsureRootOrThreeFifthsCouncil = EnsureOneOf< - EnsureRoot, - pallet_collective::EnsureProportionAtLeast, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast, >; type EnsureRootOrMoreThanHalfCouncil = EnsureOneOf< - EnsureRoot, - pallet_collective::EnsureProportionMoreThan, + EnsureRoot, + pallet_collective::EnsureProportionMoreThan, >; impl pallet_treasury::Config for Runtime { - type PalletId = TreasuryPalletId; - type Currency = Balances; - type ApproveOrigin = EnsureRootOrThreeFifthsCouncil; - type RejectOrigin = EnsureRootOrMoreThanHalfCouncil; - type Event = Event; - type OnSlash = Treasury; - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ProposalBondMinimum; - type ProposalBondMaximum = ProposalBondMaximum; - type SpendPeriod = SpendPeriod; - type Burn = Burn; - type BurnDestination = (); - type MaxApprovals = ConstU32<100>; - type WeightInfo = weights::pallet_treasury::SubstrateWeight; - type SpendFunds = (); + type PalletId = TreasuryPalletId; + type Currency = Balances; + type ApproveOrigin = EnsureRootOrThreeFifthsCouncil; + type RejectOrigin = EnsureRootOrMoreThanHalfCouncil; + type Event = Event; + type OnSlash = Treasury; + type ProposalBond = ProposalBond; + type ProposalBondMinimum = ProposalBondMinimum; + type ProposalBondMaximum = ProposalBondMaximum; + type SpendPeriod = SpendPeriod; + type Burn = Burn; + type BurnDestination = (); + type MaxApprovals = ConstU32<100>; + type WeightInfo = weights::pallet_treasury::SubstrateWeight; + type SpendFunds = (); } parameter_types! { - pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * - RuntimeBlockWeights::get().max_block; - pub const NoPreimagePostponement: Option = Some(10); + pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * + RuntimeBlockWeights::get().max_block; + pub const NoPreimagePostponement: Option = Some(10); } type ScheduleOrigin = EnsureRoot; /// Used the compare the privilege of an origin inside the scheduler. pub struct OriginPrivilegeCmp; impl PrivilegeCmp for OriginPrivilegeCmp { - fn cmp_privilege(left: &OriginCaller, right: &OriginCaller) -> Option { - if left == right { - return Some(Ordering::Equal); - } - - match (left, right) { - // Root is greater than anything. - (OriginCaller::system(frame_system::RawOrigin::Root), _) => Some(Ordering::Greater), - // Check which one has more yes votes. - ( - OriginCaller::Council(pallet_collective::RawOrigin::Members(l_yes_votes, l_count)), - OriginCaller::Council(pallet_collective::RawOrigin::Members(r_yes_votes, r_count)), - ) => Some((l_yes_votes * r_count).cmp(&(r_yes_votes * l_count))), - // For every other origin we don't care, as they are not used for `ScheduleOrigin`. - _ => None, - } - } + fn cmp_privilege(left: &OriginCaller, right: &OriginCaller) -> Option { + if left == right { + return Some(Ordering::Equal); + } + + match (left, right) { + // Root is greater than anything. + (OriginCaller::system(frame_system::RawOrigin::Root), _) => Some(Ordering::Greater), + // Check which one has more yes votes. + ( + OriginCaller::Council(pallet_collective::RawOrigin::Members(l_yes_votes, l_count)), + OriginCaller::Council(pallet_collective::RawOrigin::Members(r_yes_votes, r_count)), + ) => Some((l_yes_votes * r_count).cmp(&(r_yes_votes * l_count))), + // For every other origin we don't care, as they are not used for `ScheduleOrigin`. + _ => None, + } + } } impl pallet_scheduler::Config for Runtime { - type Event = Event; - type Origin = Origin; - type PalletsOrigin = OriginCaller; - type Call = Call; - type MaximumWeight = MaximumSchedulerWeight; - type ScheduleOrigin = ScheduleOrigin; - type MaxScheduledPerBlock = ConstU32<50>; // 50 scheduled calls at most in the queue for a single block. - type WeightInfo = weights::pallet_scheduler::SubstrateWeight; - type OriginPrivilegeCmp = OriginPrivilegeCmp; - type PreimageProvider = Preimage; - type NoPreimagePostponement = NoPreimagePostponement; + type Event = Event; + type Origin = Origin; + type PalletsOrigin = OriginCaller; + type Call = Call; + type MaximumWeight = MaximumSchedulerWeight; + type ScheduleOrigin = ScheduleOrigin; + type MaxScheduledPerBlock = ConstU32<50>; // 50 scheduled calls at most in the queue for a single block. + type WeightInfo = weights::pallet_scheduler::SubstrateWeight; + type OriginPrivilegeCmp = OriginPrivilegeCmp; + type PreimageProvider = Preimage; + type NoPreimagePostponement = NoPreimagePostponement; } parameter_types! { - // Our NORMAL_DISPATCH_RATIO is 70% of the 5MB limit - // So anything more than 3.5MB doesn't make sense here - pub const PreimageMaxSize: u32 = 3584 * 1024; - pub const PreimageBaseDeposit: Balance = 1 * KMA; + // Our NORMAL_DISPATCH_RATIO is 70% of the 5MB limit + // So anything more than 3.5MB doesn't make sense here + pub const PreimageMaxSize: u32 = 3584 * 1024; + pub const PreimageBaseDeposit: Balance = 1 * KMA; } impl pallet_preimage::Config for Runtime { - type WeightInfo = weights::pallet_preimage::SubstrateWeight; - type Event = Event; - type Currency = Balances; - type ManagerOrigin = EnsureRoot; - type MaxSize = PreimageMaxSize; - // The sum of the below 2 amounts will get reserved every time someone submits a preimage. - // Their sum will be unreserved when the preimage is requested, i.e. when it is going to be used. - type BaseDeposit = PreimageBaseDeposit; - type ByteDeposit = PreimageByteDeposit; + type WeightInfo = weights::pallet_preimage::SubstrateWeight; + type Event = Event; + type Currency = Balances; + type ManagerOrigin = EnsureRoot; + type MaxSize = PreimageMaxSize; + // The sum of the below 2 amounts will get reserved every time someone submits a preimage. + // Their sum will be unreserved when the preimage is requested, i.e. when it is going to be used. + type BaseDeposit = PreimageBaseDeposit; + type ByteDeposit = PreimageByteDeposit; } parameter_types! { - // Rotate collator's spot each 6 hours. - pub Period: u32 = prod_or_fast!(6 * HOURS, 2 * MINUTES, "CALAMARI_PERIOD"); - pub const Offset: u32 = 0; + // Rotate collator's spot each 6 hours. + pub Period: u32 = prod_or_fast!(6 * HOURS, 2 * MINUTES, "CALAMARI_PERIOD"); + pub const Offset: u32 = 0; } impl pallet_session::Config for Runtime { - type Event = Event; - type ValidatorId = ::AccountId; - // we don't have stash and controller, thus we don't need the convert as well. - type ValidatorIdOf = manta_collator_selection::IdentityCollator; - type ShouldEndSession = pallet_session::PeriodicSessions; - type NextSessionRotation = pallet_session::PeriodicSessions; - type SessionManager = CollatorSelection; - // Essentially just Aura, but lets be pedantic. - type SessionHandler = - ::KeyTypeIdProviders; - type Keys = opaque::SessionKeys; - type WeightInfo = weights::pallet_session::SubstrateWeight; + type Event = Event; + type ValidatorId = ::AccountId; + // we don't have stash and controller, thus we don't need the convert as well. + type ValidatorIdOf = manta_collator_selection::IdentityCollator; + type ShouldEndSession = pallet_session::PeriodicSessions; + type NextSessionRotation = pallet_session::PeriodicSessions; + type SessionManager = CollatorSelection; + // Essentially just Aura, but lets be pedantic. + type SessionHandler = + ::KeyTypeIdProviders; + type Keys = opaque::SessionKeys; + type WeightInfo = weights::pallet_session::SubstrateWeight; } impl pallet_aura::Config for Runtime { - type AuthorityId = AuraId; - type DisabledValidators = (); - type MaxAuthorities = ConstU32<100_000>; + type AuthorityId = AuraId; + type DisabledValidators = (); + type MaxAuthorities = ConstU32<100_000>; } parameter_types! { - // Pallet account for record rewards and give rewards to collator. - pub const PotId: PalletId = STAKING_PALLET_ID; + // Pallet account for record rewards and give rewards to collator. + pub const PotId: PalletId = STAKING_PALLET_ID; } parameter_types! { - pub const ExecutiveBody: BodyId = BodyId::Executive; + pub const ExecutiveBody: BodyId = BodyId::Executive; } /// We allow root and the Relay Chain council to execute privileged collator selection operations. pub type CollatorSelectionUpdateOrigin = EnsureOneOf< - EnsureRoot, - pallet_collective::EnsureProportionAtLeast, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast, >; impl manta_collator_selection::Config for Runtime { - type Event = Event; - type Currency = Balances; - type UpdateOrigin = CollatorSelectionUpdateOrigin; - type PotId = PotId; - type MaxCandidates = ConstU32<50>; // 50 candidates at most - type MaxInvulnerables = ConstU32<5>; // 5 invulnerables at most - type ValidatorId = ::AccountId; - type ValidatorIdOf = manta_collator_selection::IdentityCollator; - type AccountIdOf = manta_collator_selection::IdentityCollator; - type ValidatorRegistration = Session; - type WeightInfo = weights::manta_collator_selection::SubstrateWeight; + type Event = Event; + type Currency = Balances; + type UpdateOrigin = CollatorSelectionUpdateOrigin; + type PotId = PotId; + type MaxCandidates = ConstU32<50>; // 50 candidates at most + type MaxInvulnerables = ConstU32<5>; // 5 invulnerables at most + type ValidatorId = ::AccountId; + type ValidatorIdOf = manta_collator_selection::IdentityCollator; + type AccountIdOf = manta_collator_selection::IdentityCollator; + type ValidatorRegistration = Session; + type WeightInfo = weights::manta_collator_selection::SubstrateWeight; } // Calamari pallets configuration parameter_types! { - pub const MinVestedTransfer: Balance = KMA; + pub const MinVestedTransfer: Balance = KMA; } impl calamari_vesting::Config for Runtime { - type Currency = Balances; - type Event = Event; - type Timestamp = Timestamp; - type MinVestedTransfer = MinVestedTransfer; - type MaxScheduleLength = ConstU32<6>; - type WeightInfo = weights::calamari_vesting::SubstrateWeight; + type Currency = Balances; + type Event = Event; + type Timestamp = Timestamp; + type MinVestedTransfer = MinVestedTransfer; + type MaxScheduleLength = ConstU32<6>; + type WeightInfo = weights::calamari_vesting::SubstrateWeight; } // Create the runtime by composing the FRAME pallets that were previously configured. construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = opaque::Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - // System support stuff. - System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, - ParachainSystem: cumulus_pallet_parachain_system::{ - Pallet, Call, Config, Storage, Inherent, Event, ValidateUnsigned, - } = 1, - Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 2, - ParachainInfo: parachain_info::{Pallet, Storage, Config} = 3, - TransactionPause: pallet_tx_pause::{Pallet, Call, Storage, Event} = 9, - - // Monetary stuff. - Balances: pallet_balances::{Pallet, Call, Storage, Config, Event} = 10, - TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 11, - - // Governance stuff. - Democracy: pallet_democracy::{Pallet, Call, Storage, Config, Event} = 14, - Council: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 15, - CouncilMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 16, - TechnicalCommittee: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 17, - TechnicalMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 18, - - // Collator support. the order of these 5 are important and shall not change. - Authorship: pallet_authorship::{Pallet, Call, Storage} = 20, - CollatorSelection: manta_collator_selection::{Pallet, Call, Storage, Event, Config} = 21, - Session: pallet_session::{Pallet, Call, Storage, Event, Config} = 22, - Aura: pallet_aura::{Pallet, Storage, Config} = 23, - AuraExt: cumulus_pallet_aura_ext::{Pallet, Storage, Config} = 24, - - // Treasury - Treasury: pallet_treasury::{Pallet, Call, Storage, Event} = 26, - - // Preimage registrar. - Preimage: pallet_preimage::{Pallet, Call, Storage, Event} = 28, - // System scheduler. - Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event} = 29, - - // XCM helpers. - XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event} = 30, - PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event, Origin, Config} = 31, - CumulusXcm: cumulus_pallet_xcm::{Pallet, Event, Origin} = 32, - DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event} = 33, - XTokens: orml_xtokens::{Pallet, Call, Event, Storage} = 34, - - // Handy utilities. - Utility: pallet_utility::{Pallet, Call, Event} = 40, - Multisig: pallet_multisig::{Pallet, Call, Storage, Event} = 41, - // 42 was occupied by pallet-sudo, we should discuss it if another pallet takes 42 in the future. - - // Assets management - Assets: pallet_assets::{Pallet, Call, Storage, Event} = 45, - AssetManager: pallet_asset_manager::{Pallet, Call, Storage, Config, Event} = 46, - - // Calamari stuff - CalamariVesting: calamari_vesting::{Pallet, Call, Storage, Event} = 50, - } + pub enum Runtime where + Block = Block, + NodeBlock = opaque::Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + // System support stuff. + System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, + ParachainSystem: cumulus_pallet_parachain_system::{ + Pallet, Call, Config, Storage, Inherent, Event, ValidateUnsigned, + } = 1, + Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 2, + ParachainInfo: parachain_info::{Pallet, Storage, Config} = 3, + TransactionPause: pallet_tx_pause::{Pallet, Call, Storage, Event} = 9, + + // Monetary stuff. + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event} = 10, + TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 11, + + // Governance stuff. + Democracy: pallet_democracy::{Pallet, Call, Storage, Config, Event} = 14, + Council: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 15, + CouncilMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 16, + TechnicalCommittee: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 17, + TechnicalMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 18, + + // Collator support. the order of these 5 are important and shall not change. + Authorship: pallet_authorship::{Pallet, Call, Storage} = 20, + CollatorSelection: manta_collator_selection::{Pallet, Call, Storage, Event, Config} = 21, + Session: pallet_session::{Pallet, Call, Storage, Event, Config} = 22, + Aura: pallet_aura::{Pallet, Storage, Config} = 23, + AuraExt: cumulus_pallet_aura_ext::{Pallet, Storage, Config} = 24, + + // Treasury + Treasury: pallet_treasury::{Pallet, Call, Storage, Event} = 26, + + // Preimage registrar. + Preimage: pallet_preimage::{Pallet, Call, Storage, Event} = 28, + // System scheduler. + Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event} = 29, + + // XCM helpers. + XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event} = 30, + PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event, Origin, Config} = 31, + CumulusXcm: cumulus_pallet_xcm::{Pallet, Event, Origin} = 32, + DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event} = 33, + XTokens: orml_xtokens::{Pallet, Call, Event, Storage} = 34, + + // Handy utilities. + Utility: pallet_utility::{Pallet, Call, Event} = 40, + Multisig: pallet_multisig::{Pallet, Call, Storage, Event} = 41, + // 42 was occupied by pallet-sudo, we should discuss it if another pallet takes 42 in the future. + + // Assets management + Assets: pallet_assets::{Pallet, Call, Storage, Event} = 45, + AssetManager: pallet_asset_manager::{Pallet, Call, Storage, Config, Event} = 46, + + // Calamari stuff + CalamariVesting: calamari_vesting::{Pallet, Call, Storage, Event} = 50, + } ); /// The address format for describing accounts. @@ -720,13 +733,13 @@ pub type SignedBlock = generic::SignedBlock; pub type BlockId = generic::BlockId; /// The SignedExtension to the basic transaction logic. pub type SignedExtra = ( - frame_system::CheckSpecVersion, - frame_system::CheckTxVersion, - frame_system::CheckGenesis, - frame_system::CheckEra, - frame_system::CheckNonce, - frame_system::CheckWeight, - pallet_transaction_payment::ChargeTransactionPayment, + frame_system::CheckSpecVersion, + frame_system::CheckTxVersion, + frame_system::CheckGenesis, + frame_system::CheckEra, + frame_system::CheckNonce, + frame_system::CheckWeight, + pallet_transaction_payment::ChargeTransactionPayment, ); /// Unchecked extrinsic type as expected by this runtime. pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; @@ -734,12 +747,12 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; /// Executive: handles dispatch to the various modules. pub type Executive = frame_executive::Executive< - Runtime, - Block, - frame_system::ChainContext, - Runtime, - AllPalletsReversedWithSystemFirst, - crate::migrations::sudo::RemoveSudo, + Runtime, + Block, + frame_system::ChainContext, + Runtime, + AllPalletsReversedWithSystemFirst, + crate::migrations::sudo::RemoveSudo, >; #[cfg(feature = "runtime-benchmarks")] @@ -748,228 +761,228 @@ extern crate frame_benchmarking; #[cfg(feature = "runtime-benchmarks")] mod benches { - frame_benchmarking::define_benchmarks!( - // Substrate pallets - [pallet_balances, Balances] - [pallet_multisig, Multisig] - [frame_system, SystemBench::] - [pallet_timestamp, Timestamp] - [pallet_utility, Utility] - [pallet_democracy, Democracy] - [pallet_collective, Council] - [pallet_membership, CouncilMembership] - [pallet_treasury, Treasury] - [pallet_preimage, Preimage] - [pallet_scheduler, Scheduler] - [pallet_session, SessionBench::] - [pallet_assets, Assets] - // XCM - [cumulus_pallet_xcmp_queue, XcmpQueue] - // Manta pallets - [calamari_vesting, CalamariVesting] - [pallet_tx_pause, TransactionPause] - [manta_collator_selection, CollatorSelection] - [pallet_asset_manager, AssetManager] - ); + frame_benchmarking::define_benchmarks!( + // Substrate pallets + [pallet_balances, Balances] + [pallet_multisig, Multisig] + [frame_system, SystemBench::] + [pallet_timestamp, Timestamp] + [pallet_utility, Utility] + [pallet_democracy, Democracy] + [pallet_collective, Council] + [pallet_membership, CouncilMembership] + [pallet_treasury, Treasury] + [pallet_preimage, Preimage] + [pallet_scheduler, Scheduler] + [pallet_session, SessionBench::] + [pallet_assets, Assets] + // XCM + [cumulus_pallet_xcmp_queue, XcmpQueue] + // Manta pallets + [calamari_vesting, CalamariVesting] + [pallet_tx_pause, TransactionPause] + [manta_collator_selection, CollatorSelection] + [pallet_asset_manager, AssetManager] + ); } impl_runtime_apis! { - impl sp_consensus_aura::AuraApi for Runtime { - fn slot_duration() -> sp_consensus_aura::SlotDuration { - sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) - } - - fn authorities() -> Vec { - Aura::authorities().into_inner() - } - } - - impl sp_api::Core for Runtime { - fn version() -> RuntimeVersion { - VERSION - } - - fn execute_block(block: Block) { - Executive::execute_block(block) - } - - fn initialize_block(header: &::Header) { - Executive::initialize_block(header) - } - } - - impl sp_api::Metadata for Runtime { - fn metadata() -> OpaqueMetadata { - OpaqueMetadata::new(Runtime::metadata().into()) - } - } - - impl sp_block_builder::BlockBuilder for Runtime { - fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { - Executive::apply_extrinsic(extrinsic) - } - - fn finalize_block() -> ::Header { - Executive::finalize_block() - } - - fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { - data.create_extrinsics() - } - - fn check_inherents( - block: Block, - data: sp_inherents::InherentData, - ) -> sp_inherents::CheckInherentsResult { - data.check_extrinsics(&block) - } - } - - impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { - fn validate_transaction( - source: TransactionSource, - tx: ::Extrinsic, - block_hash: ::Hash, - ) -> TransactionValidity { - Executive::validate_transaction(source, tx, block_hash) - } - } - - impl sp_offchain::OffchainWorkerApi for Runtime { - fn offchain_worker(header: &::Header) { - Executive::offchain_worker(header) - } - } - - impl sp_session::SessionKeys for Runtime { - fn generate_session_keys(seed: Option>) -> Vec { - opaque::SessionKeys::generate(seed) - } - - fn decode_session_keys( - encoded: Vec, - ) -> Option, KeyTypeId)>> { - opaque::SessionKeys::decode_into_raw_public_keys(&encoded) - } - } - - impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { - fn account_nonce(account: AccountId) -> Index { - System::account_nonce(account) - } - } - - impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { - fn query_info( - uxt: ::Extrinsic, - len: u32, - ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { - TransactionPayment::query_info(uxt, len) - } - fn query_fee_details( - uxt: ::Extrinsic, - len: u32, - ) -> pallet_transaction_payment::FeeDetails { - TransactionPayment::query_fee_details(uxt, len) - } - } - - impl cumulus_primitives_core::CollectCollationInfo for Runtime { - fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { - ParachainSystem::collect_collation_info(header) - } - } - - #[cfg(feature = "try-runtime")] - impl frame_try_runtime::TryRuntime for Runtime { - fn on_runtime_upgrade() -> (Weight, Weight) { - let weight = Executive::try_runtime_upgrade().unwrap(); - (weight, RuntimeBlockWeights::get().max_block) - } - - fn execute_block_no_check(block: Block) -> Weight { - Executive::execute_block_no_check(block) - } - } - - #[cfg(feature = "runtime-benchmarks")] - impl frame_benchmarking::Benchmark for Runtime { - fn benchmark_metadata(extra: bool) -> ( - Vec, - Vec, - ) { - use frame_benchmarking::{Benchmarking, BenchmarkList}; - use frame_support::traits::StorageInfoTrait; - use frame_system_benchmarking::Pallet as SystemBench; - use cumulus_pallet_session_benchmarking::Pallet as SessionBench; - - let mut list = Vec::::new(); - list_benchmarks!(list, extra); - - let storage_info = AllPalletsReversedWithSystemFirst::storage_info(); - (list, storage_info) - } - - fn dispatch_benchmark( - config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { - use frame_benchmarking::{Benchmarking, BenchmarkBatch, TrackedStorageKey}; - - use frame_system_benchmarking::Pallet as SystemBench; - impl frame_system_benchmarking::Config for Runtime {} - - use cumulus_pallet_session_benchmarking::Pallet as SessionBench; - impl cumulus_pallet_session_benchmarking::Config for Runtime {} - - let whitelist: Vec = vec![ - // Block Number - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(), - // Total Issuance - hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(), - // Execution Phase - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(), - // Event Count - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(), - // System Events - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(), - // Treasury Account - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da95ecffd7b6c0f78751baa9d281e0bfa3a6d6f646c70792f74727372790000000000000000000000000000000000000000").to_vec().into(), - ]; - - let mut batches = Vec::::new(); - let params = (&config, &whitelist); - add_benchmarks!(params, batches); - - if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } - Ok(batches) - } - } + impl sp_consensus_aura::AuraApi for Runtime { + fn slot_duration() -> sp_consensus_aura::SlotDuration { + sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) + } + + fn authorities() -> Vec { + Aura::authorities().into_inner() + } + } + + impl sp_api::Core for Runtime { + fn version() -> RuntimeVersion { + VERSION + } + + fn execute_block(block: Block) { + Executive::execute_block(block) + } + + fn initialize_block(header: &::Header) { + Executive::initialize_block(header) + } + } + + impl sp_api::Metadata for Runtime { + fn metadata() -> OpaqueMetadata { + OpaqueMetadata::new(Runtime::metadata().into()) + } + } + + impl sp_block_builder::BlockBuilder for Runtime { + fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { + Executive::apply_extrinsic(extrinsic) + } + + fn finalize_block() -> ::Header { + Executive::finalize_block() + } + + fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { + data.create_extrinsics() + } + + fn check_inherents( + block: Block, + data: sp_inherents::InherentData, + ) -> sp_inherents::CheckInherentsResult { + data.check_extrinsics(&block) + } + } + + impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { + fn validate_transaction( + source: TransactionSource, + tx: ::Extrinsic, + block_hash: ::Hash, + ) -> TransactionValidity { + Executive::validate_transaction(source, tx, block_hash) + } + } + + impl sp_offchain::OffchainWorkerApi for Runtime { + fn offchain_worker(header: &::Header) { + Executive::offchain_worker(header) + } + } + + impl sp_session::SessionKeys for Runtime { + fn generate_session_keys(seed: Option>) -> Vec { + opaque::SessionKeys::generate(seed) + } + + fn decode_session_keys( + encoded: Vec, + ) -> Option, KeyTypeId)>> { + opaque::SessionKeys::decode_into_raw_public_keys(&encoded) + } + } + + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Index { + System::account_nonce(account) + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { + fn query_info( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { + TransactionPayment::query_info(uxt, len) + } + fn query_fee_details( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_fee_details(uxt, len) + } + } + + impl cumulus_primitives_core::CollectCollationInfo for Runtime { + fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { + ParachainSystem::collect_collation_info(header) + } + } + + #[cfg(feature = "try-runtime")] + impl frame_try_runtime::TryRuntime for Runtime { + fn on_runtime_upgrade() -> (Weight, Weight) { + let weight = Executive::try_runtime_upgrade().unwrap(); + (weight, RuntimeBlockWeights::get().max_block) + } + + fn execute_block_no_check(block: Block) -> Weight { + Executive::execute_block_no_check(block) + } + } + + #[cfg(feature = "runtime-benchmarks")] + impl frame_benchmarking::Benchmark for Runtime { + fn benchmark_metadata(extra: bool) -> ( + Vec, + Vec, + ) { + use frame_benchmarking::{Benchmarking, BenchmarkList}; + use frame_support::traits::StorageInfoTrait; + use frame_system_benchmarking::Pallet as SystemBench; + use cumulus_pallet_session_benchmarking::Pallet as SessionBench; + + let mut list = Vec::::new(); + list_benchmarks!(list, extra); + + let storage_info = AllPalletsReversedWithSystemFirst::storage_info(); + (list, storage_info) + } + + fn dispatch_benchmark( + config: frame_benchmarking::BenchmarkConfig + ) -> Result, sp_runtime::RuntimeString> { + use frame_benchmarking::{Benchmarking, BenchmarkBatch, TrackedStorageKey}; + + use frame_system_benchmarking::Pallet as SystemBench; + impl frame_system_benchmarking::Config for Runtime {} + + use cumulus_pallet_session_benchmarking::Pallet as SessionBench; + impl cumulus_pallet_session_benchmarking::Config for Runtime {} + + let whitelist: Vec = vec![ + // Block Number + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(), + // Total Issuance + hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(), + // Execution Phase + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(), + // Event Count + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(), + // System Events + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(), + // Treasury Account + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da95ecffd7b6c0f78751baa9d281e0bfa3a6d6f646c70792f74727372790000000000000000000000000000000000000000").to_vec().into(), + ]; + + let mut batches = Vec::::new(); + let params = (&config, &whitelist); + add_benchmarks!(params, batches); + + if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } + Ok(batches) + } + } } struct CheckInherents; impl cumulus_pallet_parachain_system::CheckInherents for CheckInherents { - fn check_inherents( - block: &Block, - relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof, - ) -> sp_inherents::CheckInherentsResult { - let relay_chain_slot = relay_state_proof - .read_slot() - .expect("Could not read the relay chain slot from the proof"); - - let inherent_data = - cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration( - relay_chain_slot, - sp_std::time::Duration::from_secs(6), - ) - .create_inherent_data() - .expect("Could not create the timestamp inherent data"); - - inherent_data.check_extrinsics(block) - } + fn check_inherents( + block: &Block, + relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof, + ) -> sp_inherents::CheckInherentsResult { + let relay_chain_slot = relay_state_proof + .read_slot() + .expect("Could not read the relay chain slot from the proof"); + + let inherent_data = + cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration( + relay_chain_slot, + sp_std::time::Duration::from_secs(6), + ) + .create_inherent_data() + .expect("Could not create the timestamp inherent data"); + + inherent_data.check_extrinsics(block) + } } cumulus_pallet_parachain_system::register_validate_block! { - Runtime = Runtime, - BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::, - CheckInherents = CheckInherents, + Runtime = Runtime, + BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::, + CheckInherents = CheckInherents, } diff --git a/runtime/calamari/src/migrations/sudo.rs b/runtime/calamari/src/migrations/sudo.rs index 8daf36fd5..493c64fc9 100644 --- a/runtime/calamari/src/migrations/sudo.rs +++ b/runtime/calamari/src/migrations/sudo.rs @@ -16,44 +16,44 @@ use core::marker::PhantomData; use frame_support::{ - migration::{have_storage_value, remove_storage_prefix}, - pallet_prelude::Weight, - traits::{Get, OnRuntimeUpgrade}, + migration::{have_storage_value, remove_storage_prefix}, + pallet_prelude::Weight, + traits::{Get, OnRuntimeUpgrade}, }; pub struct RemoveSudo(PhantomData); impl OnRuntimeUpgrade for RemoveSudo { - fn on_runtime_upgrade() -> Weight { - if have_storage_value(b"Sudo", b"Key", b"") { - remove_storage_prefix(b"Sudo", b"Key", b""); - remove_storage_prefix(b"Sudo", b":__STORAGE_VERSION__:", b""); - log::info!(target: "OnRuntimeUpgrade", "✅ Sudo key has been removed."); - log::info!(target: "OnRuntimeUpgrade", "✅ The pallet version has been removed."); - T::DbWeight::get() - .reads(1 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } else { - T::DbWeight::get().reads(1 as Weight) - } - } + fn on_runtime_upgrade() -> Weight { + if have_storage_value(b"Sudo", b"Key", b"") { + remove_storage_prefix(b"Sudo", b"Key", b""); + remove_storage_prefix(b"Sudo", b":__STORAGE_VERSION__:", b""); + log::info!(target: "OnRuntimeUpgrade", "✅ Sudo key has been removed."); + log::info!(target: "OnRuntimeUpgrade", "✅ The pallet version has been removed."); + T::DbWeight::get() + .reads(1 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } else { + T::DbWeight::get().reads(1 as Weight) + } + } - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result<(), &'static str> { - if have_storage_value(b"Sudo", b"Key", b"") { - log::info!(target: "OnRuntimeUpgrade", "✅ Sudo key will be removed soon."); - log::info!(target: "OnRuntimeUpgrade", "✅ The pallet version will be removed soon."); - Ok(()) - } else { - Err("Sudo doesn't exist.") - } - } + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result<(), &'static str> { + if have_storage_value(b"Sudo", b"Key", b"") { + log::info!(target: "OnRuntimeUpgrade", "✅ Sudo key will be removed soon."); + log::info!(target: "OnRuntimeUpgrade", "✅ The pallet version will be removed soon."); + Ok(()) + } else { + Err("Sudo doesn't exist.") + } + } - #[cfg(feature = "try-runtime")] - fn post_upgrade() -> Result<(), &'static str> { - if have_storage_value(b"Sudo", b"Key", b"") { - Err("Failed to remove sudo module.") - } else { - Ok(()) - } - } + #[cfg(feature = "try-runtime")] + fn post_upgrade() -> Result<(), &'static str> { + if have_storage_value(b"Sudo", b"Key", b"") { + Err("Failed to remove sudo module.") + } else { + Ok(()) + } + } } diff --git a/runtime/calamari/src/weights/calamari_vesting.rs b/runtime/calamari/src/weights/calamari_vesting.rs index f4ec8696a..f23edf568 100644 --- a/runtime/calamari/src/weights/calamari_vesting.rs +++ b/runtime/calamari/src/weights/calamari_vesting.rs @@ -43,70 +43,70 @@ use sp_std::marker::PhantomData; /// Weight functions needed for calamari_vesting. pub trait WeightInfo { - fn update_vesting_schedule() -> Weight; - fn vest() -> Weight; - fn vested_transfer() -> Weight; + fn update_vesting_schedule() -> Weight; + fn vest() -> Weight; + fn vested_transfer() -> Weight; } /// Weights for calamari_vesting using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl calamari_vesting::WeightInfo for SubstrateWeight { - // Storage: CalamariVesting VestingSchedule (r:1 w:1) - // Storage: Timestamp Now (r:1 w:0) - fn update_vesting_schedule() -> Weight { - (13_520_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Timestamp Now (r:1 w:0) - // Storage: CalamariVesting VestingSchedule (r:1 w:0) - // Storage: CalamariVesting VestingBalances (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn vest() -> Weight { - (33_998_000 as Weight) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: CalamariVesting VestingBalances (r:1 w:1) - // Storage: System Account (r:1 w:1) - // Storage: Timestamp Now (r:1 w:0) - // Storage: CalamariVesting VestingSchedule (r:1 w:0) - // Storage: Balances Locks (r:1 w:1) - fn vested_transfer() -> Weight { - (57_623_000 as Weight) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } + // Storage: CalamariVesting VestingSchedule (r:1 w:1) + // Storage: Timestamp Now (r:1 w:0) + fn update_vesting_schedule() -> Weight { + (13_520_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Timestamp Now (r:1 w:0) + // Storage: CalamariVesting VestingSchedule (r:1 w:0) + // Storage: CalamariVesting VestingBalances (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn vest() -> Weight { + (33_998_000 as Weight) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: CalamariVesting VestingBalances (r:1 w:1) + // Storage: System Account (r:1 w:1) + // Storage: Timestamp Now (r:1 w:0) + // Storage: CalamariVesting VestingSchedule (r:1 w:0) + // Storage: Balances Locks (r:1 w:1) + fn vested_transfer() -> Weight { + (57_623_000 as Weight) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: CalamariVesting VestingSchedule (r:1 w:1) - // Storage: Timestamp Now (r:1 w:0) - fn update_vesting_schedule() -> Weight { - (13_520_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Timestamp Now (r:1 w:0) - // Storage: CalamariVesting VestingSchedule (r:1 w:0) - // Storage: CalamariVesting VestingBalances (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn vest() -> Weight { - (33_998_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: CalamariVesting VestingBalances (r:1 w:1) - // Storage: System Account (r:1 w:1) - // Storage: Timestamp Now (r:1 w:0) - // Storage: CalamariVesting VestingSchedule (r:1 w:0) - // Storage: Balances Locks (r:1 w:1) - fn vested_transfer() -> Weight { - (57_623_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } -} \ No newline at end of file + // Storage: CalamariVesting VestingSchedule (r:1 w:1) + // Storage: Timestamp Now (r:1 w:0) + fn update_vesting_schedule() -> Weight { + (13_520_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Timestamp Now (r:1 w:0) + // Storage: CalamariVesting VestingSchedule (r:1 w:0) + // Storage: CalamariVesting VestingBalances (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn vest() -> Weight { + (33_998_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: CalamariVesting VestingBalances (r:1 w:1) + // Storage: System Account (r:1 w:1) + // Storage: Timestamp Now (r:1 w:0) + // Storage: CalamariVesting VestingSchedule (r:1 w:0) + // Storage: Balances Locks (r:1 w:1) + fn vested_transfer() -> Weight { + (57_623_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } +} diff --git a/runtime/calamari/src/weights/cumulus_pallet_xcmp_queue.rs b/runtime/calamari/src/weights/cumulus_pallet_xcmp_queue.rs index 27847a358..5a8a30928 100644 --- a/runtime/calamari/src/weights/cumulus_pallet_xcmp_queue.rs +++ b/runtime/calamari/src/weights/cumulus_pallet_xcmp_queue.rs @@ -43,39 +43,39 @@ use sp_std::marker::PhantomData; /// Weight functions needed for cumulus_pallet_xcmp_queue. pub trait WeightInfo { - fn set_config_with_u32() -> Weight; - fn set_config_with_weight() -> Weight; + fn set_config_with_u32() -> Weight; + fn set_config_with_weight() -> Weight; } /// Weights for cumulus_pallet_xcmp_queue using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl cumulus_pallet_xcmp_queue::WeightInfo for SubstrateWeight { - // Storage: XcmpQueue QueueConfig (r:1 w:1) - fn set_config_with_u32() -> Weight { - (6_354_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: XcmpQueue QueueConfig (r:1 w:1) - fn set_config_with_weight() -> Weight { - (4_226_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } + // Storage: XcmpQueue QueueConfig (r:1 w:1) + fn set_config_with_u32() -> Weight { + (6_354_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: XcmpQueue QueueConfig (r:1 w:1) + fn set_config_with_weight() -> Weight { + (4_226_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: XcmpQueue QueueConfig (r:1 w:1) - fn set_config_with_u32() -> Weight { - (6_354_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: XcmpQueue QueueConfig (r:1 w:1) - fn set_config_with_weight() -> Weight { - (4_226_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } -} \ No newline at end of file + // Storage: XcmpQueue QueueConfig (r:1 w:1) + fn set_config_with_u32() -> Weight { + (6_354_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: XcmpQueue QueueConfig (r:1 w:1) + fn set_config_with_weight() -> Weight { + (4_226_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } +} diff --git a/runtime/calamari/src/weights/frame_system.rs b/runtime/calamari/src/weights/frame_system.rs index 7206cb291..5405e8f97 100644 --- a/runtime/calamari/src/weights/frame_system.rs +++ b/runtime/calamari/src/weights/frame_system.rs @@ -43,91 +43,91 @@ use sp_std::marker::PhantomData; /// Weight functions needed for frame_system. pub trait WeightInfo { - fn remark(b: u32, ) -> Weight; - fn remark_with_event(b: u32, ) -> Weight; - fn set_heap_pages() -> Weight; - fn set_storage(i: u32, ) -> Weight; - fn kill_storage(i: u32, ) -> Weight; - fn kill_prefix(p: u32, ) -> Weight; + fn remark(b: u32, ) -> Weight; + fn remark_with_event(b: u32, ) -> Weight; + fn set_heap_pages() -> Weight; + fn set_storage(i: u32, ) -> Weight; + fn kill_storage(i: u32, ) -> Weight; + fn kill_prefix(p: u32, ) -> Weight; } /// Weights for frame_system using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl frame_system::WeightInfo for SubstrateWeight { - fn remark(_b: u32, ) -> Weight { - (5_053_000 as Weight) - } - fn remark_with_event(b: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - } - // Storage: System Digest (r:1 w:1) - // Storage: unknown [0x3a686561707061676573] (r:0 w:1) - fn set_heap_pages() -> Weight { - (2_825_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Skipped Metadata (r:0 w:0) - fn set_storage(i: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((492_000 as Weight).saturating_mul(i as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) - } - // Storage: Skipped Metadata (r:0 w:0) - fn kill_storage(i: u32, ) -> Weight { - (2_162_000 as Weight) - // Standard Error: 0 - .saturating_add((346_000 as Weight).saturating_mul(i as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) - } - // Storage: Skipped Metadata (r:0 w:0) - fn kill_prefix(p: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 1_000 - .saturating_add((814_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) - } + fn remark(_b: u32, ) -> Weight { + (5_053_000 as Weight) + } + fn remark_with_event(b: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + } + // Storage: System Digest (r:1 w:1) + // Storage: unknown [0x3a686561707061676573] (r:0 w:1) + fn set_heap_pages() -> Weight { + (2_825_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Skipped Metadata (r:0 w:0) + fn set_storage(i: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((492_000 as Weight).saturating_mul(i as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) + } + // Storage: Skipped Metadata (r:0 w:0) + fn kill_storage(i: u32, ) -> Weight { + (2_162_000 as Weight) + // Standard Error: 0 + .saturating_add((346_000 as Weight).saturating_mul(i as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) + } + // Storage: Skipped Metadata (r:0 w:0) + fn kill_prefix(p: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 1_000 + .saturating_add((814_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) + } } // For backwards compatibility and tests impl WeightInfo for () { - fn remark(_b: u32, ) -> Weight { - (5_053_000 as Weight) - } - fn remark_with_event(b: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - } - // Storage: System Digest (r:1 w:1) - // Storage: unknown [0x3a686561707061676573] (r:0 w:1) - fn set_heap_pages() -> Weight { - (2_825_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Skipped Metadata (r:0 w:0) - fn set_storage(i: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((492_000 as Weight).saturating_mul(i as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) - } - // Storage: Skipped Metadata (r:0 w:0) - fn kill_storage(i: u32, ) -> Weight { - (2_162_000 as Weight) - // Standard Error: 0 - .saturating_add((346_000 as Weight).saturating_mul(i as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) - } - // Storage: Skipped Metadata (r:0 w:0) - fn kill_prefix(p: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 1_000 - .saturating_add((814_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) - } -} \ No newline at end of file + fn remark(_b: u32, ) -> Weight { + (5_053_000 as Weight) + } + fn remark_with_event(b: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + } + // Storage: System Digest (r:1 w:1) + // Storage: unknown [0x3a686561707061676573] (r:0 w:1) + fn set_heap_pages() -> Weight { + (2_825_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Skipped Metadata (r:0 w:0) + fn set_storage(i: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((492_000 as Weight).saturating_mul(i as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) + } + // Storage: Skipped Metadata (r:0 w:0) + fn kill_storage(i: u32, ) -> Weight { + (2_162_000 as Weight) + // Standard Error: 0 + .saturating_add((346_000 as Weight).saturating_mul(i as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) + } + // Storage: Skipped Metadata (r:0 w:0) + fn kill_prefix(p: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 1_000 + .saturating_add((814_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) + } +} diff --git a/runtime/calamari/src/weights/manta_collator_selection.rs b/runtime/calamari/src/weights/manta_collator_selection.rs index 8ab7cfe94..6e7545d31 100644 --- a/runtime/calamari/src/weights/manta_collator_selection.rs +++ b/runtime/calamari/src/weights/manta_collator_selection.rs @@ -43,210 +43,210 @@ use sp_std::marker::PhantomData; /// Weight functions needed for manta_collator_selection. pub trait WeightInfo { - fn set_invulnerables(b: u32, ) -> Weight; - fn set_desired_candidates() -> Weight; - fn set_candidacy_bond() -> Weight; - fn set_eviction_baseline() -> Weight; - fn set_eviction_tolerance() -> Weight; - fn register_as_candidate(c: u32, ) -> Weight; - fn leave_intent(c: u32, ) -> Weight; - fn remove_collator(c: u32, ) -> Weight; - fn register_candidate(c: u32, ) -> Weight; - fn note_author() -> Weight; - fn new_session(c: u32, ) -> Weight; + fn set_invulnerables(b: u32, ) -> Weight; + fn set_desired_candidates() -> Weight; + fn set_candidacy_bond() -> Weight; + fn set_eviction_baseline() -> Weight; + fn set_eviction_tolerance() -> Weight; + fn register_as_candidate(c: u32, ) -> Weight; + fn leave_intent(c: u32, ) -> Weight; + fn remove_collator(c: u32, ) -> Weight; + fn register_candidate(c: u32, ) -> Weight; + fn note_author() -> Weight; + fn new_session(c: u32, ) -> Weight; } /// Weights for manta_collator_selection using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl manta_collator_selection::WeightInfo for SubstrateWeight { - // Storage: CollatorSelection Invulnerables (r:0 w:1) - fn set_invulnerables(b: u32, ) -> Weight { - (9_445_000 as Weight) - // Standard Error: 15_000 - .saturating_add((115_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection DesiredCandidates (r:0 w:1) - fn set_desired_candidates() -> Weight { - (10_740_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection CandidacyBond (r:0 w:1) - fn set_candidacy_bond() -> Weight { - (9_190_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection EvictionBaseline (r:0 w:1) - fn set_eviction_baseline() -> Weight { - (8_851_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection EvictionTolerance (r:0 w:1) - fn set_eviction_tolerance() -> Weight { - (8_869_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:1) - // Storage: CollatorSelection DesiredCandidates (r:1 w:0) - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: Session NextKeys (r:1 w:0) - // Storage: CollatorSelection CandidacyBond (r:1 w:0) - fn register_as_candidate(c: u32, ) -> Weight { - (39_139_000 as Weight) - // Standard Error: 6_000 - .saturating_add((261_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:1) - fn leave_intent(c: u32, ) -> Weight { - (25_988_000 as Weight) - // Standard Error: 4_000 - .saturating_add((263_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: CollatorSelection Candidates (r:1 w:1) - fn remove_collator(c: u32, ) -> Weight { - (28_330_000 as Weight) - // Standard Error: 3_000 - .saturating_add((278_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:1) - // Storage: CollatorSelection DesiredCandidates (r:1 w:0) - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: Session NextKeys (r:1 w:0) - // Storage: CollatorSelection CandidacyBond (r:1 w:0) - fn register_candidate(c: u32, ) -> Weight { - (38_812_000 as Weight) - // Standard Error: 5_000 - .saturating_add((256_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:2 w:2) - // Storage: CollatorSelection BlocksPerCollatorThisSession (r:1 w:1) - // Storage: System BlockWeight (r:1 w:1) - fn note_author() -> Weight { - (35_513_000 as Weight) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:0) - // Storage: CollatorSelection EvictionBaseline (r:1 w:0) - // Storage: CollatorSelection EvictionTolerance (r:1 w:0) - // Storage: CollatorSelection BlocksPerCollatorThisSession (r:2 w:2) - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: System BlockWeight (r:1 w:1) - // Storage: Session Validators (r:1 w:0) - // Storage: System Account (r:1 w:1) - fn new_session(c: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 64_000 - .saturating_add((25_856_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads(6 as Weight)) - .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) - } + // Storage: CollatorSelection Invulnerables (r:0 w:1) + fn set_invulnerables(b: u32, ) -> Weight { + (9_445_000 as Weight) + // Standard Error: 15_000 + .saturating_add((115_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection DesiredCandidates (r:0 w:1) + fn set_desired_candidates() -> Weight { + (10_740_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection CandidacyBond (r:0 w:1) + fn set_candidacy_bond() -> Weight { + (9_190_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection EvictionBaseline (r:0 w:1) + fn set_eviction_baseline() -> Weight { + (8_851_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection EvictionTolerance (r:0 w:1) + fn set_eviction_tolerance() -> Weight { + (8_869_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:1) + // Storage: CollatorSelection DesiredCandidates (r:1 w:0) + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: Session NextKeys (r:1 w:0) + // Storage: CollatorSelection CandidacyBond (r:1 w:0) + fn register_as_candidate(c: u32, ) -> Weight { + (39_139_000 as Weight) + // Standard Error: 6_000 + .saturating_add((261_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:1) + fn leave_intent(c: u32, ) -> Weight { + (25_988_000 as Weight) + // Standard Error: 4_000 + .saturating_add((263_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: CollatorSelection Candidates (r:1 w:1) + fn remove_collator(c: u32, ) -> Weight { + (28_330_000 as Weight) + // Standard Error: 3_000 + .saturating_add((278_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:1) + // Storage: CollatorSelection DesiredCandidates (r:1 w:0) + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: Session NextKeys (r:1 w:0) + // Storage: CollatorSelection CandidacyBond (r:1 w:0) + fn register_candidate(c: u32, ) -> Weight { + (38_812_000 as Weight) + // Standard Error: 5_000 + .saturating_add((256_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:2 w:2) + // Storage: CollatorSelection BlocksPerCollatorThisSession (r:1 w:1) + // Storage: System BlockWeight (r:1 w:1) + fn note_author() -> Weight { + (35_513_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:0) + // Storage: CollatorSelection EvictionBaseline (r:1 w:0) + // Storage: CollatorSelection EvictionTolerance (r:1 w:0) + // Storage: CollatorSelection BlocksPerCollatorThisSession (r:2 w:2) + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: System BlockWeight (r:1 w:1) + // Storage: Session Validators (r:1 w:0) + // Storage: System Account (r:1 w:1) + fn new_session(c: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 64_000 + .saturating_add((25_856_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(6 as Weight)) + .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: CollatorSelection Invulnerables (r:0 w:1) - fn set_invulnerables(b: u32, ) -> Weight { - (9_445_000 as Weight) - // Standard Error: 15_000 - .saturating_add((115_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection DesiredCandidates (r:0 w:1) - fn set_desired_candidates() -> Weight { - (10_740_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection CandidacyBond (r:0 w:1) - fn set_candidacy_bond() -> Weight { - (9_190_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection EvictionBaseline (r:0 w:1) - fn set_eviction_baseline() -> Weight { - (8_851_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection EvictionTolerance (r:0 w:1) - fn set_eviction_tolerance() -> Weight { - (8_869_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:1) - // Storage: CollatorSelection DesiredCandidates (r:1 w:0) - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: Session NextKeys (r:1 w:0) - // Storage: CollatorSelection CandidacyBond (r:1 w:0) - fn register_as_candidate(c: u32, ) -> Weight { - (39_139_000 as Weight) - // Standard Error: 6_000 - .saturating_add((261_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:1) - fn leave_intent(c: u32, ) -> Weight { - (25_988_000 as Weight) - // Standard Error: 4_000 - .saturating_add((263_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: CollatorSelection Candidates (r:1 w:1) - fn remove_collator(c: u32, ) -> Weight { - (28_330_000 as Weight) - // Standard Error: 3_000 - .saturating_add((278_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:1) - // Storage: CollatorSelection DesiredCandidates (r:1 w:0) - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: Session NextKeys (r:1 w:0) - // Storage: CollatorSelection CandidacyBond (r:1 w:0) - fn register_candidate(c: u32, ) -> Weight { - (38_812_000 as Weight) - // Standard Error: 5_000 - .saturating_add((256_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:2 w:2) - // Storage: CollatorSelection BlocksPerCollatorThisSession (r:1 w:1) - // Storage: System BlockWeight (r:1 w:1) - fn note_author() -> Weight { - (35_513_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:0) - // Storage: CollatorSelection EvictionBaseline (r:1 w:0) - // Storage: CollatorSelection EvictionTolerance (r:1 w:0) - // Storage: CollatorSelection BlocksPerCollatorThisSession (r:2 w:2) - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: System BlockWeight (r:1 w:1) - // Storage: Session Validators (r:1 w:0) - // Storage: System Account (r:1 w:1) - fn new_session(c: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 64_000 - .saturating_add((25_856_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(RocksDbWeight::get().reads(6 as Weight)) - .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) - } -} \ No newline at end of file + // Storage: CollatorSelection Invulnerables (r:0 w:1) + fn set_invulnerables(b: u32, ) -> Weight { + (9_445_000 as Weight) + // Standard Error: 15_000 + .saturating_add((115_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection DesiredCandidates (r:0 w:1) + fn set_desired_candidates() -> Weight { + (10_740_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection CandidacyBond (r:0 w:1) + fn set_candidacy_bond() -> Weight { + (9_190_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection EvictionBaseline (r:0 w:1) + fn set_eviction_baseline() -> Weight { + (8_851_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection EvictionTolerance (r:0 w:1) + fn set_eviction_tolerance() -> Weight { + (8_869_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:1) + // Storage: CollatorSelection DesiredCandidates (r:1 w:0) + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: Session NextKeys (r:1 w:0) + // Storage: CollatorSelection CandidacyBond (r:1 w:0) + fn register_as_candidate(c: u32, ) -> Weight { + (39_139_000 as Weight) + // Standard Error: 6_000 + .saturating_add((261_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:1) + fn leave_intent(c: u32, ) -> Weight { + (25_988_000 as Weight) + // Standard Error: 4_000 + .saturating_add((263_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: CollatorSelection Candidates (r:1 w:1) + fn remove_collator(c: u32, ) -> Weight { + (28_330_000 as Weight) + // Standard Error: 3_000 + .saturating_add((278_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:1) + // Storage: CollatorSelection DesiredCandidates (r:1 w:0) + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: Session NextKeys (r:1 w:0) + // Storage: CollatorSelection CandidacyBond (r:1 w:0) + fn register_candidate(c: u32, ) -> Weight { + (38_812_000 as Weight) + // Standard Error: 5_000 + .saturating_add((256_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:2 w:2) + // Storage: CollatorSelection BlocksPerCollatorThisSession (r:1 w:1) + // Storage: System BlockWeight (r:1 w:1) + fn note_author() -> Weight { + (35_513_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:0) + // Storage: CollatorSelection EvictionBaseline (r:1 w:0) + // Storage: CollatorSelection EvictionTolerance (r:1 w:0) + // Storage: CollatorSelection BlocksPerCollatorThisSession (r:2 w:2) + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: System BlockWeight (r:1 w:1) + // Storage: Session Validators (r:1 w:0) + // Storage: System Account (r:1 w:1) + fn new_session(c: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 64_000 + .saturating_add((25_856_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(RocksDbWeight::get().reads(6 as Weight)) + .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) + } +} diff --git a/runtime/calamari/src/weights/pallet_asset_manager.rs b/runtime/calamari/src/weights/pallet_asset_manager.rs index c7c3e35e2..bbd9b4531 100644 --- a/runtime/calamari/src/weights/pallet_asset_manager.rs +++ b/runtime/calamari/src/weights/pallet_asset_manager.rs @@ -43,115 +43,115 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_asset_manager. pub trait WeightInfo { - fn register_asset() -> Weight; - fn set_units_per_second() -> Weight; - fn update_asset_location() -> Weight; - fn update_asset_metadata() -> Weight; - fn mint_asset() -> Weight; - fn set_min_xcm_fee() -> Weight; + fn register_asset() -> Weight; + fn set_units_per_second() -> Weight; + fn update_asset_location() -> Weight; + fn update_asset_metadata() -> Weight; + fn mint_asset() -> Weight; + fn set_min_xcm_fee() -> Weight; } /// Weights for pallet_asset_manager using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_asset_manager::WeightInfo for SubstrateWeight { - // Storage: AssetManager LocationAssetId (r:1 w:1) - // Storage: AssetManager NextAssetId (r:1 w:1) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Metadata (r:1 w:1) - // Storage: AssetManager AssetIdMetadata (r:0 w:1) - // Storage: AssetManager AssetIdLocation (r:0 w:1) - fn register_asset() -> Weight { - (37_954_000 as Weight) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(6 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: AssetManager UnitsPerSecond (r:0 w:1) - fn set_units_per_second() -> Weight { - (46_763_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:1) - // Storage: AssetManager LocationAssetId (r:1 w:2) - // Storage: AssetManager AllowedDestParaIds (r:1 w:1) - fn update_asset_location() -> Weight { - (62_667_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - // Storage: AssetManager AssetIdMetadata (r:0 w:1) - fn update_asset_metadata() -> Weight { - (63_177_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:1 w:1) - fn mint_asset() -> Weight { - (73_558_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: AssetManager MinXcmFee (r:0 w:1) - fn set_min_xcm_fee() -> Weight { - (43_240_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } + // Storage: AssetManager LocationAssetId (r:1 w:1) + // Storage: AssetManager NextAssetId (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + // Storage: AssetManager AssetIdLocation (r:0 w:1) + fn register_asset() -> Weight { + (37_954_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(6 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: AssetManager UnitsPerSecond (r:0 w:1) + fn set_units_per_second() -> Weight { + (46_763_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:1) + // Storage: AssetManager LocationAssetId (r:1 w:2) + // Storage: AssetManager AllowedDestParaIds (r:1 w:1) + fn update_asset_location() -> Weight { + (62_667_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + fn update_asset_metadata() -> Weight { + (63_177_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + fn mint_asset() -> Weight { + (73_558_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: AssetManager MinXcmFee (r:0 w:1) + fn set_min_xcm_fee() -> Weight { + (43_240_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: AssetManager LocationAssetId (r:1 w:1) - // Storage: AssetManager NextAssetId (r:1 w:1) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Metadata (r:1 w:1) - // Storage: AssetManager AssetIdMetadata (r:0 w:1) - // Storage: AssetManager AssetIdLocation (r:0 w:1) - fn register_asset() -> Weight { - (37_954_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(6 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: AssetManager UnitsPerSecond (r:0 w:1) - fn set_units_per_second() -> Weight { - (46_763_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:1) - // Storage: AssetManager LocationAssetId (r:1 w:2) - // Storage: AssetManager AllowedDestParaIds (r:1 w:1) - fn update_asset_location() -> Weight { - (62_667_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - // Storage: AssetManager AssetIdMetadata (r:0 w:1) - fn update_asset_metadata() -> Weight { - (63_177_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:1 w:1) - fn mint_asset() -> Weight { - (73_558_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: AssetManager MinXcmFee (r:0 w:1) - fn set_min_xcm_fee() -> Weight { - (43_240_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } -} \ No newline at end of file + // Storage: AssetManager LocationAssetId (r:1 w:1) + // Storage: AssetManager NextAssetId (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + // Storage: AssetManager AssetIdLocation (r:0 w:1) + fn register_asset() -> Weight { + (37_954_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(6 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: AssetManager UnitsPerSecond (r:0 w:1) + fn set_units_per_second() -> Weight { + (46_763_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:1) + // Storage: AssetManager LocationAssetId (r:1 w:2) + // Storage: AssetManager AllowedDestParaIds (r:1 w:1) + fn update_asset_location() -> Weight { + (62_667_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + fn update_asset_metadata() -> Weight { + (63_177_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + fn mint_asset() -> Weight { + (73_558_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: AssetManager MinXcmFee (r:0 w:1) + fn set_min_xcm_fee() -> Weight { + (43_240_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } +} diff --git a/runtime/calamari/src/weights/pallet_assets.rs b/runtime/calamari/src/weights/pallet_assets.rs index 64287f841..54af0b48d 100644 --- a/runtime/calamari/src/weights/pallet_assets.rs +++ b/runtime/calamari/src/weights/pallet_assets.rs @@ -43,390 +43,390 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_assets. pub trait WeightInfo { - fn create() -> Weight; - fn force_create() -> Weight; - fn destroy(c: u32, s: u32, a: u32, ) -> Weight; - fn mint() -> Weight; - fn burn() -> Weight; - fn transfer() -> Weight; - fn transfer_keep_alive() -> Weight; - fn force_transfer() -> Weight; - fn freeze() -> Weight; - fn thaw() -> Weight; - fn freeze_asset() -> Weight; - fn thaw_asset() -> Weight; - fn transfer_ownership() -> Weight; - fn set_team() -> Weight; - fn set_metadata(n: u32, s: u32, ) -> Weight; - fn clear_metadata() -> Weight; - fn force_set_metadata(n: u32, s: u32, ) -> Weight; - fn force_clear_metadata() -> Weight; - fn force_asset_status() -> Weight; - fn approve_transfer() -> Weight; - fn transfer_approved() -> Weight; - fn cancel_approval() -> Weight; - fn force_cancel_approval() -> Weight; + fn create() -> Weight; + fn force_create() -> Weight; + fn destroy(c: u32, s: u32, a: u32, ) -> Weight; + fn mint() -> Weight; + fn burn() -> Weight; + fn transfer() -> Weight; + fn transfer_keep_alive() -> Weight; + fn force_transfer() -> Weight; + fn freeze() -> Weight; + fn thaw() -> Weight; + fn freeze_asset() -> Weight; + fn thaw_asset() -> Weight; + fn transfer_ownership() -> Weight; + fn set_team() -> Weight; + fn set_metadata(n: u32, s: u32, ) -> Weight; + fn clear_metadata() -> Weight; + fn force_set_metadata(n: u32, s: u32, ) -> Weight; + fn force_clear_metadata() -> Weight; + fn force_asset_status() -> Weight; + fn approve_transfer() -> Weight; + fn transfer_approved() -> Weight; + fn cancel_approval() -> Weight; + fn force_cancel_approval() -> Weight; } /// Weights for pallet_assets using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_assets::WeightInfo for SubstrateWeight { - // Storage: Assets Asset (r:1 w:1) - fn create() -> Weight { - (13_274_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - fn force_create() -> Weight { - (12_654_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:5002 w:5001) - // Storage: System Account (r:5000 w:5000) - // Storage: Assets Metadata (r:1 w:0) - // Storage: Assets Approvals (r:501 w:500) - fn destroy(c: u32, s: u32, a: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 45_000 - .saturating_add((16_463_000 as Weight).saturating_mul(c as Weight)) - // Standard Error: 45_000 - .saturating_add((19_303_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 451_000 - .saturating_add((11_602_000 as Weight).saturating_mul(a as Weight)) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) - .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(a as Weight))) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) - .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(a as Weight))) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:1 w:1) - fn mint() -> Weight { - (28_167_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:1 w:1) - fn burn() -> Weight { - (33_054_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - // Storage: System Account (r:1 w:1) - fn transfer() -> Weight { - (47_084_000 as Weight) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - // Storage: System Account (r:1 w:1) - fn transfer_keep_alive() -> Weight { - (38_447_000 as Weight) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - // Storage: System Account (r:1 w:1) - fn force_transfer() -> Weight { - (47_645_000 as Weight) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Account (r:1 w:1) - fn freeze() -> Weight { - (18_711_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Account (r:1 w:1) - fn thaw() -> Weight { - (18_863_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - fn freeze_asset() -> Weight { - (14_778_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - fn thaw_asset() -> Weight { - (14_525_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Metadata (r:1 w:0) - fn transfer_ownership() -> Weight { - (16_111_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - fn set_team() -> Weight { - (14_353_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - fn set_metadata(_n: u32, s: u32, ) -> Weight { - (17_818_000 as Weight) - // Standard Error: 1_000 - .saturating_add((3_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - fn clear_metadata() -> Weight { - (17_817_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - fn force_set_metadata(_n: u32, _s: u32, ) -> Weight { - (16_060_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - fn force_clear_metadata() -> Weight { - (16_516_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - fn force_asset_status() -> Weight { - (13_864_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Approvals (r:1 w:1) - fn approve_transfer() -> Weight { - (21_418_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Assets Approvals (r:1 w:1) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - // Storage: System Account (r:1 w:1) - fn transfer_approved() -> Weight { - (54_371_000 as Weight) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().writes(5 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Approvals (r:1 w:1) - fn cancel_approval() -> Weight { - (22_205_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Approvals (r:1 w:1) - fn force_cancel_approval() -> Weight { - (22_021_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } + // Storage: Assets Asset (r:1 w:1) + fn create() -> Weight { + (13_274_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + fn force_create() -> Weight { + (12_654_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:5002 w:5001) + // Storage: System Account (r:5000 w:5000) + // Storage: Assets Metadata (r:1 w:0) + // Storage: Assets Approvals (r:501 w:500) + fn destroy(c: u32, s: u32, a: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 45_000 + .saturating_add((16_463_000 as Weight).saturating_mul(c as Weight)) + // Standard Error: 45_000 + .saturating_add((19_303_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 451_000 + .saturating_add((11_602_000 as Weight).saturating_mul(a as Weight)) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) + .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(a as Weight))) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) + .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(a as Weight))) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + fn mint() -> Weight { + (28_167_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + fn burn() -> Weight { + (33_054_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + // Storage: System Account (r:1 w:1) + fn transfer() -> Weight { + (47_084_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + // Storage: System Account (r:1 w:1) + fn transfer_keep_alive() -> Weight { + (38_447_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + // Storage: System Account (r:1 w:1) + fn force_transfer() -> Weight { + (47_645_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Account (r:1 w:1) + fn freeze() -> Weight { + (18_711_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Account (r:1 w:1) + fn thaw() -> Weight { + (18_863_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + fn freeze_asset() -> Weight { + (14_778_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + fn thaw_asset() -> Weight { + (14_525_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:0) + fn transfer_ownership() -> Weight { + (16_111_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + fn set_team() -> Weight { + (14_353_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + fn set_metadata(_n: u32, s: u32, ) -> Weight { + (17_818_000 as Weight) + // Standard Error: 1_000 + .saturating_add((3_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + fn clear_metadata() -> Weight { + (17_817_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + fn force_set_metadata(_n: u32, _s: u32, ) -> Weight { + (16_060_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + fn force_clear_metadata() -> Weight { + (16_516_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + fn force_asset_status() -> Weight { + (13_864_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Approvals (r:1 w:1) + fn approve_transfer() -> Weight { + (21_418_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Assets Approvals (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + // Storage: System Account (r:1 w:1) + fn transfer_approved() -> Weight { + (54_371_000 as Weight) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(5 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Approvals (r:1 w:1) + fn cancel_approval() -> Weight { + (22_205_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Approvals (r:1 w:1) + fn force_cancel_approval() -> Weight { + (22_021_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Assets Asset (r:1 w:1) - fn create() -> Weight { - (13_274_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - fn force_create() -> Weight { - (12_654_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:5002 w:5001) - // Storage: System Account (r:5000 w:5000) - // Storage: Assets Metadata (r:1 w:0) - // Storage: Assets Approvals (r:501 w:500) - fn destroy(c: u32, s: u32, a: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 45_000 - .saturating_add((16_463_000 as Weight).saturating_mul(c as Weight)) - // Standard Error: 45_000 - .saturating_add((19_303_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 451_000 - .saturating_add((11_602_000 as Weight).saturating_mul(a as Weight)) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) - .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(a as Weight))) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) - .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(a as Weight))) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:1 w:1) - fn mint() -> Weight { - (28_167_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:1 w:1) - fn burn() -> Weight { - (33_054_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - // Storage: System Account (r:1 w:1) - fn transfer() -> Weight { - (47_084_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - // Storage: System Account (r:1 w:1) - fn transfer_keep_alive() -> Weight { - (38_447_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - // Storage: System Account (r:1 w:1) - fn force_transfer() -> Weight { - (47_645_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Account (r:1 w:1) - fn freeze() -> Weight { - (18_711_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Account (r:1 w:1) - fn thaw() -> Weight { - (18_863_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - fn freeze_asset() -> Weight { - (14_778_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - fn thaw_asset() -> Weight { - (14_525_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Metadata (r:1 w:0) - fn transfer_ownership() -> Weight { - (16_111_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - fn set_team() -> Weight { - (14_353_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - fn set_metadata(_n: u32, s: u32, ) -> Weight { - (17_818_000 as Weight) - // Standard Error: 1_000 - .saturating_add((3_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - fn clear_metadata() -> Weight { - (17_817_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - fn force_set_metadata(_n: u32, _s: u32, ) -> Weight { - (16_060_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - fn force_clear_metadata() -> Weight { - (16_516_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - fn force_asset_status() -> Weight { - (13_864_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Approvals (r:1 w:1) - fn approve_transfer() -> Weight { - (21_418_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Assets Approvals (r:1 w:1) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - // Storage: System Account (r:1 w:1) - fn transfer_approved() -> Weight { - (54_371_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(5 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Approvals (r:1 w:1) - fn cancel_approval() -> Weight { - (22_205_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Approvals (r:1 w:1) - fn force_cancel_approval() -> Weight { - (22_021_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } -} \ No newline at end of file + // Storage: Assets Asset (r:1 w:1) + fn create() -> Weight { + (13_274_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + fn force_create() -> Weight { + (12_654_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:5002 w:5001) + // Storage: System Account (r:5000 w:5000) + // Storage: Assets Metadata (r:1 w:0) + // Storage: Assets Approvals (r:501 w:500) + fn destroy(c: u32, s: u32, a: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 45_000 + .saturating_add((16_463_000 as Weight).saturating_mul(c as Weight)) + // Standard Error: 45_000 + .saturating_add((19_303_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 451_000 + .saturating_add((11_602_000 as Weight).saturating_mul(a as Weight)) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) + .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(a as Weight))) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) + .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(a as Weight))) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + fn mint() -> Weight { + (28_167_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + fn burn() -> Weight { + (33_054_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + // Storage: System Account (r:1 w:1) + fn transfer() -> Weight { + (47_084_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + // Storage: System Account (r:1 w:1) + fn transfer_keep_alive() -> Weight { + (38_447_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + // Storage: System Account (r:1 w:1) + fn force_transfer() -> Weight { + (47_645_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Account (r:1 w:1) + fn freeze() -> Weight { + (18_711_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Account (r:1 w:1) + fn thaw() -> Weight { + (18_863_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + fn freeze_asset() -> Weight { + (14_778_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + fn thaw_asset() -> Weight { + (14_525_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:0) + fn transfer_ownership() -> Weight { + (16_111_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + fn set_team() -> Weight { + (14_353_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + fn set_metadata(_n: u32, s: u32, ) -> Weight { + (17_818_000 as Weight) + // Standard Error: 1_000 + .saturating_add((3_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + fn clear_metadata() -> Weight { + (17_817_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + fn force_set_metadata(_n: u32, _s: u32, ) -> Weight { + (16_060_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + fn force_clear_metadata() -> Weight { + (16_516_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + fn force_asset_status() -> Weight { + (13_864_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Approvals (r:1 w:1) + fn approve_transfer() -> Weight { + (21_418_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Assets Approvals (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + // Storage: System Account (r:1 w:1) + fn transfer_approved() -> Weight { + (54_371_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().writes(5 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Approvals (r:1 w:1) + fn cancel_approval() -> Weight { + (22_205_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Approvals (r:1 w:1) + fn force_cancel_approval() -> Weight { + (22_021_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } +} diff --git a/runtime/calamari/src/weights/pallet_balances.rs b/runtime/calamari/src/weights/pallet_balances.rs index c3ebc02e6..753b19568 100644 --- a/runtime/calamari/src/weights/pallet_balances.rs +++ b/runtime/calamari/src/weights/pallet_balances.rs @@ -43,104 +43,104 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_balances. pub trait WeightInfo { - fn transfer() -> Weight; - fn transfer_keep_alive() -> Weight; - fn set_balance_creating() -> Weight; - fn set_balance_killing() -> Weight; - fn force_transfer() -> Weight; - fn transfer_all() -> Weight; - fn force_unreserve() -> Weight; + fn transfer() -> Weight; + fn transfer_keep_alive() -> Weight; + fn set_balance_creating() -> Weight; + fn set_balance_killing() -> Weight; + fn force_transfer() -> Weight; + fn transfer_all() -> Weight; + fn force_unreserve() -> Weight; } /// Weights for pallet_balances using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_balances::WeightInfo for SubstrateWeight { - // Storage: System Account (r:1 w:1) - fn transfer() -> Weight { - (37_719_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn transfer_keep_alive() -> Weight { - (30_678_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn set_balance_creating() -> Weight { - (18_339_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn set_balance_killing() -> Weight { - (21_359_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:2 w:2) - fn force_transfer() -> Weight { - (40_352_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn transfer_all() -> Weight { - (36_133_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn force_unreserve() -> Weight { - (16_234_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } + // Storage: System Account (r:1 w:1) + fn transfer() -> Weight { + (37_719_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn transfer_keep_alive() -> Weight { + (30_678_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn set_balance_creating() -> Weight { + (18_339_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn set_balance_killing() -> Weight { + (21_359_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:2 w:2) + fn force_transfer() -> Weight { + (40_352_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn transfer_all() -> Weight { + (36_133_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn force_unreserve() -> Weight { + (16_234_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: System Account (r:1 w:1) - fn transfer() -> Weight { - (37_719_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn transfer_keep_alive() -> Weight { - (30_678_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn set_balance_creating() -> Weight { - (18_339_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn set_balance_killing() -> Weight { - (21_359_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:2 w:2) - fn force_transfer() -> Weight { - (40_352_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn transfer_all() -> Weight { - (36_133_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn force_unreserve() -> Weight { - (16_234_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } -} \ No newline at end of file + // Storage: System Account (r:1 w:1) + fn transfer() -> Weight { + (37_719_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn transfer_keep_alive() -> Weight { + (30_678_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn set_balance_creating() -> Weight { + (18_339_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn set_balance_killing() -> Weight { + (21_359_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:2 w:2) + fn force_transfer() -> Weight { + (40_352_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn transfer_all() -> Weight { + (36_133_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn force_unreserve() -> Weight { + (16_234_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } +} diff --git a/runtime/calamari/src/weights/pallet_collective.rs b/runtime/calamari/src/weights/pallet_collective.rs index 73d50d4ad..64b2541e0 100644 --- a/runtime/calamari/src/weights/pallet_collective.rs +++ b/runtime/calamari/src/weights/pallet_collective.rs @@ -43,281 +43,281 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_collective. pub trait WeightInfo { - fn set_members(m: u32, n: u32, p: u32, ) -> Weight; - fn execute(b: u32, m: u32, ) -> Weight; - fn propose_execute(b: u32, m: u32, ) -> Weight; - fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight; - fn vote(m: u32, ) -> Weight; - fn close_early_disapproved(m: u32, p: u32, ) -> Weight; - fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight; - fn close_disapproved(m: u32, p: u32, ) -> Weight; - fn close_approved(b: u32, m: u32, p: u32, ) -> Weight; - fn disapprove_proposal(p: u32, ) -> Weight; + fn set_members(m: u32, n: u32, p: u32, ) -> Weight; + fn execute(b: u32, m: u32, ) -> Weight; + fn propose_execute(b: u32, m: u32, ) -> Weight; + fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight; + fn vote(m: u32, ) -> Weight; + fn close_early_disapproved(m: u32, p: u32, ) -> Weight; + fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight; + fn close_disapproved(m: u32, p: u32, ) -> Weight; + fn close_approved(b: u32, m: u32, p: u32, ) -> Weight; + fn disapprove_proposal(p: u32, ) -> Weight; } /// Weights for pallet_collective using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_collective::WeightInfo for SubstrateWeight { - // Storage: Council Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: Council Voting (r:100 w:100) - // Storage: Council Prime (r:0 w:1) - fn set_members(m: u32, n: u32, p: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 7_000 - .saturating_add((13_575_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 7_000 - .saturating_add((126_000 as Weight).saturating_mul(n as Weight)) - // Standard Error: 7_000 - .saturating_add((16_516_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(p as Weight))) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) - } - // Storage: Council Members (r:1 w:0) - fn execute(b: u32, m: u32, ) -> Weight { - (13_115_000 as Weight) - // Standard Error: 0 - .saturating_add((3_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 0 - .saturating_add((35_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - } - // Storage: Council Members (r:1 w:0) - // Storage: Council ProposalOf (r:1 w:0) - fn propose_execute(b: u32, m: u32, ) -> Weight { - (16_224_000 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 0 - .saturating_add((57_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - } - // Storage: Council Members (r:1 w:0) - // Storage: Council ProposalOf (r:1 w:1) - // Storage: Council Proposals (r:1 w:1) - // Storage: Council ProposalCount (r:1 w:1) - // Storage: Council Voting (r:0 w:1) - fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight { - (19_781_000 as Weight) - // Standard Error: 0 - .saturating_add((8_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 1_000 - .saturating_add((43_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((202_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - } - // Storage: Council Members (r:1 w:0) - // Storage: Council Voting (r:1 w:1) - fn vote(m: u32, ) -> Weight { - (29_710_000 as Weight) - // Standard Error: 2_000 - .saturating_add((82_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Council Voting (r:1 w:1) - // Storage: Council Members (r:1 w:0) - // Storage: Council Proposals (r:1 w:1) - // Storage: Council ProposalOf (r:0 w:1) - fn close_early_disapproved(m: u32, p: u32, ) -> Weight { - (27_640_000 as Weight) - // Standard Error: 2_000 - .saturating_add((56_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((152_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Council Voting (r:1 w:1) - // Storage: Council Members (r:1 w:0) - // Storage: Council ProposalOf (r:1 w:1) - // Storage: Council Proposals (r:1 w:1) - fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight { - (28_103_000 as Weight) - // Standard Error: 0 - .saturating_add((8_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 1_000 - .saturating_add((80_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((213_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Council Voting (r:1 w:1) - // Storage: Council Members (r:1 w:0) - // Storage: Council Prime (r:1 w:0) - // Storage: Council Proposals (r:1 w:1) - // Storage: Council ProposalOf (r:0 w:1) - fn close_disapproved(m: u32, p: u32, ) -> Weight { - (29_000_000 as Weight) - // Standard Error: 1_000 - .saturating_add((75_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((157_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Council Voting (r:1 w:1) - // Storage: Council Members (r:1 w:0) - // Storage: Council Prime (r:1 w:0) - // Storage: Council ProposalOf (r:1 w:1) - // Storage: Council Proposals (r:1 w:1) - fn close_approved(b: u32, m: u32, p: u32, ) -> Weight { - (31_618_000 as Weight) - // Standard Error: 0 - .saturating_add((7_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 1_000 - .saturating_add((77_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((206_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Council Proposals (r:1 w:1) - // Storage: Council Voting (r:0 w:1) - // Storage: Council ProposalOf (r:0 w:1) - fn disapprove_proposal(p: u32, ) -> Weight { - (15_756_000 as Weight) - // Standard Error: 1_000 - .saturating_add((198_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } + // Storage: Council Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: Council Voting (r:100 w:100) + // Storage: Council Prime (r:0 w:1) + fn set_members(m: u32, n: u32, p: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 7_000 + .saturating_add((13_575_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 7_000 + .saturating_add((126_000 as Weight).saturating_mul(n as Weight)) + // Standard Error: 7_000 + .saturating_add((16_516_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(p as Weight))) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) + } + // Storage: Council Members (r:1 w:0) + fn execute(b: u32, m: u32, ) -> Weight { + (13_115_000 as Weight) + // Standard Error: 0 + .saturating_add((3_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 0 + .saturating_add((35_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + } + // Storage: Council Members (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:0) + fn propose_execute(b: u32, m: u32, ) -> Weight { + (16_224_000 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 0 + .saturating_add((57_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + } + // Storage: Council Members (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:1) + // Storage: Council Proposals (r:1 w:1) + // Storage: Council ProposalCount (r:1 w:1) + // Storage: Council Voting (r:0 w:1) + fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight { + (19_781_000 as Weight) + // Standard Error: 0 + .saturating_add((8_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 1_000 + .saturating_add((43_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 1_000 + .saturating_add((202_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + // Storage: Council Members (r:1 w:0) + // Storage: Council Voting (r:1 w:1) + fn vote(m: u32, ) -> Weight { + (29_710_000 as Weight) + // Standard Error: 2_000 + .saturating_add((82_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council Proposals (r:1 w:1) + // Storage: Council ProposalOf (r:0 w:1) + fn close_early_disapproved(m: u32, p: u32, ) -> Weight { + (27_640_000 as Weight) + // Standard Error: 2_000 + .saturating_add((56_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 1_000 + .saturating_add((152_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:1) + // Storage: Council Proposals (r:1 w:1) + fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight { + (28_103_000 as Weight) + // Standard Error: 0 + .saturating_add((8_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 1_000 + .saturating_add((80_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 1_000 + .saturating_add((213_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council Prime (r:1 w:0) + // Storage: Council Proposals (r:1 w:1) + // Storage: Council ProposalOf (r:0 w:1) + fn close_disapproved(m: u32, p: u32, ) -> Weight { + (29_000_000 as Weight) + // Standard Error: 1_000 + .saturating_add((75_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 1_000 + .saturating_add((157_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council Prime (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:1) + // Storage: Council Proposals (r:1 w:1) + fn close_approved(b: u32, m: u32, p: u32, ) -> Weight { + (31_618_000 as Weight) + // Standard Error: 0 + .saturating_add((7_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 1_000 + .saturating_add((77_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 1_000 + .saturating_add((206_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Council Proposals (r:1 w:1) + // Storage: Council Voting (r:0 w:1) + // Storage: Council ProposalOf (r:0 w:1) + fn disapprove_proposal(p: u32, ) -> Weight { + (15_756_000 as Weight) + // Standard Error: 1_000 + .saturating_add((198_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Council Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: Council Voting (r:100 w:100) - // Storage: Council Prime (r:0 w:1) - fn set_members(m: u32, n: u32, p: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 7_000 - .saturating_add((13_575_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 7_000 - .saturating_add((126_000 as Weight).saturating_mul(n as Weight)) - // Standard Error: 7_000 - .saturating_add((16_516_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(p as Weight))) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) - } - // Storage: Council Members (r:1 w:0) - fn execute(b: u32, m: u32, ) -> Weight { - (13_115_000 as Weight) - // Standard Error: 0 - .saturating_add((3_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 0 - .saturating_add((35_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - } - // Storage: Council Members (r:1 w:0) - // Storage: Council ProposalOf (r:1 w:0) - fn propose_execute(b: u32, m: u32, ) -> Weight { - (16_224_000 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 0 - .saturating_add((57_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - } - // Storage: Council Members (r:1 w:0) - // Storage: Council ProposalOf (r:1 w:1) - // Storage: Council Proposals (r:1 w:1) - // Storage: Council ProposalCount (r:1 w:1) - // Storage: Council Voting (r:0 w:1) - fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight { - (19_781_000 as Weight) - // Standard Error: 0 - .saturating_add((8_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 1_000 - .saturating_add((43_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((202_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - } - // Storage: Council Members (r:1 w:0) - // Storage: Council Voting (r:1 w:1) - fn vote(m: u32, ) -> Weight { - (29_710_000 as Weight) - // Standard Error: 2_000 - .saturating_add((82_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Council Voting (r:1 w:1) - // Storage: Council Members (r:1 w:0) - // Storage: Council Proposals (r:1 w:1) - // Storage: Council ProposalOf (r:0 w:1) - fn close_early_disapproved(m: u32, p: u32, ) -> Weight { - (27_640_000 as Weight) - // Standard Error: 2_000 - .saturating_add((56_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((152_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Council Voting (r:1 w:1) - // Storage: Council Members (r:1 w:0) - // Storage: Council ProposalOf (r:1 w:1) - // Storage: Council Proposals (r:1 w:1) - fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight { - (28_103_000 as Weight) - // Standard Error: 0 - .saturating_add((8_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 1_000 - .saturating_add((80_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((213_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Council Voting (r:1 w:1) - // Storage: Council Members (r:1 w:0) - // Storage: Council Prime (r:1 w:0) - // Storage: Council Proposals (r:1 w:1) - // Storage: Council ProposalOf (r:0 w:1) - fn close_disapproved(m: u32, p: u32, ) -> Weight { - (29_000_000 as Weight) - // Standard Error: 1_000 - .saturating_add((75_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((157_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Council Voting (r:1 w:1) - // Storage: Council Members (r:1 w:0) - // Storage: Council Prime (r:1 w:0) - // Storage: Council ProposalOf (r:1 w:1) - // Storage: Council Proposals (r:1 w:1) - fn close_approved(b: u32, m: u32, p: u32, ) -> Weight { - (31_618_000 as Weight) - // Standard Error: 0 - .saturating_add((7_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 1_000 - .saturating_add((77_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((206_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Council Proposals (r:1 w:1) - // Storage: Council Voting (r:0 w:1) - // Storage: Council ProposalOf (r:0 w:1) - fn disapprove_proposal(p: u32, ) -> Weight { - (15_756_000 as Weight) - // Standard Error: 1_000 - .saturating_add((198_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } -} \ No newline at end of file + // Storage: Council Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: Council Voting (r:100 w:100) + // Storage: Council Prime (r:0 w:1) + fn set_members(m: u32, n: u32, p: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 7_000 + .saturating_add((13_575_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 7_000 + .saturating_add((126_000 as Weight).saturating_mul(n as Weight)) + // Standard Error: 7_000 + .saturating_add((16_516_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(p as Weight))) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) + } + // Storage: Council Members (r:1 w:0) + fn execute(b: u32, m: u32, ) -> Weight { + (13_115_000 as Weight) + // Standard Error: 0 + .saturating_add((3_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 0 + .saturating_add((35_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + } + // Storage: Council Members (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:0) + fn propose_execute(b: u32, m: u32, ) -> Weight { + (16_224_000 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 0 + .saturating_add((57_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + } + // Storage: Council Members (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:1) + // Storage: Council Proposals (r:1 w:1) + // Storage: Council ProposalCount (r:1 w:1) + // Storage: Council Voting (r:0 w:1) + fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight { + (19_781_000 as Weight) + // Standard Error: 0 + .saturating_add((8_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 1_000 + .saturating_add((43_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 1_000 + .saturating_add((202_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + // Storage: Council Members (r:1 w:0) + // Storage: Council Voting (r:1 w:1) + fn vote(m: u32, ) -> Weight { + (29_710_000 as Weight) + // Standard Error: 2_000 + .saturating_add((82_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council Proposals (r:1 w:1) + // Storage: Council ProposalOf (r:0 w:1) + fn close_early_disapproved(m: u32, p: u32, ) -> Weight { + (27_640_000 as Weight) + // Standard Error: 2_000 + .saturating_add((56_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 1_000 + .saturating_add((152_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:1) + // Storage: Council Proposals (r:1 w:1) + fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight { + (28_103_000 as Weight) + // Standard Error: 0 + .saturating_add((8_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 1_000 + .saturating_add((80_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 1_000 + .saturating_add((213_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council Prime (r:1 w:0) + // Storage: Council Proposals (r:1 w:1) + // Storage: Council ProposalOf (r:0 w:1) + fn close_disapproved(m: u32, p: u32, ) -> Weight { + (29_000_000 as Weight) + // Standard Error: 1_000 + .saturating_add((75_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 1_000 + .saturating_add((157_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council Prime (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:1) + // Storage: Council Proposals (r:1 w:1) + fn close_approved(b: u32, m: u32, p: u32, ) -> Weight { + (31_618_000 as Weight) + // Standard Error: 0 + .saturating_add((7_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 1_000 + .saturating_add((77_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 1_000 + .saturating_add((206_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Council Proposals (r:1 w:1) + // Storage: Council Voting (r:0 w:1) + // Storage: Council ProposalOf (r:0 w:1) + fn disapprove_proposal(p: u32, ) -> Weight { + (15_756_000 as Weight) + // Standard Error: 1_000 + .saturating_add((198_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } +} diff --git a/runtime/calamari/src/weights/pallet_democracy.rs b/runtime/calamari/src/weights/pallet_democracy.rs index e3c28d315..52947771f 100644 --- a/runtime/calamari/src/weights/pallet_democracy.rs +++ b/runtime/calamari/src/weights/pallet_democracy.rs @@ -43,505 +43,505 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_democracy. pub trait WeightInfo { - fn propose() -> Weight; - fn second(s: u32, ) -> Weight; - fn vote_new(r: u32, ) -> Weight; - fn vote_existing(r: u32, ) -> Weight; - fn emergency_cancel() -> Weight; - fn blacklist(p: u32, ) -> Weight; - fn external_propose(v: u32, ) -> Weight; - fn external_propose_majority() -> Weight; - fn external_propose_default() -> Weight; - fn fast_track() -> Weight; - fn veto_external(v: u32, ) -> Weight; - fn cancel_proposal(p: u32, ) -> Weight; - fn cancel_referendum() -> Weight; - fn cancel_queued(r: u32, ) -> Weight; - fn on_initialize_base(r: u32, ) -> Weight; - fn on_initialize_base_with_launch_period(r: u32, ) -> Weight; - fn delegate(r: u32, ) -> Weight; - fn undelegate(r: u32, ) -> Weight; - fn clear_public_proposals() -> Weight; - fn note_preimage(b: u32, ) -> Weight; - fn note_imminent_preimage(b: u32, ) -> Weight; - fn reap_preimage(b: u32, ) -> Weight; - fn unlock_remove(r: u32, ) -> Weight; - fn unlock_set(r: u32, ) -> Weight; - fn remove_vote(r: u32, ) -> Weight; - fn remove_other_vote(r: u32, ) -> Weight; + fn propose() -> Weight; + fn second(s: u32, ) -> Weight; + fn vote_new(r: u32, ) -> Weight; + fn vote_existing(r: u32, ) -> Weight; + fn emergency_cancel() -> Weight; + fn blacklist(p: u32, ) -> Weight; + fn external_propose(v: u32, ) -> Weight; + fn external_propose_majority() -> Weight; + fn external_propose_default() -> Weight; + fn fast_track() -> Weight; + fn veto_external(v: u32, ) -> Weight; + fn cancel_proposal(p: u32, ) -> Weight; + fn cancel_referendum() -> Weight; + fn cancel_queued(r: u32, ) -> Weight; + fn on_initialize_base(r: u32, ) -> Weight; + fn on_initialize_base_with_launch_period(r: u32, ) -> Weight; + fn delegate(r: u32, ) -> Weight; + fn undelegate(r: u32, ) -> Weight; + fn clear_public_proposals() -> Weight; + fn note_preimage(b: u32, ) -> Weight; + fn note_imminent_preimage(b: u32, ) -> Weight; + fn reap_preimage(b: u32, ) -> Weight; + fn unlock_remove(r: u32, ) -> Weight; + fn unlock_set(r: u32, ) -> Weight; + fn remove_vote(r: u32, ) -> Weight; + fn remove_other_vote(r: u32, ) -> Weight; } /// Weights for pallet_democracy using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_democracy::WeightInfo for SubstrateWeight { - // Storage: Democracy PublicPropCount (r:1 w:1) - // Storage: Democracy PublicProps (r:1 w:1) - // Storage: Democracy Blacklist (r:1 w:0) - // Storage: Democracy DepositOf (r:0 w:1) - fn propose() -> Weight { - (48_151_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy DepositOf (r:1 w:1) - fn second(s: u32, ) -> Weight { - (27_784_000 as Weight) - // Standard Error: 1_000 - .saturating_add((128_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy VotingOf (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - fn vote_new(r: u32, ) -> Weight { - (36_711_000 as Weight) - // Standard Error: 2_000 - .saturating_add((148_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy VotingOf (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - fn vote_existing(r: u32, ) -> Weight { - (35_964_000 as Weight) - // Standard Error: 2_000 - .saturating_add((164_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy Cancellations (r:1 w:1) - fn emergency_cancel() -> Weight { - (15_069_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Democracy PublicProps (r:1 w:1) - // Storage: Democracy NextExternal (r:1 w:1) - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy Blacklist (r:0 w:1) - // Storage: Democracy DepositOf (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn blacklist(p: u32, ) -> Weight { - (46_812_000 as Weight) - // Standard Error: 3_000 - .saturating_add((201_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().writes(6 as Weight)) - } - // Storage: Democracy NextExternal (r:1 w:1) - // Storage: Democracy Blacklist (r:1 w:0) - fn external_propose(v: u32, ) -> Weight { - (8_439_000 as Weight) - // Standard Error: 0 - .saturating_add((33_000 as Weight).saturating_mul(v as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy NextExternal (r:0 w:1) - fn external_propose_majority() -> Weight { - (1_378_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy NextExternal (r:0 w:1) - fn external_propose_default() -> Weight { - (1_466_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy NextExternal (r:1 w:1) - // Storage: Democracy ReferendumCount (r:1 w:1) - // Storage: Democracy ReferendumInfoOf (r:0 w:1) - fn fast_track() -> Weight { - (17_470_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy NextExternal (r:1 w:1) - // Storage: Democracy Blacklist (r:1 w:1) - fn veto_external(v: u32, ) -> Weight { - (17_848_000 as Weight) - // Standard Error: 1_000 - .saturating_add((52_000 as Weight).saturating_mul(v as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Democracy PublicProps (r:1 w:1) - // Storage: Democracy DepositOf (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn cancel_proposal(p: u32, ) -> Weight { - (31_530_000 as Weight) - // Standard Error: 2_000 - .saturating_add((190_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:0 w:1) - fn cancel_referendum() -> Weight { - (10_034_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Scheduler Lookup (r:1 w:1) - // Storage: Scheduler Agenda (r:1 w:1) - fn cancel_queued(r: u32, ) -> Weight { - (22_336_000 as Weight) - // Standard Error: 3_000 - .saturating_add((1_701_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Democracy LowestUnbaked (r:1 w:1) - // Storage: Democracy ReferendumCount (r:1 w:0) - // Storage: Democracy ReferendumInfoOf (r:1 w:0) - fn on_initialize_base(r: u32, ) -> Weight { - (3_363_000 as Weight) - // Standard Error: 6_000 - .saturating_add((3_538_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy LowestUnbaked (r:1 w:1) - // Storage: Democracy ReferendumCount (r:1 w:0) - // Storage: Democracy LastTabledWasExternal (r:1 w:0) - // Storage: Democracy NextExternal (r:1 w:0) - // Storage: Democracy PublicProps (r:1 w:0) - // Storage: Democracy ReferendumInfoOf (r:1 w:0) - fn on_initialize_base_with_launch_period(r: u32, ) -> Weight { - (8_978_000 as Weight) - // Standard Error: 5_000 - .saturating_add((3_511_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy VotingOf (r:3 w:3) - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - fn delegate(r: u32, ) -> Weight { - (35_977_000 as Weight) - // Standard Error: 6_000 - .saturating_add((4_509_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(r as Weight))) - } - // Storage: Democracy VotingOf (r:2 w:2) - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - fn undelegate(r: u32, ) -> Weight { - (16_551_000 as Weight) - // Standard Error: 6_000 - .saturating_add((4_541_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(r as Weight))) - } - // Storage: Democracy PublicProps (r:0 w:1) - fn clear_public_proposals() -> Weight { - (1_682_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy Preimages (r:1 w:1) - fn note_preimage(b: u32, ) -> Weight { - (25_150_000 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy Preimages (r:1 w:1) - fn note_imminent_preimage(b: u32, ) -> Weight { - (16_617_000 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy Preimages (r:1 w:1) - // Storage: System Account (r:1 w:0) - fn reap_preimage(b: u32, ) -> Weight { - (25_063_000 as Weight) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy VotingOf (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn unlock_remove(r: u32, ) -> Weight { - (23_959_000 as Weight) - // Standard Error: 1_000 - .saturating_add((40_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy VotingOf (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn unlock_set(r: u32, ) -> Weight { - (22_717_000 as Weight) - // Standard Error: 2_000 - .saturating_add((126_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy VotingOf (r:1 w:1) - fn remove_vote(r: u32, ) -> Weight { - (13_575_000 as Weight) - // Standard Error: 1_000 - .saturating_add((120_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy VotingOf (r:1 w:1) - fn remove_other_vote(r: u32, ) -> Weight { - (13_694_000 as Weight) - // Standard Error: 1_000 - .saturating_add((124_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } + // Storage: Democracy PublicPropCount (r:1 w:1) + // Storage: Democracy PublicProps (r:1 w:1) + // Storage: Democracy Blacklist (r:1 w:0) + // Storage: Democracy DepositOf (r:0 w:1) + fn propose() -> Weight { + (48_151_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy DepositOf (r:1 w:1) + fn second(s: u32, ) -> Weight { + (27_784_000 as Weight) + // Standard Error: 1_000 + .saturating_add((128_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy VotingOf (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + fn vote_new(r: u32, ) -> Weight { + (36_711_000 as Weight) + // Standard Error: 2_000 + .saturating_add((148_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy VotingOf (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + fn vote_existing(r: u32, ) -> Weight { + (35_964_000 as Weight) + // Standard Error: 2_000 + .saturating_add((164_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy Cancellations (r:1 w:1) + fn emergency_cancel() -> Weight { + (15_069_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Democracy PublicProps (r:1 w:1) + // Storage: Democracy NextExternal (r:1 w:1) + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy Blacklist (r:0 w:1) + // Storage: Democracy DepositOf (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn blacklist(p: u32, ) -> Weight { + (46_812_000 as Weight) + // Standard Error: 3_000 + .saturating_add((201_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(6 as Weight)) + } + // Storage: Democracy NextExternal (r:1 w:1) + // Storage: Democracy Blacklist (r:1 w:0) + fn external_propose(v: u32, ) -> Weight { + (8_439_000 as Weight) + // Standard Error: 0 + .saturating_add((33_000 as Weight).saturating_mul(v as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy NextExternal (r:0 w:1) + fn external_propose_majority() -> Weight { + (1_378_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy NextExternal (r:0 w:1) + fn external_propose_default() -> Weight { + (1_466_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy NextExternal (r:1 w:1) + // Storage: Democracy ReferendumCount (r:1 w:1) + // Storage: Democracy ReferendumInfoOf (r:0 w:1) + fn fast_track() -> Weight { + (17_470_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy NextExternal (r:1 w:1) + // Storage: Democracy Blacklist (r:1 w:1) + fn veto_external(v: u32, ) -> Weight { + (17_848_000 as Weight) + // Standard Error: 1_000 + .saturating_add((52_000 as Weight).saturating_mul(v as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Democracy PublicProps (r:1 w:1) + // Storage: Democracy DepositOf (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn cancel_proposal(p: u32, ) -> Weight { + (31_530_000 as Weight) + // Standard Error: 2_000 + .saturating_add((190_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:0 w:1) + fn cancel_referendum() -> Weight { + (10_034_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Scheduler Lookup (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn cancel_queued(r: u32, ) -> Weight { + (22_336_000 as Weight) + // Standard Error: 3_000 + .saturating_add((1_701_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Democracy LowestUnbaked (r:1 w:1) + // Storage: Democracy ReferendumCount (r:1 w:0) + // Storage: Democracy ReferendumInfoOf (r:1 w:0) + fn on_initialize_base(r: u32, ) -> Weight { + (3_363_000 as Weight) + // Standard Error: 6_000 + .saturating_add((3_538_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy LowestUnbaked (r:1 w:1) + // Storage: Democracy ReferendumCount (r:1 w:0) + // Storage: Democracy LastTabledWasExternal (r:1 w:0) + // Storage: Democracy NextExternal (r:1 w:0) + // Storage: Democracy PublicProps (r:1 w:0) + // Storage: Democracy ReferendumInfoOf (r:1 w:0) + fn on_initialize_base_with_launch_period(r: u32, ) -> Weight { + (8_978_000 as Weight) + // Standard Error: 5_000 + .saturating_add((3_511_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy VotingOf (r:3 w:3) + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + fn delegate(r: u32, ) -> Weight { + (35_977_000 as Weight) + // Standard Error: 6_000 + .saturating_add((4_509_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(r as Weight))) + } + // Storage: Democracy VotingOf (r:2 w:2) + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + fn undelegate(r: u32, ) -> Weight { + (16_551_000 as Weight) + // Standard Error: 6_000 + .saturating_add((4_541_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(r as Weight))) + } + // Storage: Democracy PublicProps (r:0 w:1) + fn clear_public_proposals() -> Weight { + (1_682_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy Preimages (r:1 w:1) + fn note_preimage(b: u32, ) -> Weight { + (25_150_000 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy Preimages (r:1 w:1) + fn note_imminent_preimage(b: u32, ) -> Weight { + (16_617_000 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy Preimages (r:1 w:1) + // Storage: System Account (r:1 w:0) + fn reap_preimage(b: u32, ) -> Weight { + (25_063_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy VotingOf (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn unlock_remove(r: u32, ) -> Weight { + (23_959_000 as Weight) + // Standard Error: 1_000 + .saturating_add((40_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy VotingOf (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn unlock_set(r: u32, ) -> Weight { + (22_717_000 as Weight) + // Standard Error: 2_000 + .saturating_add((126_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy VotingOf (r:1 w:1) + fn remove_vote(r: u32, ) -> Weight { + (13_575_000 as Weight) + // Standard Error: 1_000 + .saturating_add((120_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy VotingOf (r:1 w:1) + fn remove_other_vote(r: u32, ) -> Weight { + (13_694_000 as Weight) + // Standard Error: 1_000 + .saturating_add((124_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Democracy PublicPropCount (r:1 w:1) - // Storage: Democracy PublicProps (r:1 w:1) - // Storage: Democracy Blacklist (r:1 w:0) - // Storage: Democracy DepositOf (r:0 w:1) - fn propose() -> Weight { - (48_151_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy DepositOf (r:1 w:1) - fn second(s: u32, ) -> Weight { - (27_784_000 as Weight) - // Standard Error: 1_000 - .saturating_add((128_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy VotingOf (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - fn vote_new(r: u32, ) -> Weight { - (36_711_000 as Weight) - // Standard Error: 2_000 - .saturating_add((148_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy VotingOf (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - fn vote_existing(r: u32, ) -> Weight { - (35_964_000 as Weight) - // Standard Error: 2_000 - .saturating_add((164_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy Cancellations (r:1 w:1) - fn emergency_cancel() -> Weight { - (15_069_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Democracy PublicProps (r:1 w:1) - // Storage: Democracy NextExternal (r:1 w:1) - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy Blacklist (r:0 w:1) - // Storage: Democracy DepositOf (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn blacklist(p: u32, ) -> Weight { - (46_812_000 as Weight) - // Standard Error: 3_000 - .saturating_add((201_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(6 as Weight)) - } - // Storage: Democracy NextExternal (r:1 w:1) - // Storage: Democracy Blacklist (r:1 w:0) - fn external_propose(v: u32, ) -> Weight { - (8_439_000 as Weight) - // Standard Error: 0 - .saturating_add((33_000 as Weight).saturating_mul(v as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy NextExternal (r:0 w:1) - fn external_propose_majority() -> Weight { - (1_378_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy NextExternal (r:0 w:1) - fn external_propose_default() -> Weight { - (1_466_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy NextExternal (r:1 w:1) - // Storage: Democracy ReferendumCount (r:1 w:1) - // Storage: Democracy ReferendumInfoOf (r:0 w:1) - fn fast_track() -> Weight { - (17_470_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy NextExternal (r:1 w:1) - // Storage: Democracy Blacklist (r:1 w:1) - fn veto_external(v: u32, ) -> Weight { - (17_848_000 as Weight) - // Standard Error: 1_000 - .saturating_add((52_000 as Weight).saturating_mul(v as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Democracy PublicProps (r:1 w:1) - // Storage: Democracy DepositOf (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn cancel_proposal(p: u32, ) -> Weight { - (31_530_000 as Weight) - // Standard Error: 2_000 - .saturating_add((190_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:0 w:1) - fn cancel_referendum() -> Weight { - (10_034_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Scheduler Lookup (r:1 w:1) - // Storage: Scheduler Agenda (r:1 w:1) - fn cancel_queued(r: u32, ) -> Weight { - (22_336_000 as Weight) - // Standard Error: 3_000 - .saturating_add((1_701_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Democracy LowestUnbaked (r:1 w:1) - // Storage: Democracy ReferendumCount (r:1 w:0) - // Storage: Democracy ReferendumInfoOf (r:1 w:0) - fn on_initialize_base(r: u32, ) -> Weight { - (3_363_000 as Weight) - // Standard Error: 6_000 - .saturating_add((3_538_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy LowestUnbaked (r:1 w:1) - // Storage: Democracy ReferendumCount (r:1 w:0) - // Storage: Democracy LastTabledWasExternal (r:1 w:0) - // Storage: Democracy NextExternal (r:1 w:0) - // Storage: Democracy PublicProps (r:1 w:0) - // Storage: Democracy ReferendumInfoOf (r:1 w:0) - fn on_initialize_base_with_launch_period(r: u32, ) -> Weight { - (8_978_000 as Weight) - // Standard Error: 5_000 - .saturating_add((3_511_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy VotingOf (r:3 w:3) - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - fn delegate(r: u32, ) -> Weight { - (35_977_000 as Weight) - // Standard Error: 6_000 - .saturating_add((4_509_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(r as Weight))) - } - // Storage: Democracy VotingOf (r:2 w:2) - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - fn undelegate(r: u32, ) -> Weight { - (16_551_000 as Weight) - // Standard Error: 6_000 - .saturating_add((4_541_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(r as Weight))) - } - // Storage: Democracy PublicProps (r:0 w:1) - fn clear_public_proposals() -> Weight { - (1_682_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy Preimages (r:1 w:1) - fn note_preimage(b: u32, ) -> Weight { - (25_150_000 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy Preimages (r:1 w:1) - fn note_imminent_preimage(b: u32, ) -> Weight { - (16_617_000 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy Preimages (r:1 w:1) - // Storage: System Account (r:1 w:0) - fn reap_preimage(b: u32, ) -> Weight { - (25_063_000 as Weight) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy VotingOf (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn unlock_remove(r: u32, ) -> Weight { - (23_959_000 as Weight) - // Standard Error: 1_000 - .saturating_add((40_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy VotingOf (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn unlock_set(r: u32, ) -> Weight { - (22_717_000 as Weight) - // Standard Error: 2_000 - .saturating_add((126_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy VotingOf (r:1 w:1) - fn remove_vote(r: u32, ) -> Weight { - (13_575_000 as Weight) - // Standard Error: 1_000 - .saturating_add((120_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy VotingOf (r:1 w:1) - fn remove_other_vote(r: u32, ) -> Weight { - (13_694_000 as Weight) - // Standard Error: 1_000 - .saturating_add((124_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } -} \ No newline at end of file + // Storage: Democracy PublicPropCount (r:1 w:1) + // Storage: Democracy PublicProps (r:1 w:1) + // Storage: Democracy Blacklist (r:1 w:0) + // Storage: Democracy DepositOf (r:0 w:1) + fn propose() -> Weight { + (48_151_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy DepositOf (r:1 w:1) + fn second(s: u32, ) -> Weight { + (27_784_000 as Weight) + // Standard Error: 1_000 + .saturating_add((128_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy VotingOf (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + fn vote_new(r: u32, ) -> Weight { + (36_711_000 as Weight) + // Standard Error: 2_000 + .saturating_add((148_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy VotingOf (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + fn vote_existing(r: u32, ) -> Weight { + (35_964_000 as Weight) + // Standard Error: 2_000 + .saturating_add((164_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy Cancellations (r:1 w:1) + fn emergency_cancel() -> Weight { + (15_069_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Democracy PublicProps (r:1 w:1) + // Storage: Democracy NextExternal (r:1 w:1) + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy Blacklist (r:0 w:1) + // Storage: Democracy DepositOf (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn blacklist(p: u32, ) -> Weight { + (46_812_000 as Weight) + // Standard Error: 3_000 + .saturating_add((201_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().writes(6 as Weight)) + } + // Storage: Democracy NextExternal (r:1 w:1) + // Storage: Democracy Blacklist (r:1 w:0) + fn external_propose(v: u32, ) -> Weight { + (8_439_000 as Weight) + // Standard Error: 0 + .saturating_add((33_000 as Weight).saturating_mul(v as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy NextExternal (r:0 w:1) + fn external_propose_majority() -> Weight { + (1_378_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy NextExternal (r:0 w:1) + fn external_propose_default() -> Weight { + (1_466_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy NextExternal (r:1 w:1) + // Storage: Democracy ReferendumCount (r:1 w:1) + // Storage: Democracy ReferendumInfoOf (r:0 w:1) + fn fast_track() -> Weight { + (17_470_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy NextExternal (r:1 w:1) + // Storage: Democracy Blacklist (r:1 w:1) + fn veto_external(v: u32, ) -> Weight { + (17_848_000 as Weight) + // Standard Error: 1_000 + .saturating_add((52_000 as Weight).saturating_mul(v as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Democracy PublicProps (r:1 w:1) + // Storage: Democracy DepositOf (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn cancel_proposal(p: u32, ) -> Weight { + (31_530_000 as Weight) + // Standard Error: 2_000 + .saturating_add((190_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:0 w:1) + fn cancel_referendum() -> Weight { + (10_034_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Scheduler Lookup (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn cancel_queued(r: u32, ) -> Weight { + (22_336_000 as Weight) + // Standard Error: 3_000 + .saturating_add((1_701_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Democracy LowestUnbaked (r:1 w:1) + // Storage: Democracy ReferendumCount (r:1 w:0) + // Storage: Democracy ReferendumInfoOf (r:1 w:0) + fn on_initialize_base(r: u32, ) -> Weight { + (3_363_000 as Weight) + // Standard Error: 6_000 + .saturating_add((3_538_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy LowestUnbaked (r:1 w:1) + // Storage: Democracy ReferendumCount (r:1 w:0) + // Storage: Democracy LastTabledWasExternal (r:1 w:0) + // Storage: Democracy NextExternal (r:1 w:0) + // Storage: Democracy PublicProps (r:1 w:0) + // Storage: Democracy ReferendumInfoOf (r:1 w:0) + fn on_initialize_base_with_launch_period(r: u32, ) -> Weight { + (8_978_000 as Weight) + // Standard Error: 5_000 + .saturating_add((3_511_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy VotingOf (r:3 w:3) + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + fn delegate(r: u32, ) -> Weight { + (35_977_000 as Weight) + // Standard Error: 6_000 + .saturating_add((4_509_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(r as Weight))) + } + // Storage: Democracy VotingOf (r:2 w:2) + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + fn undelegate(r: u32, ) -> Weight { + (16_551_000 as Weight) + // Standard Error: 6_000 + .saturating_add((4_541_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(r as Weight))) + } + // Storage: Democracy PublicProps (r:0 w:1) + fn clear_public_proposals() -> Weight { + (1_682_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy Preimages (r:1 w:1) + fn note_preimage(b: u32, ) -> Weight { + (25_150_000 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy Preimages (r:1 w:1) + fn note_imminent_preimage(b: u32, ) -> Weight { + (16_617_000 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy Preimages (r:1 w:1) + // Storage: System Account (r:1 w:0) + fn reap_preimage(b: u32, ) -> Weight { + (25_063_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy VotingOf (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn unlock_remove(r: u32, ) -> Weight { + (23_959_000 as Weight) + // Standard Error: 1_000 + .saturating_add((40_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy VotingOf (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn unlock_set(r: u32, ) -> Weight { + (22_717_000 as Weight) + // Standard Error: 2_000 + .saturating_add((126_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy VotingOf (r:1 w:1) + fn remove_vote(r: u32, ) -> Weight { + (13_575_000 as Weight) + // Standard Error: 1_000 + .saturating_add((120_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy VotingOf (r:1 w:1) + fn remove_other_vote(r: u32, ) -> Weight { + (13_694_000 as Weight) + // Standard Error: 1_000 + .saturating_add((124_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } +} diff --git a/runtime/calamari/src/weights/pallet_membership.rs b/runtime/calamari/src/weights/pallet_membership.rs index 7cb9ee03f..27ce75cc5 100644 --- a/runtime/calamari/src/weights/pallet_membership.rs +++ b/runtime/calamari/src/weights/pallet_membership.rs @@ -43,174 +43,174 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_membership. pub trait WeightInfo { - fn add_member(m: u32, ) -> Weight; - fn remove_member(m: u32, ) -> Weight; - fn swap_member(m: u32, ) -> Weight; - fn reset_member(m: u32, ) -> Weight; - fn change_key(m: u32, ) -> Weight; - fn set_prime(m: u32, ) -> Weight; - fn clear_prime(m: u32, ) -> Weight; + fn add_member(m: u32, ) -> Weight; + fn remove_member(m: u32, ) -> Weight; + fn swap_member(m: u32, ) -> Weight; + fn reset_member(m: u32, ) -> Weight; + fn change_key(m: u32, ) -> Weight; + fn set_prime(m: u32, ) -> Weight; + fn clear_prime(m: u32, ) -> Weight; } /// Weights for pallet_membership using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_membership::WeightInfo for SubstrateWeight { - // Storage: CouncilMembership Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: Council Members (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn add_member(m: u32, ) -> Weight { - (15_514_000 as Weight) - // Standard Error: 1_000 - .saturating_add((56_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: CouncilMembership Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: CouncilMembership Prime (r:1 w:0) - // Storage: Council Members (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn remove_member(m: u32, ) -> Weight { - (18_691_000 as Weight) - // Standard Error: 0 - .saturating_add((46_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: CouncilMembership Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: CouncilMembership Prime (r:1 w:0) - // Storage: Council Members (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn swap_member(m: u32, ) -> Weight { - (18_814_000 as Weight) - // Standard Error: 0 - .saturating_add((60_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: CouncilMembership Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: CouncilMembership Prime (r:1 w:0) - // Storage: Council Members (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn reset_member(m: u32, ) -> Weight { - (18_608_000 as Weight) - // Standard Error: 1_000 - .saturating_add((183_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: CouncilMembership Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: CouncilMembership Prime (r:1 w:1) - // Storage: Council Members (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn change_key(m: u32, ) -> Weight { - (19_595_000 as Weight) - // Standard Error: 1_000 - .saturating_add((58_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - } - // Storage: CouncilMembership Members (r:1 w:0) - // Storage: CouncilMembership Prime (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn set_prime(m: u32, ) -> Weight { - (5_348_000 as Weight) - // Standard Error: 0 - .saturating_add((31_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: CouncilMembership Prime (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn clear_prime(m: u32, ) -> Weight { - (1_740_000 as Weight) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } + // Storage: CouncilMembership Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn add_member(m: u32, ) -> Weight { + (15_514_000 as Weight) + // Standard Error: 1_000 + .saturating_add((56_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: CouncilMembership Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: CouncilMembership Prime (r:1 w:0) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn remove_member(m: u32, ) -> Weight { + (18_691_000 as Weight) + // Standard Error: 0 + .saturating_add((46_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: CouncilMembership Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: CouncilMembership Prime (r:1 w:0) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn swap_member(m: u32, ) -> Weight { + (18_814_000 as Weight) + // Standard Error: 0 + .saturating_add((60_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: CouncilMembership Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: CouncilMembership Prime (r:1 w:0) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn reset_member(m: u32, ) -> Weight { + (18_608_000 as Weight) + // Standard Error: 1_000 + .saturating_add((183_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: CouncilMembership Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: CouncilMembership Prime (r:1 w:1) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn change_key(m: u32, ) -> Weight { + (19_595_000 as Weight) + // Standard Error: 1_000 + .saturating_add((58_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + // Storage: CouncilMembership Members (r:1 w:0) + // Storage: CouncilMembership Prime (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn set_prime(m: u32, ) -> Weight { + (5_348_000 as Weight) + // Standard Error: 0 + .saturating_add((31_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: CouncilMembership Prime (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn clear_prime(m: u32, ) -> Weight { + (1_740_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: CouncilMembership Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: Council Members (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn add_member(m: u32, ) -> Weight { - (15_514_000 as Weight) - // Standard Error: 1_000 - .saturating_add((56_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: CouncilMembership Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: CouncilMembership Prime (r:1 w:0) - // Storage: Council Members (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn remove_member(m: u32, ) -> Weight { - (18_691_000 as Weight) - // Standard Error: 0 - .saturating_add((46_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: CouncilMembership Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: CouncilMembership Prime (r:1 w:0) - // Storage: Council Members (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn swap_member(m: u32, ) -> Weight { - (18_814_000 as Weight) - // Standard Error: 0 - .saturating_add((60_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: CouncilMembership Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: CouncilMembership Prime (r:1 w:0) - // Storage: Council Members (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn reset_member(m: u32, ) -> Weight { - (18_608_000 as Weight) - // Standard Error: 1_000 - .saturating_add((183_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: CouncilMembership Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: CouncilMembership Prime (r:1 w:1) - // Storage: Council Members (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn change_key(m: u32, ) -> Weight { - (19_595_000 as Weight) - // Standard Error: 1_000 - .saturating_add((58_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - } - // Storage: CouncilMembership Members (r:1 w:0) - // Storage: CouncilMembership Prime (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn set_prime(m: u32, ) -> Weight { - (5_348_000 as Weight) - // Standard Error: 0 - .saturating_add((31_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: CouncilMembership Prime (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn clear_prime(m: u32, ) -> Weight { - (1_740_000 as Weight) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } -} \ No newline at end of file + // Storage: CouncilMembership Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn add_member(m: u32, ) -> Weight { + (15_514_000 as Weight) + // Standard Error: 1_000 + .saturating_add((56_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: CouncilMembership Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: CouncilMembership Prime (r:1 w:0) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn remove_member(m: u32, ) -> Weight { + (18_691_000 as Weight) + // Standard Error: 0 + .saturating_add((46_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: CouncilMembership Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: CouncilMembership Prime (r:1 w:0) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn swap_member(m: u32, ) -> Weight { + (18_814_000 as Weight) + // Standard Error: 0 + .saturating_add((60_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: CouncilMembership Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: CouncilMembership Prime (r:1 w:0) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn reset_member(m: u32, ) -> Weight { + (18_608_000 as Weight) + // Standard Error: 1_000 + .saturating_add((183_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: CouncilMembership Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: CouncilMembership Prime (r:1 w:1) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn change_key(m: u32, ) -> Weight { + (19_595_000 as Weight) + // Standard Error: 1_000 + .saturating_add((58_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + // Storage: CouncilMembership Members (r:1 w:0) + // Storage: CouncilMembership Prime (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn set_prime(m: u32, ) -> Weight { + (5_348_000 as Weight) + // Standard Error: 0 + .saturating_add((31_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: CouncilMembership Prime (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn clear_prime(m: u32, ) -> Weight { + (1_740_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } +} diff --git a/runtime/calamari/src/weights/pallet_multisig.rs b/runtime/calamari/src/weights/pallet_multisig.rs index d1e4ace21..a11883bad 100644 --- a/runtime/calamari/src/weights/pallet_multisig.rs +++ b/runtime/calamari/src/weights/pallet_multisig.rs @@ -43,219 +43,219 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_multisig. pub trait WeightInfo { - fn as_multi_threshold_1(z: u32, ) -> Weight; - fn as_multi_create(s: u32, z: u32, ) -> Weight; - fn as_multi_create_store(s: u32, z: u32, ) -> Weight; - fn as_multi_approve(s: u32, z: u32, ) -> Weight; - fn as_multi_approve_store(s: u32, z: u32, ) -> Weight; - fn as_multi_complete(s: u32, z: u32, ) -> Weight; - fn approve_as_multi_create(s: u32, ) -> Weight; - fn approve_as_multi_approve(s: u32, ) -> Weight; - fn approve_as_multi_complete(s: u32, ) -> Weight; - fn cancel_as_multi(s: u32, ) -> Weight; + fn as_multi_threshold_1(z: u32, ) -> Weight; + fn as_multi_create(s: u32, z: u32, ) -> Weight; + fn as_multi_create_store(s: u32, z: u32, ) -> Weight; + fn as_multi_approve(s: u32, z: u32, ) -> Weight; + fn as_multi_approve_store(s: u32, z: u32, ) -> Weight; + fn as_multi_complete(s: u32, z: u32, ) -> Weight; + fn approve_as_multi_create(s: u32, ) -> Weight; + fn approve_as_multi_approve(s: u32, ) -> Weight; + fn approve_as_multi_complete(s: u32, ) -> Weight; + fn cancel_as_multi(s: u32, ) -> Weight; } /// Weights for pallet_multisig using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_multisig::WeightInfo for SubstrateWeight { - fn as_multi_threshold_1(z: u32, ) -> Weight { - (14_218_000 as Weight) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) - fn as_multi_create(s: u32, z: u32, ) -> Weight { - (34_058_000 as Weight) - // Standard Error: 1_000 - .saturating_add((92_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) - fn as_multi_create_store(s: u32, z: u32, ) -> Weight { - (37_900_000 as Weight) - // Standard Error: 1_000 - .saturating_add((91_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - fn as_multi_approve(s: u32, z: u32, ) -> Weight { - (21_689_000 as Weight) - // Standard Error: 1_000 - .saturating_add((89_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - fn as_multi_approve_store(s: u32, z: u32, ) -> Weight { - (34_644_000 as Weight) - // Standard Error: 2_000 - .saturating_add((104_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn as_multi_complete(s: u32, z: u32, ) -> Weight { - (45_679_000 as Weight) - // Standard Error: 2_000 - .saturating_add((132_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) - fn approve_as_multi_create(s: u32, ) -> Weight { - (31_057_000 as Weight) - // Standard Error: 1_000 - .saturating_add((110_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:0) - fn approve_as_multi_approve(s: u32, ) -> Weight { - (17_981_000 as Weight) - // Standard Error: 1_000 - .saturating_add((114_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn approve_as_multi_complete(s: u32, ) -> Weight { - (62_907_000 as Weight) - // Standard Error: 1_000 - .saturating_add((151_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - fn cancel_as_multi(s: u32, ) -> Weight { - (49_147_000 as Weight) - // Standard Error: 1_000 - .saturating_add((127_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } + fn as_multi_threshold_1(z: u32, ) -> Weight { + (14_218_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) + fn as_multi_create(s: u32, z: u32, ) -> Weight { + (34_058_000 as Weight) + // Standard Error: 1_000 + .saturating_add((92_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) + fn as_multi_create_store(s: u32, z: u32, ) -> Weight { + (37_900_000 as Weight) + // Standard Error: 1_000 + .saturating_add((91_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + fn as_multi_approve(s: u32, z: u32, ) -> Weight { + (21_689_000 as Weight) + // Standard Error: 1_000 + .saturating_add((89_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + fn as_multi_approve_store(s: u32, z: u32, ) -> Weight { + (34_644_000 as Weight) + // Standard Error: 2_000 + .saturating_add((104_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn as_multi_complete(s: u32, z: u32, ) -> Weight { + (45_679_000 as Weight) + // Standard Error: 2_000 + .saturating_add((132_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) + fn approve_as_multi_create(s: u32, ) -> Weight { + (31_057_000 as Weight) + // Standard Error: 1_000 + .saturating_add((110_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:0) + fn approve_as_multi_approve(s: u32, ) -> Weight { + (17_981_000 as Weight) + // Standard Error: 1_000 + .saturating_add((114_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn approve_as_multi_complete(s: u32, ) -> Weight { + (62_907_000 as Weight) + // Standard Error: 1_000 + .saturating_add((151_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + fn cancel_as_multi(s: u32, ) -> Weight { + (49_147_000 as Weight) + // Standard Error: 1_000 + .saturating_add((127_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - fn as_multi_threshold_1(z: u32, ) -> Weight { - (14_218_000 as Weight) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) - fn as_multi_create(s: u32, z: u32, ) -> Weight { - (34_058_000 as Weight) - // Standard Error: 1_000 - .saturating_add((92_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) - fn as_multi_create_store(s: u32, z: u32, ) -> Weight { - (37_900_000 as Weight) - // Standard Error: 1_000 - .saturating_add((91_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - fn as_multi_approve(s: u32, z: u32, ) -> Weight { - (21_689_000 as Weight) - // Standard Error: 1_000 - .saturating_add((89_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - fn as_multi_approve_store(s: u32, z: u32, ) -> Weight { - (34_644_000 as Weight) - // Standard Error: 2_000 - .saturating_add((104_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn as_multi_complete(s: u32, z: u32, ) -> Weight { - (45_679_000 as Weight) - // Standard Error: 2_000 - .saturating_add((132_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) - fn approve_as_multi_create(s: u32, ) -> Weight { - (31_057_000 as Weight) - // Standard Error: 1_000 - .saturating_add((110_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:0) - fn approve_as_multi_approve(s: u32, ) -> Weight { - (17_981_000 as Weight) - // Standard Error: 1_000 - .saturating_add((114_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn approve_as_multi_complete(s: u32, ) -> Weight { - (62_907_000 as Weight) - // Standard Error: 1_000 - .saturating_add((151_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - fn cancel_as_multi(s: u32, ) -> Weight { - (49_147_000 as Weight) - // Standard Error: 1_000 - .saturating_add((127_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } -} \ No newline at end of file + fn as_multi_threshold_1(z: u32, ) -> Weight { + (14_218_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) + fn as_multi_create(s: u32, z: u32, ) -> Weight { + (34_058_000 as Weight) + // Standard Error: 1_000 + .saturating_add((92_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) + fn as_multi_create_store(s: u32, z: u32, ) -> Weight { + (37_900_000 as Weight) + // Standard Error: 1_000 + .saturating_add((91_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + fn as_multi_approve(s: u32, z: u32, ) -> Weight { + (21_689_000 as Weight) + // Standard Error: 1_000 + .saturating_add((89_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + fn as_multi_approve_store(s: u32, z: u32, ) -> Weight { + (34_644_000 as Weight) + // Standard Error: 2_000 + .saturating_add((104_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn as_multi_complete(s: u32, z: u32, ) -> Weight { + (45_679_000 as Weight) + // Standard Error: 2_000 + .saturating_add((132_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) + fn approve_as_multi_create(s: u32, ) -> Weight { + (31_057_000 as Weight) + // Standard Error: 1_000 + .saturating_add((110_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:0) + fn approve_as_multi_approve(s: u32, ) -> Weight { + (17_981_000 as Weight) + // Standard Error: 1_000 + .saturating_add((114_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn approve_as_multi_complete(s: u32, ) -> Weight { + (62_907_000 as Weight) + // Standard Error: 1_000 + .saturating_add((151_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + fn cancel_as_multi(s: u32, ) -> Weight { + (49_147_000 as Weight) + // Standard Error: 1_000 + .saturating_add((127_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } +} diff --git a/runtime/calamari/src/weights/pallet_preimage.rs b/runtime/calamari/src/weights/pallet_preimage.rs index a00a13a8b..2489481eb 100644 --- a/runtime/calamari/src/weights/pallet_preimage.rs +++ b/runtime/calamari/src/weights/pallet_preimage.rs @@ -43,195 +43,195 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_preimage. pub trait WeightInfo { - fn note_preimage(s: u32, ) -> Weight; - fn note_requested_preimage(s: u32, ) -> Weight; - fn note_no_deposit_preimage(s: u32, ) -> Weight; - fn unnote_preimage() -> Weight; - fn unnote_no_deposit_preimage() -> Weight; - fn request_preimage() -> Weight; - fn request_no_deposit_preimage() -> Weight; - fn request_unnoted_preimage() -> Weight; - fn request_requested_preimage() -> Weight; - fn unrequest_preimage() -> Weight; - fn unrequest_unnoted_preimage() -> Weight; - fn unrequest_multi_referenced_preimage() -> Weight; + fn note_preimage(s: u32, ) -> Weight; + fn note_requested_preimage(s: u32, ) -> Weight; + fn note_no_deposit_preimage(s: u32, ) -> Weight; + fn unnote_preimage() -> Weight; + fn unnote_no_deposit_preimage() -> Weight; + fn request_preimage() -> Weight; + fn request_no_deposit_preimage() -> Weight; + fn request_unnoted_preimage() -> Weight; + fn request_requested_preimage() -> Weight; + fn unrequest_preimage() -> Weight; + fn unrequest_unnoted_preimage() -> Weight; + fn unrequest_multi_referenced_preimage() -> Weight; } /// Weights for pallet_preimage using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_preimage::WeightInfo for SubstrateWeight { - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - fn note_preimage(s: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:0) - fn note_requested_preimage(s: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:0) - fn note_no_deposit_preimage(s: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unnote_preimage() -> Weight { - (31_129_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unnote_no_deposit_preimage() -> Weight { - (17_780_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_preimage() -> Weight { - (29_767_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_no_deposit_preimage() -> Weight { - (17_007_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_unnoted_preimage() -> Weight { - (12_871_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_requested_preimage() -> Weight { - (4_889_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unrequest_preimage() -> Weight { - (17_482_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unrequest_unnoted_preimage() -> Weight { - (13_928_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn unrequest_multi_referenced_preimage() -> Weight { - (4_881_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + fn note_preimage(s: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:0) + fn note_requested_preimage(s: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:0) + fn note_no_deposit_preimage(s: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unnote_preimage() -> Weight { + (31_129_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unnote_no_deposit_preimage() -> Weight { + (17_780_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_preimage() -> Weight { + (29_767_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_no_deposit_preimage() -> Weight { + (17_007_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_unnoted_preimage() -> Weight { + (12_871_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_requested_preimage() -> Weight { + (4_889_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unrequest_preimage() -> Weight { + (17_482_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unrequest_unnoted_preimage() -> Weight { + (13_928_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn unrequest_multi_referenced_preimage() -> Weight { + (4_881_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - fn note_preimage(s: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:0) - fn note_requested_preimage(s: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:0) - fn note_no_deposit_preimage(s: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unnote_preimage() -> Weight { - (31_129_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unnote_no_deposit_preimage() -> Weight { - (17_780_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_preimage() -> Weight { - (29_767_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_no_deposit_preimage() -> Weight { - (17_007_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_unnoted_preimage() -> Weight { - (12_871_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_requested_preimage() -> Weight { - (4_889_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unrequest_preimage() -> Weight { - (17_482_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unrequest_unnoted_preimage() -> Weight { - (13_928_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn unrequest_multi_referenced_preimage() -> Weight { - (4_881_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } -} \ No newline at end of file + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + fn note_preimage(s: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:0) + fn note_requested_preimage(s: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:0) + fn note_no_deposit_preimage(s: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unnote_preimage() -> Weight { + (31_129_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unnote_no_deposit_preimage() -> Weight { + (17_780_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_preimage() -> Weight { + (29_767_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_no_deposit_preimage() -> Weight { + (17_007_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_unnoted_preimage() -> Weight { + (12_871_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_requested_preimage() -> Weight { + (4_889_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unrequest_preimage() -> Weight { + (17_482_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unrequest_unnoted_preimage() -> Weight { + (13_928_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn unrequest_multi_referenced_preimage() -> Weight { + (4_881_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } +} diff --git a/runtime/calamari/src/weights/pallet_scheduler.rs b/runtime/calamari/src/weights/pallet_scheduler.rs index 680b50a29..e18608bf5 100644 --- a/runtime/calamari/src/weights/pallet_scheduler.rs +++ b/runtime/calamari/src/weights/pallet_scheduler.rs @@ -43,319 +43,319 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_scheduler. pub trait WeightInfo { - fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight; - fn on_initialize_named_resolved(s: u32, ) -> Weight; - fn on_initialize_periodic_resolved(s: u32, ) -> Weight; - fn on_initialize_resolved(s: u32, ) -> Weight; - fn on_initialize_named_aborted(s: u32, ) -> Weight; - fn on_initialize_aborted(s: u32, ) -> Weight; - fn on_initialize_periodic_named(s: u32, ) -> Weight; - fn on_initialize_periodic(s: u32, ) -> Weight; - fn on_initialize_named(s: u32, ) -> Weight; - fn on_initialize(s: u32, ) -> Weight; - fn schedule(s: u32, ) -> Weight; - fn cancel(s: u32, ) -> Weight; - fn schedule_named(s: u32, ) -> Weight; - fn cancel_named(s: u32, ) -> Weight; + fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight; + fn on_initialize_named_resolved(s: u32, ) -> Weight; + fn on_initialize_periodic_resolved(s: u32, ) -> Weight; + fn on_initialize_resolved(s: u32, ) -> Weight; + fn on_initialize_named_aborted(s: u32, ) -> Weight; + fn on_initialize_aborted(s: u32, ) -> Weight; + fn on_initialize_periodic_named(s: u32, ) -> Weight; + fn on_initialize_periodic(s: u32, ) -> Weight; + fn on_initialize_named(s: u32, ) -> Weight; + fn on_initialize(s: u32, ) -> Weight; + fn schedule(s: u32, ) -> Weight; + fn cancel(s: u32, ) -> Weight; + fn schedule_named(s: u32, ) -> Weight; + fn cancel_named(s: u32, ) -> Weight; } /// Weights for pallet_scheduler using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_scheduler::WeightInfo for SubstrateWeight { - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight { - (18_537_000 as Weight) - // Standard Error: 47_000 - .saturating_add((24_566_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((4 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_named_resolved(s: u32, ) -> Weight { - (10_325_000 as Weight) - // Standard Error: 44_000 - .saturating_add((19_761_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - fn on_initialize_periodic_resolved(s: u32, ) -> Weight { - (13_329_000 as Weight) - // Standard Error: 52_000 - .saturating_add((21_827_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - fn on_initialize_resolved(s: u32, ) -> Weight { - (8_330_000 as Weight) - // Standard Error: 46_000 - .saturating_add((18_544_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:0) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_named_aborted(s: u32, ) -> Weight { - (6_978_000 as Weight) - // Standard Error: 28_000 - .saturating_add((8_749_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:0) - fn on_initialize_aborted(s: u32, ) -> Weight { - (8_474_000 as Weight) - // Standard Error: 20_000 - .saturating_add((5_951_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_periodic_named(s: u32, ) -> Weight { - (14_119_000 as Weight) - // Standard Error: 40_000 - .saturating_add((13_761_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - fn on_initialize_periodic(s: u32, ) -> Weight { - (13_428_000 as Weight) - // Standard Error: 34_000 - .saturating_add((10_782_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_named(s: u32, ) -> Weight { - (12_496_000 as Weight) - // Standard Error: 29_000 - .saturating_add((8_802_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - fn on_initialize(s: u32, ) -> Weight { - (12_283_000 as Weight) - // Standard Error: 25_000 - .saturating_add((7_531_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Scheduler Agenda (r:1 w:1) - fn schedule(s: u32, ) -> Weight { - (16_392_000 as Weight) - // Standard Error: 2_000 - .saturating_add((80_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn cancel(s: u32, ) -> Weight { - (15_883_000 as Weight) - // Standard Error: 7_000 - .saturating_add((1_728_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Scheduler Lookup (r:1 w:1) - // Storage: Scheduler Agenda (r:1 w:1) - fn schedule_named(s: u32, ) -> Weight { - (19_748_000 as Weight) - // Standard Error: 2_000 - .saturating_add((100_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Scheduler Lookup (r:1 w:1) - // Storage: Scheduler Agenda (r:1 w:1) - fn cancel_named(s: u32, ) -> Weight { - (18_623_000 as Weight) - // Standard Error: 8_000 - .saturating_add((1_729_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight { + (18_537_000 as Weight) + // Standard Error: 47_000 + .saturating_add((24_566_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((4 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_named_resolved(s: u32, ) -> Weight { + (10_325_000 as Weight) + // Standard Error: 44_000 + .saturating_add((19_761_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + fn on_initialize_periodic_resolved(s: u32, ) -> Weight { + (13_329_000 as Weight) + // Standard Error: 52_000 + .saturating_add((21_827_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + fn on_initialize_resolved(s: u32, ) -> Weight { + (8_330_000 as Weight) + // Standard Error: 46_000 + .saturating_add((18_544_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:0) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_named_aborted(s: u32, ) -> Weight { + (6_978_000 as Weight) + // Standard Error: 28_000 + .saturating_add((8_749_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:0) + fn on_initialize_aborted(s: u32, ) -> Weight { + (8_474_000 as Weight) + // Standard Error: 20_000 + .saturating_add((5_951_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_periodic_named(s: u32, ) -> Weight { + (14_119_000 as Weight) + // Standard Error: 40_000 + .saturating_add((13_761_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + fn on_initialize_periodic(s: u32, ) -> Weight { + (13_428_000 as Weight) + // Standard Error: 34_000 + .saturating_add((10_782_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_named(s: u32, ) -> Weight { + (12_496_000 as Weight) + // Standard Error: 29_000 + .saturating_add((8_802_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + fn on_initialize(s: u32, ) -> Weight { + (12_283_000 as Weight) + // Standard Error: 25_000 + .saturating_add((7_531_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Scheduler Agenda (r:1 w:1) + fn schedule(s: u32, ) -> Weight { + (16_392_000 as Weight) + // Standard Error: 2_000 + .saturating_add((80_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn cancel(s: u32, ) -> Weight { + (15_883_000 as Weight) + // Standard Error: 7_000 + .saturating_add((1_728_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Scheduler Lookup (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn schedule_named(s: u32, ) -> Weight { + (19_748_000 as Weight) + // Standard Error: 2_000 + .saturating_add((100_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Scheduler Lookup (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn cancel_named(s: u32, ) -> Weight { + (18_623_000 as Weight) + // Standard Error: 8_000 + .saturating_add((1_729_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight { - (18_537_000 as Weight) - // Standard Error: 47_000 - .saturating_add((24_566_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((4 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_named_resolved(s: u32, ) -> Weight { - (10_325_000 as Weight) - // Standard Error: 44_000 - .saturating_add((19_761_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - fn on_initialize_periodic_resolved(s: u32, ) -> Weight { - (13_329_000 as Weight) - // Standard Error: 52_000 - .saturating_add((21_827_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - fn on_initialize_resolved(s: u32, ) -> Weight { - (8_330_000 as Weight) - // Standard Error: 46_000 - .saturating_add((18_544_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:0) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_named_aborted(s: u32, ) -> Weight { - (6_978_000 as Weight) - // Standard Error: 28_000 - .saturating_add((8_749_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:0) - fn on_initialize_aborted(s: u32, ) -> Weight { - (8_474_000 as Weight) - // Standard Error: 20_000 - .saturating_add((5_951_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_periodic_named(s: u32, ) -> Weight { - (14_119_000 as Weight) - // Standard Error: 40_000 - .saturating_add((13_761_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - fn on_initialize_periodic(s: u32, ) -> Weight { - (13_428_000 as Weight) - // Standard Error: 34_000 - .saturating_add((10_782_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_named(s: u32, ) -> Weight { - (12_496_000 as Weight) - // Standard Error: 29_000 - .saturating_add((8_802_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - fn on_initialize(s: u32, ) -> Weight { - (12_283_000 as Weight) - // Standard Error: 25_000 - .saturating_add((7_531_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Scheduler Agenda (r:1 w:1) - fn schedule(s: u32, ) -> Weight { - (16_392_000 as Weight) - // Standard Error: 2_000 - .saturating_add((80_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn cancel(s: u32, ) -> Weight { - (15_883_000 as Weight) - // Standard Error: 7_000 - .saturating_add((1_728_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Scheduler Lookup (r:1 w:1) - // Storage: Scheduler Agenda (r:1 w:1) - fn schedule_named(s: u32, ) -> Weight { - (19_748_000 as Weight) - // Standard Error: 2_000 - .saturating_add((100_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Scheduler Lookup (r:1 w:1) - // Storage: Scheduler Agenda (r:1 w:1) - fn cancel_named(s: u32, ) -> Weight { - (18_623_000 as Weight) - // Standard Error: 8_000 - .saturating_add((1_729_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } -} \ No newline at end of file + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight { + (18_537_000 as Weight) + // Standard Error: 47_000 + .saturating_add((24_566_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((4 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_named_resolved(s: u32, ) -> Weight { + (10_325_000 as Weight) + // Standard Error: 44_000 + .saturating_add((19_761_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + fn on_initialize_periodic_resolved(s: u32, ) -> Weight { + (13_329_000 as Weight) + // Standard Error: 52_000 + .saturating_add((21_827_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + fn on_initialize_resolved(s: u32, ) -> Weight { + (8_330_000 as Weight) + // Standard Error: 46_000 + .saturating_add((18_544_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:0) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_named_aborted(s: u32, ) -> Weight { + (6_978_000 as Weight) + // Standard Error: 28_000 + .saturating_add((8_749_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:0) + fn on_initialize_aborted(s: u32, ) -> Weight { + (8_474_000 as Weight) + // Standard Error: 20_000 + .saturating_add((5_951_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_periodic_named(s: u32, ) -> Weight { + (14_119_000 as Weight) + // Standard Error: 40_000 + .saturating_add((13_761_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + fn on_initialize_periodic(s: u32, ) -> Weight { + (13_428_000 as Weight) + // Standard Error: 34_000 + .saturating_add((10_782_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_named(s: u32, ) -> Weight { + (12_496_000 as Weight) + // Standard Error: 29_000 + .saturating_add((8_802_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + fn on_initialize(s: u32, ) -> Weight { + (12_283_000 as Weight) + // Standard Error: 25_000 + .saturating_add((7_531_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Scheduler Agenda (r:1 w:1) + fn schedule(s: u32, ) -> Weight { + (16_392_000 as Weight) + // Standard Error: 2_000 + .saturating_add((80_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn cancel(s: u32, ) -> Weight { + (15_883_000 as Weight) + // Standard Error: 7_000 + .saturating_add((1_728_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Scheduler Lookup (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn schedule_named(s: u32, ) -> Weight { + (19_748_000 as Weight) + // Standard Error: 2_000 + .saturating_add((100_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Scheduler Lookup (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn cancel_named(s: u32, ) -> Weight { + (18_623_000 as Weight) + // Standard Error: 8_000 + .saturating_add((1_729_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } +} diff --git a/runtime/calamari/src/weights/pallet_session.rs b/runtime/calamari/src/weights/pallet_session.rs index c34fab301..6bec809af 100644 --- a/runtime/calamari/src/weights/pallet_session.rs +++ b/runtime/calamari/src/weights/pallet_session.rs @@ -43,43 +43,43 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_session. pub trait WeightInfo { - fn set_keys() -> Weight; - fn purge_keys() -> Weight; + fn set_keys() -> Weight; + fn purge_keys() -> Weight; } /// Weights for pallet_session using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_session::WeightInfo for SubstrateWeight { - // Storage: Session NextKeys (r:1 w:1) - // Storage: Session KeyOwner (r:1 w:1) - fn set_keys() -> Weight { - (14_500_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Session NextKeys (r:1 w:1) - // Storage: Session KeyOwner (r:0 w:1) - fn purge_keys() -> Weight { - (10_384_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } + // Storage: Session NextKeys (r:1 w:1) + // Storage: Session KeyOwner (r:1 w:1) + fn set_keys() -> Weight { + (14_500_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Session NextKeys (r:1 w:1) + // Storage: Session KeyOwner (r:0 w:1) + fn purge_keys() -> Weight { + (10_384_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Session NextKeys (r:1 w:1) - // Storage: Session KeyOwner (r:1 w:1) - fn set_keys() -> Weight { - (14_500_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Session NextKeys (r:1 w:1) - // Storage: Session KeyOwner (r:0 w:1) - fn purge_keys() -> Weight { - (10_384_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } -} \ No newline at end of file + // Storage: Session NextKeys (r:1 w:1) + // Storage: Session KeyOwner (r:1 w:1) + fn set_keys() -> Weight { + (14_500_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Session NextKeys (r:1 w:1) + // Storage: Session KeyOwner (r:0 w:1) + fn purge_keys() -> Weight { + (10_384_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } +} diff --git a/runtime/calamari/src/weights/pallet_timestamp.rs b/runtime/calamari/src/weights/pallet_timestamp.rs index f08fcdfb0..021c5429f 100644 --- a/runtime/calamari/src/weights/pallet_timestamp.rs +++ b/runtime/calamari/src/weights/pallet_timestamp.rs @@ -43,33 +43,33 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_timestamp. pub trait WeightInfo { - fn set() -> Weight; - fn on_finalize() -> Weight; + fn set() -> Weight; + fn on_finalize() -> Weight; } /// Weights for pallet_timestamp using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_timestamp::WeightInfo for SubstrateWeight { - // Storage: Timestamp Now (r:1 w:1) - fn set() -> Weight { - (4_764_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn on_finalize() -> Weight { - (2_779_000 as Weight) - } + // Storage: Timestamp Now (r:1 w:1) + fn set() -> Weight { + (4_764_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + fn on_finalize() -> Weight { + (2_779_000 as Weight) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Timestamp Now (r:1 w:1) - fn set() -> Weight { - (4_764_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - fn on_finalize() -> Weight { - (2_779_000 as Weight) - } -} \ No newline at end of file + // Storage: Timestamp Now (r:1 w:1) + fn set() -> Weight { + (4_764_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + fn on_finalize() -> Weight { + (2_779_000 as Weight) + } +} diff --git a/runtime/calamari/src/weights/pallet_treasury.rs b/runtime/calamari/src/weights/pallet_treasury.rs index 538f9fd0e..16bd3408b 100644 --- a/runtime/calamari/src/weights/pallet_treasury.rs +++ b/runtime/calamari/src/weights/pallet_treasury.rs @@ -43,87 +43,87 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_treasury. pub trait WeightInfo { - fn propose_spend() -> Weight; - fn reject_proposal() -> Weight; - fn approve_proposal(p: u32, ) -> Weight; - fn on_initialize_proposals(p: u32, ) -> Weight; + fn propose_spend() -> Weight; + fn reject_proposal() -> Weight; + fn approve_proposal(p: u32, ) -> Weight; + fn on_initialize_proposals(p: u32, ) -> Weight; } /// Weights for pallet_treasury using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_treasury::WeightInfo for SubstrateWeight { - // Storage: Treasury ProposalCount (r:1 w:1) - // Storage: Treasury Proposals (r:0 w:1) - fn propose_spend() -> Weight { - (25_278_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Treasury Proposals (r:1 w:1) - // Storage: System Account (r:2 w:2) - fn reject_proposal() -> Weight { - (42_964_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Treasury Proposals (r:1 w:0) - // Storage: Treasury Approvals (r:1 w:1) - fn approve_proposal(p: u32, ) -> Weight { - (10_466_000 as Weight) - // Standard Error: 1_000 - .saturating_add((65_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:0) - // Storage: Treasury Approvals (r:1 w:1) - // Storage: Treasury Proposals (r:2 w:2) - fn on_initialize_proposals(p: u32, ) -> Weight { - (28_898_000 as Weight) - // Standard Error: 37_000 - .saturating_add((32_652_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(p as Weight))) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(p as Weight))) - } + // Storage: Treasury ProposalCount (r:1 w:1) + // Storage: Treasury Proposals (r:0 w:1) + fn propose_spend() -> Weight { + (25_278_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Treasury Proposals (r:1 w:1) + // Storage: System Account (r:2 w:2) + fn reject_proposal() -> Weight { + (42_964_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Treasury Proposals (r:1 w:0) + // Storage: Treasury Approvals (r:1 w:1) + fn approve_proposal(p: u32, ) -> Weight { + (10_466_000 as Weight) + // Standard Error: 1_000 + .saturating_add((65_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:0) + // Storage: Treasury Approvals (r:1 w:1) + // Storage: Treasury Proposals (r:2 w:2) + fn on_initialize_proposals(p: u32, ) -> Weight { + (28_898_000 as Weight) + // Standard Error: 37_000 + .saturating_add((32_652_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(p as Weight))) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(p as Weight))) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Treasury ProposalCount (r:1 w:1) - // Storage: Treasury Proposals (r:0 w:1) - fn propose_spend() -> Weight { - (25_278_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Treasury Proposals (r:1 w:1) - // Storage: System Account (r:2 w:2) - fn reject_proposal() -> Weight { - (42_964_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Treasury Proposals (r:1 w:0) - // Storage: Treasury Approvals (r:1 w:1) - fn approve_proposal(p: u32, ) -> Weight { - (10_466_000 as Weight) - // Standard Error: 1_000 - .saturating_add((65_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:0) - // Storage: Treasury Approvals (r:1 w:1) - // Storage: Treasury Proposals (r:2 w:2) - fn on_initialize_proposals(p: u32, ) -> Weight { - (28_898_000 as Weight) - // Standard Error: 37_000 - .saturating_add((32_652_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(p as Weight))) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(p as Weight))) - } -} \ No newline at end of file + // Storage: Treasury ProposalCount (r:1 w:1) + // Storage: Treasury Proposals (r:0 w:1) + fn propose_spend() -> Weight { + (25_278_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Treasury Proposals (r:1 w:1) + // Storage: System Account (r:2 w:2) + fn reject_proposal() -> Weight { + (42_964_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Treasury Proposals (r:1 w:0) + // Storage: Treasury Approvals (r:1 w:1) + fn approve_proposal(p: u32, ) -> Weight { + (10_466_000 as Weight) + // Standard Error: 1_000 + .saturating_add((65_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:0) + // Storage: Treasury Approvals (r:1 w:1) + // Storage: Treasury Proposals (r:2 w:2) + fn on_initialize_proposals(p: u32, ) -> Weight { + (28_898_000 as Weight) + // Standard Error: 37_000 + .saturating_add((32_652_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(p as Weight))) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(p as Weight))) + } +} diff --git a/runtime/calamari/src/weights/pallet_tx_pause.rs b/runtime/calamari/src/weights/pallet_tx_pause.rs index ef891266f..a75e4656c 100644 --- a/runtime/calamari/src/weights/pallet_tx_pause.rs +++ b/runtime/calamari/src/weights/pallet_tx_pause.rs @@ -43,39 +43,39 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_tx_pause. pub trait WeightInfo { - fn pause_transaction() -> Weight; - fn unpause_transaction() -> Weight; + fn pause_transaction() -> Weight; + fn unpause_transaction() -> Weight; } /// Weights for pallet_tx_pause using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_tx_pause::WeightInfo for SubstrateWeight { - // Storage: TransactionPause PausedTransactions (r:1 w:1) - fn pause_transaction() -> Weight { - (12_106_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: TransactionPause PausedTransactions (r:1 w:1) - fn unpause_transaction() -> Weight { - (12_723_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } + // Storage: TransactionPause PausedTransactions (r:1 w:1) + fn pause_transaction() -> Weight { + (12_106_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: TransactionPause PausedTransactions (r:1 w:1) + fn unpause_transaction() -> Weight { + (12_723_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: TransactionPause PausedTransactions (r:1 w:1) - fn pause_transaction() -> Weight { - (12_106_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: TransactionPause PausedTransactions (r:1 w:1) - fn unpause_transaction() -> Weight { - (12_723_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } -} \ No newline at end of file + // Storage: TransactionPause PausedTransactions (r:1 w:1) + fn pause_transaction() -> Weight { + (12_106_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: TransactionPause PausedTransactions (r:1 w:1) + fn unpause_transaction() -> Weight { + (12_723_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } +} diff --git a/runtime/calamari/src/weights/pallet_utility.rs b/runtime/calamari/src/weights/pallet_utility.rs index acb070787..1a4bafc13 100644 --- a/runtime/calamari/src/weights/pallet_utility.rs +++ b/runtime/calamari/src/weights/pallet_utility.rs @@ -43,49 +43,49 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_utility. pub trait WeightInfo { - fn batch(c: u32, ) -> Weight; - fn as_derivative() -> Weight; - fn batch_all(c: u32, ) -> Weight; - fn dispatch_as() -> Weight; + fn batch(c: u32, ) -> Weight; + fn as_derivative() -> Weight; + fn batch_all(c: u32, ) -> Weight; + fn dispatch_as() -> Weight; } /// Weights for pallet_utility using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_utility::WeightInfo for SubstrateWeight { - fn batch(c: u32, ) -> Weight { - (21_573_000 as Weight) - // Standard Error: 4_000 - .saturating_add((3_544_000 as Weight).saturating_mul(c as Weight)) - } - fn as_derivative() -> Weight { - (2_148_000 as Weight) - } - fn batch_all(c: u32, ) -> Weight { - (25_257_000 as Weight) - // Standard Error: 4_000 - .saturating_add((3_789_000 as Weight).saturating_mul(c as Weight)) - } - fn dispatch_as() -> Weight { - (9_294_000 as Weight) - } + fn batch(c: u32, ) -> Weight { + (21_573_000 as Weight) + // Standard Error: 4_000 + .saturating_add((3_544_000 as Weight).saturating_mul(c as Weight)) + } + fn as_derivative() -> Weight { + (2_148_000 as Weight) + } + fn batch_all(c: u32, ) -> Weight { + (25_257_000 as Weight) + // Standard Error: 4_000 + .saturating_add((3_789_000 as Weight).saturating_mul(c as Weight)) + } + fn dispatch_as() -> Weight { + (9_294_000 as Weight) + } } // For backwards compatibility and tests impl WeightInfo for () { - fn batch(c: u32, ) -> Weight { - (21_573_000 as Weight) - // Standard Error: 4_000 - .saturating_add((3_544_000 as Weight).saturating_mul(c as Weight)) - } - fn as_derivative() -> Weight { - (2_148_000 as Weight) - } - fn batch_all(c: u32, ) -> Weight { - (25_257_000 as Weight) - // Standard Error: 4_000 - .saturating_add((3_789_000 as Weight).saturating_mul(c as Weight)) - } - fn dispatch_as() -> Weight { - (9_294_000 as Weight) - } -} \ No newline at end of file + fn batch(c: u32, ) -> Weight { + (21_573_000 as Weight) + // Standard Error: 4_000 + .saturating_add((3_544_000 as Weight).saturating_mul(c as Weight)) + } + fn as_derivative() -> Weight { + (2_148_000 as Weight) + } + fn batch_all(c: u32, ) -> Weight { + (25_257_000 as Weight) + // Standard Error: 4_000 + .saturating_add((3_789_000 as Weight).saturating_mul(c as Weight)) + } + fn dispatch_as() -> Weight { + (9_294_000 as Weight) + } +} diff --git a/runtime/calamari/src/xcm_config.rs b/runtime/calamari/src/xcm_config.rs index 56366d299..a6f4e3f08 100644 --- a/runtime/calamari/src/xcm_config.rs +++ b/runtime/calamari/src/xcm_config.rs @@ -15,9 +15,9 @@ // along with Manta. If not, see . use super::{ - AssetManager, Assets, Balances, Call, DmpQueue, EnsureRootOrMoreThanHalfCouncil, Event, Origin, - ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, Treasury, XcmpQueue, - MAXIMUM_BLOCK_WEIGHT, + AssetManager, Assets, Balances, Call, DmpQueue, EnsureRootOrMoreThanHalfCouncil, Event, Origin, + ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, Treasury, XcmpQueue, + MAXIMUM_BLOCK_WEIGHT, }; use codec::{Decode, Encode}; @@ -26,15 +26,15 @@ use scale_info::TypeInfo; use sp_std::prelude::*; use frame_support::{ - match_type, parameter_types, - traits::{Everything, Nothing}, - weights::Weight, + match_type, parameter_types, + traits::{Everything, Nothing}, + weights::Weight, }; use frame_system::EnsureRoot; use manta_primitives::{ - assets::{AssetIdLocationConvert, AssetLocation}, - types::{AccountId, AssetId, Balance}, - xcm::{AccountIdToMultiLocation, FirstAssetTrader, IsNativeConcrete, MultiNativeAsset}, + assets::{AssetIdLocationConvert, AssetLocation}, + types::{AccountId, AssetId, Balance}, + xcm::{AccountIdToMultiLocation, FirstAssetTrader, IsNativeConcrete, MultiNativeAsset}, }; #[cfg(any(feature = "std", test))] @@ -47,29 +47,29 @@ use polkadot_parachain::primitives::Sibling; use xcm::latest::prelude::*; use xcm_builder::{ - AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, - AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, ConvertedConcreteAssetId, - CurrencyAdapter as XcmCurrencyAdapter, EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, - FungiblesAdapter, LocationInverter, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, - SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, - SovereignSignedViaLocation, TakeWeightCredit, + AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, + AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, ConvertedConcreteAssetId, + CurrencyAdapter as XcmCurrencyAdapter, EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, + FungiblesAdapter, LocationInverter, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, + SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, + SovereignSignedViaLocation, TakeWeightCredit, }; use xcm_executor::{traits::JustTry, Config, XcmExecutor}; parameter_types! { - pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; - pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; + pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; + pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; } impl cumulus_pallet_parachain_system::Config for Runtime { - type Event = Event; - type SelfParaId = parachain_info::Pallet; - type DmpMessageHandler = DmpQueue; - type ReservedDmpWeight = ReservedDmpWeight; - type OutboundXcmpMessageSource = XcmpQueue; - type XcmpMessageHandler = XcmpQueue; - type ReservedXcmpWeight = ReservedXcmpWeight; - type OnSystemEvent = (); + type Event = Event; + type SelfParaId = parachain_info::Pallet; + type DmpMessageHandler = DmpQueue; + type ReservedDmpWeight = ReservedDmpWeight; + type OutboundXcmpMessageSource = XcmpQueue; + type XcmpMessageHandler = XcmpQueue; + type ReservedXcmpWeight = ReservedXcmpWeight; + type OnSystemEvent = (); } impl parachain_info::Config for Runtime {} @@ -77,38 +77,38 @@ impl parachain_info::Config for Runtime {} impl cumulus_pallet_aura_ext::Config for Runtime {} parameter_types! { - pub const KsmLocation: MultiLocation = MultiLocation::parent(); - pub const RelayNetwork: NetworkId = NetworkId::Kusama; - pub RelayChainOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into(); - pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into(); - pub SelfReserve: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::parachain_id().into()))); - pub CheckingAccount: AccountId = PolkadotXcm::check_account(); + pub const KsmLocation: MultiLocation = MultiLocation::parent(); + pub const RelayNetwork: NetworkId = NetworkId::Kusama; + pub RelayChainOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into(); + pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into(); + pub SelfReserve: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::parachain_id().into()))); + pub CheckingAccount: AccountId = PolkadotXcm::check_account(); } /// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used /// when determining ownership of accounts for asset transacting and when attempting to use XCM /// `Transact` in order to determine the dispatch Origin. pub type LocationToAccountId = ( - // The parent (Relay-chain) origin converts to the default `AccountId`. - ParentIsPreset, - // Sibling parachain origins convert to AccountId via the `ParaId::into`. - SiblingParachainConvertsVia, - // Straight up local `AccountId32` origins just alias directly to `AccountId`. - AccountId32Aliases, + // The parent (Relay-chain) origin converts to the default `AccountId`. + ParentIsPreset, + // Sibling parachain origins convert to AccountId via the `ParaId::into`. + SiblingParachainConvertsVia, + // Straight up local `AccountId32` origins just alias directly to `AccountId`. + AccountId32Aliases, ); /// Transactor for native currency, i.e. implements `fungible` trait pub type LocalAssetTransactor = XcmCurrencyAdapter< - // Transacting native currency, i.e. MANTA, KMA, DOL - Balances, - // Used when the incoming asset is a fungible concrete asset matching the given location or name: - IsNativeConcrete, - // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: - LocationToAccountId, - // Our chain's account ID type (we can't get away without mentioning it explicitly): - AccountId, - // We don't track any teleports. - (), + // Transacting native currency, i.e. MANTA, KMA, DOL + Balances, + // Used when the incoming asset is a fungible concrete asset matching the given location or name: + IsNativeConcrete, + // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: + LocationToAccountId, + // Our chain's account ID type (we can't get away without mentioning it explicitly): + AccountId, + // We don't track any teleports. + (), >; /// This is the type to convert an (incoming) XCM origin into a local `Origin` instance, @@ -116,130 +116,130 @@ pub type LocalAssetTransactor = XcmCurrencyAdapter< /// It uses some Rust magic macro to do the pattern matching sequentially. /// There is an `OriginKind` which can biases the kind of local `Origin` it will become. pub type XcmOriginToCallOrigin = ( - // Sovereign account converter; this attempts to derive an `AccountId` from the origin location - // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for - // foreign chains who want to have a local sovereign account on this chain which they control. - SovereignSignedViaLocation, - // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when - // recognised. - RelayChainAsNative, - // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when - // recognised. - SiblingParachainAsNative, - // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a - // transaction from the Root origin. - ParentAsSuperuser, - // If the incoming XCM origin is of type `AccountId32` and the Network is Network::Any - // or `RelayNetwork`, convert it to a Native 32 byte account. - SignedAccountId32AsNative, - // Xcm origins can be represented natively under the Xcm pallet's Xcm origin. - XcmPassthrough, + // Sovereign account converter; this attempts to derive an `AccountId` from the origin location + // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for + // foreign chains who want to have a local sovereign account on this chain which they control. + SovereignSignedViaLocation, + // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when + // recognised. + RelayChainAsNative, + // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when + // recognised. + SiblingParachainAsNative, + // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a + // transaction from the Root origin. + ParentAsSuperuser, + // If the incoming XCM origin is of type `AccountId32` and the Network is Network::Any + // or `RelayNetwork`, convert it to a Native 32 byte account. + SignedAccountId32AsNative, + // Xcm origins can be represented natively under the Xcm pallet's Xcm origin. + XcmPassthrough, ); parameter_types! { - // One XCM operation is 1_000_000_000 weight - almost certainly a conservative estimate. - pub UnitWeightCost: Weight = 1_000_000_000; - // Used in native traders - // This might be able to skipped. - // We have to use `here()` because of reanchoring logic - pub ParaTokenPerSecond: (xcm::v2::AssetId, u128) = (Concrete(MultiLocation::here()), 1_000_000_000); - pub const MaxInstructions: u32 = 100; + // One XCM operation is 1_000_000_000 weight - almost certainly a conservative estimate. + pub UnitWeightCost: Weight = 1_000_000_000; + // Used in native traders + // This might be able to skipped. + // We have to use `here()` because of reanchoring logic + pub ParaTokenPerSecond: (xcm::v2::AssetId, u128) = (Concrete(MultiLocation::here()), 1_000_000_000); + pub const MaxInstructions: u32 = 100; } /// Transactor for currency in pallet-assets, i.e. implements `fungibles` trait pub type FungiblesTransactor = FungiblesAdapter< - Assets, - ConvertedConcreteAssetId< - AssetId, - Balance, - AssetIdLocationConvert, - JustTry, - >, - // "default" implementation of converting a `MultiLocation` to an `AccountId` - LocationToAccountId, - AccountId, - // No teleport support. - Nothing, - // No teleport tracking. - CheckingAccount, + Assets, + ConvertedConcreteAssetId< + AssetId, + Balance, + AssetIdLocationConvert, + JustTry, + >, + // "default" implementation of converting a `MultiLocation` to an `AccountId` + LocationToAccountId, + AccountId, + // No teleport support. + Nothing, + // No teleport tracking. + CheckingAccount, >; match_type! { - pub type ParentOrParentsExecutivePlurality: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Executive, .. }) } - }; + pub type ParentOrParentsExecutivePlurality: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Executive, .. }) } + }; } match_type! { - pub type ParentOrSiblings: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(_) } - }; + pub type ParentOrSiblings: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(_) } + }; } pub type Barrier = ( - // Allows local origin messages which call weight_credit >= weight_limit. - TakeWeightCredit, - // Allows non-local origin messages, for example from from the xcmp queue, - // which have the ability to deposit assets and pay for their own execution. - AllowTopLevelPaidExecutionFrom, - // Parent and its exec plurality get free execution - AllowUnpaidExecutionFrom, - // Expected responses are OK. - // Allows `Pending` or `VersionNotifier` query responses. - AllowKnownQueryResponses, - // Subscriptions for version tracking are OK. - // Allows execution of `SubscribeVersion` or `UnsubscribeVersion` instruction, - // from parent or sibling chains. - AllowSubscriptionsFrom, + // Allows local origin messages which call weight_credit >= weight_limit. + TakeWeightCredit, + // Allows non-local origin messages, for example from from the xcmp queue, + // which have the ability to deposit assets and pay for their own execution. + AllowTopLevelPaidExecutionFrom, + // Parent and its exec plurality get free execution + AllowUnpaidExecutionFrom, + // Expected responses are OK. + // Allows `Pending` or `VersionNotifier` query responses. + AllowKnownQueryResponses, + // Subscriptions for version tracking are OK. + // Allows execution of `SubscribeVersion` or `UnsubscribeVersion` instruction, + // from parent or sibling chains. + AllowSubscriptionsFrom, ); parameter_types! { - pub XcmFeesAccount: AccountId = Treasury::account_id(); + pub XcmFeesAccount: AccountId = Treasury::account_id(); } pub type XcmFeesToAccount = manta_primitives::xcm::XcmFeesToAccount< - Assets, - ConvertedConcreteAssetId< - AssetId, - Balance, - AssetIdLocationConvert, - JustTry, - >, - AccountId, - XcmFeesAccount, + Assets, + ConvertedConcreteAssetId< + AssetId, + Balance, + AssetIdLocationConvert, + JustTry, + >, + AccountId, + XcmFeesAccount, >; pub struct XcmExecutorConfig; impl Config for XcmExecutorConfig { - type Call = Call; - type XcmSender = XcmRouter; - // Defines how to Withdraw and Deposit instruction work - // Under the hood, substrate framework will do pattern matching in macro, - // as a result, the order of the following tuple matters. - type AssetTransactor = (LocalAssetTransactor, FungiblesTransactor); - type OriginConverter = XcmOriginToCallOrigin; - // Combinations of (Location, Asset) pairs which we trust as reserves. - type IsReserve = MultiNativeAsset; - type IsTeleporter = (); - type LocationInverter = LocationInverter; - type Barrier = Barrier; - type Weigher = FixedWeightBounds; - // Trader is the means to purchasing weight credit for XCM execution. - // We define two traders: - // The first one will charge parachain's native currency, who's `MultiLocation` - // is defined in `SelfReserve`. - // The second one will charge the first asset in the MultiAssets with pre-defined rate - // i.e. units_per_second in `AssetManager` - type Trader = ( - FixedRateOfFungible, - FirstAssetTrader, - ); - type ResponseHandler = PolkadotXcm; - type AssetTrap = PolkadotXcm; - type AssetClaims = PolkadotXcm; - // This is needed for the version change notifier work - type SubscriptionService = PolkadotXcm; + type Call = Call; + type XcmSender = XcmRouter; + // Defines how to Withdraw and Deposit instruction work + // Under the hood, substrate framework will do pattern matching in macro, + // as a result, the order of the following tuple matters. + type AssetTransactor = (LocalAssetTransactor, FungiblesTransactor); + type OriginConverter = XcmOriginToCallOrigin; + // Combinations of (Location, Asset) pairs which we trust as reserves. + type IsReserve = MultiNativeAsset; + type IsTeleporter = (); + type LocationInverter = LocationInverter; + type Barrier = Barrier; + type Weigher = FixedWeightBounds; + // Trader is the means to purchasing weight credit for XCM execution. + // We define two traders: + // The first one will charge parachain's native currency, who's `MultiLocation` + // is defined in `SelfReserve`. + // The second one will charge the first asset in the MultiAssets with pre-defined rate + // i.e. units_per_second in `AssetManager` + type Trader = ( + FixedRateOfFungible, + FirstAssetTrader, + ); + type ResponseHandler = PolkadotXcm; + type AssetTrap = PolkadotXcm; + type AssetClaims = PolkadotXcm; + // This is needed for the version change notifier work + type SubscriptionService = PolkadotXcm; } /// No one is allowed to dispatch XCM sends/executions. @@ -248,99 +248,99 @@ pub type LocalOriginToLocation = (); /// The means for routing XCM messages which are not for local execution into the right message /// queues. pub type XcmRouter = ( - // Two routers - use UMP to communicate with the relay chain: - cumulus_primitives_utility::ParentAsUmp, - // ..and XCMP to communicate with the sibling chains. - XcmpQueue, + // Two routers - use UMP to communicate with the relay chain: + cumulus_primitives_utility::ParentAsUmp, + // ..and XCMP to communicate with the sibling chains. + XcmpQueue, ); impl pallet_xcm::Config for Runtime { - const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; - - type Origin = Origin; - type Call = Call; - type Event = Event; - type SendXcmOrigin = EnsureXcmOrigin; - type XcmRouter = XcmRouter; - type ExecuteXcmOrigin = EnsureXcmOrigin; - /// This means that no location will pass XcmExecuteFilter, so a dispatched `execute` message will be filtered. - /// This shouldn't be reachable since `LocalOriginToLocation = ();`, but let's be on the safe side. - type XcmExecuteFilter = Nothing; - type XcmExecutor = XcmExecutor; - type XcmTeleportFilter = Nothing; - type XcmReserveTransferFilter = Nothing; - type Weigher = FixedWeightBounds; - type LocationInverter = LocationInverter; - type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; + const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; + + type Origin = Origin; + type Call = Call; + type Event = Event; + type SendXcmOrigin = EnsureXcmOrigin; + type XcmRouter = XcmRouter; + type ExecuteXcmOrigin = EnsureXcmOrigin; + /// This means that no location will pass XcmExecuteFilter, so a dispatched `execute` message will be filtered. + /// This shouldn't be reachable since `LocalOriginToLocation = ();`, but let's be on the safe side. + type XcmExecuteFilter = Nothing; + type XcmExecutor = XcmExecutor; + type XcmTeleportFilter = Nothing; + type XcmReserveTransferFilter = Nothing; + type Weigher = FixedWeightBounds; + type LocationInverter = LocationInverter; + type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; } impl cumulus_pallet_xcm::Config for Runtime { - type Event = Event; - type XcmExecutor = XcmExecutor; + type Event = Event; + type XcmExecutor = XcmExecutor; } impl cumulus_pallet_xcmp_queue::Config for Runtime { - type Event = Event; - type XcmExecutor = XcmExecutor; - type ChannelInfo = ParachainSystem; - type VersionWrapper = PolkadotXcm; - type ExecuteOverweightOrigin = EnsureRoot; - type ControllerOrigin = EnsureRootOrMoreThanHalfCouncil; - type ControllerOriginConverter = XcmOriginToCallOrigin; - type WeightInfo = crate::weights::cumulus_pallet_xcmp_queue::SubstrateWeight; + type Event = Event; + type XcmExecutor = XcmExecutor; + type ChannelInfo = ParachainSystem; + type VersionWrapper = PolkadotXcm; + type ExecuteOverweightOrigin = EnsureRoot; + type ControllerOrigin = EnsureRootOrMoreThanHalfCouncil; + type ControllerOriginConverter = XcmOriginToCallOrigin; + type WeightInfo = crate::weights::cumulus_pallet_xcmp_queue::SubstrateWeight; } impl cumulus_pallet_dmp_queue::Config for Runtime { - type Event = Event; - type XcmExecutor = XcmExecutor; - type ExecuteOverweightOrigin = EnsureRoot; + type Event = Event; + type XcmExecutor = XcmExecutor; + type ExecuteOverweightOrigin = EnsureRoot; } // We wrap AssetId for XToken #[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)] pub enum CurrencyId { - MantaCurrency(AssetId), + MantaCurrency(AssetId), } pub struct CurrencyIdtoMultiLocation(sp_std::marker::PhantomData); impl sp_runtime::traits::Convert> - for CurrencyIdtoMultiLocation + for CurrencyIdtoMultiLocation where - AssetXConverter: xcm_executor::traits::Convert, + AssetXConverter: xcm_executor::traits::Convert, { - fn convert(currency: CurrencyId) -> Option { - match currency { - CurrencyId::MantaCurrency(asset_id) => match AssetXConverter::reverse_ref(&asset_id) { - Ok(location) => Some(location), - Err(_) => None, - }, - } - } + fn convert(currency: CurrencyId) -> Option { + match currency { + CurrencyId::MantaCurrency(asset_id) => match AssetXConverter::reverse_ref(&asset_id) { + Ok(location) => Some(location), + Err(_) => None, + }, + } + } } parameter_types! { - pub const BaseXcmWeight: Weight = 100_000_000; - pub const MaxAssetsForTransfer: usize = 1; + pub const BaseXcmWeight: Weight = 100_000_000; + pub const MaxAssetsForTransfer: usize = 1; } // The XCM message wrapper wrapper impl orml_xtokens::Config for Runtime { - type Event = Event; - type Balance = Balance; - type CurrencyId = CurrencyId; - type AccountIdToMultiLocation = AccountIdToMultiLocation; - type CurrencyIdConvert = - CurrencyIdtoMultiLocation>; - type XcmExecutor = XcmExecutor; - type SelfLocation = SelfReserve; - // Take note that this pallet does not have the typical configurable WeightInfo. - // It uses the Weigher configuration to calculate weights for the user callable extrinsics on this chain, - // as well as weights for execution on the destination chain. Both based on the composed xcm messages. - type Weigher = FixedWeightBounds; - type BaseXcmWeight = BaseXcmWeight; - type LocationInverter = LocationInverter; - type MaxAssetsForTransfer = MaxAssetsForTransfer; - type MinXcmFee = AssetManager; - type MultiLocationsFilter = AssetManager; - type ReserveProvider = AbsoluteReserveProvider; + type Event = Event; + type Balance = Balance; + type CurrencyId = CurrencyId; + type AccountIdToMultiLocation = AccountIdToMultiLocation; + type CurrencyIdConvert = + CurrencyIdtoMultiLocation>; + type XcmExecutor = XcmExecutor; + type SelfLocation = SelfReserve; + // Take note that this pallet does not have the typical configurable WeightInfo. + // It uses the Weigher configuration to calculate weights for the user callable extrinsics on this chain, + // as well as weights for execution on the destination chain. Both based on the composed xcm messages. + type Weigher = FixedWeightBounds; + type BaseXcmWeight = BaseXcmWeight; + type LocationInverter = LocationInverter; + type MaxAssetsForTransfer = MaxAssetsForTransfer; + type MinXcmFee = AssetManager; + type MultiLocationsFilter = AssetManager; + type ReserveProvider = AbsoluteReserveProvider; } diff --git a/runtime/calamari/tests/common/mock.rs b/runtime/calamari/tests/common/mock.rs index 4ff2807dc..c4f1ce63d 100644 --- a/runtime/calamari/tests/common/mock.rs +++ b/runtime/calamari/tests/common/mock.rs @@ -17,137 +17,137 @@ use crate::common::*; pub use calamari_runtime::{ - assets_config::CalamariAssetConfig, currency::KMA, Call, CollatorSelection, Democracy, Runtime, - Scheduler, Session, System, TransactionPayment, + assets_config::CalamariAssetConfig, currency::KMA, Call, CollatorSelection, Democracy, Runtime, + Scheduler, Session, System, TransactionPayment, }; use frame_support::traits::{GenesisBuild, OnFinalize, OnInitialize}; use manta_primitives::{ - assets::AssetConfig, - helpers::{get_account_id_from_seed, get_collator_keys_from_seed}, - types::{AccountId, AuraId, Balance}, + assets::AssetConfig, + helpers::{get_account_id_from_seed, get_collator_keys_from_seed}, + types::{AccountId, AuraId, Balance}, }; use sp_core::sr25519; pub struct ExtBuilder { - balances: Vec<(AccountId, Balance)>, - authorities: Vec<(AccountId, AuraId)>, - invulnerables: Vec, - desired_candidates: u32, - safe_xcm_version: Option, + balances: Vec<(AccountId, Balance)>, + authorities: Vec<(AccountId, AuraId)>, + invulnerables: Vec, + desired_candidates: u32, + safe_xcm_version: Option, } use sp_std::marker::PhantomData; impl Default for ExtBuilder { - fn default() -> ExtBuilder { - ExtBuilder { - balances: vec![( - get_account_id_from_seed::("Alice"), - INITIAL_BALANCE, - )], - authorities: vec![( - get_account_id_from_seed::("Alice"), - get_collator_keys_from_seed("Alice"), - )], - invulnerables: vec![get_account_id_from_seed::("Alice")], - safe_xcm_version: None, - desired_candidates: 1, - } - } + fn default() -> ExtBuilder { + ExtBuilder { + balances: vec![( + get_account_id_from_seed::("Alice"), + INITIAL_BALANCE, + )], + authorities: vec![( + get_account_id_from_seed::("Alice"), + get_collator_keys_from_seed("Alice"), + )], + invulnerables: vec![get_account_id_from_seed::("Alice")], + safe_xcm_version: None, + desired_candidates: 1, + } + } } impl ExtBuilder { - pub fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self { - self.balances = balances; - self - } - - pub fn with_authorities(mut self, authorities: Vec<(AccountId, AuraId)>) -> Self { - self.authorities = authorities; - self - } - - pub fn with_collators( - mut self, - invulnerables: Vec, - desired_candidates: u32, - ) -> Self { - self.invulnerables = invulnerables; - self.desired_candidates = desired_candidates; - self - } - - pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); - - pallet_balances::GenesisConfig:: { - balances: self.balances, - } - .assimilate_storage(&mut t) - .unwrap(); - - manta_collator_selection::GenesisConfig:: { - invulnerables: self.invulnerables, - eviction_baseline: manta_collator_selection::GenesisConfig::::default() - .eviction_baseline, - eviction_tolerance: manta_collator_selection::GenesisConfig::::default() - .eviction_tolerance, - candidacy_bond: BOND_AMOUNT, - desired_candidates: self.desired_candidates, - } - .assimilate_storage(&mut t) - .unwrap(); - - pallet_session::GenesisConfig:: { - keys: self - .authorities - .iter() - .cloned() - .map(|(acc, aura)| { - ( - acc.clone(), // account id - acc, // validator id - calamari_runtime::opaque::SessionKeys { aura }, // session keys - ) - }) - .collect(), - } - .assimilate_storage(&mut t) - .unwrap(); - - pallet_asset_manager::GenesisConfig:: { - start_id: >::StartNonNativeAssetId::get(), - _marker: PhantomData::::default(), - } - .assimilate_storage(&mut t) - .unwrap(); - - >::assimilate_storage( - &pallet_xcm::GenesisConfig { - safe_xcm_version: self.safe_xcm_version, - }, - &mut t, - ) - .unwrap(); - - let mut ext = sp_io::TestExternalities::new(t); - - ext.execute_with(|| { - System::set_block_number(1); - }); - - ext - } + pub fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self { + self.balances = balances; + self + } + + pub fn with_authorities(mut self, authorities: Vec<(AccountId, AuraId)>) -> Self { + self.authorities = authorities; + self + } + + pub fn with_collators( + mut self, + invulnerables: Vec, + desired_candidates: u32, + ) -> Self { + self.invulnerables = invulnerables; + self.desired_candidates = desired_candidates; + self + } + + pub fn build(self) -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); + + pallet_balances::GenesisConfig:: { + balances: self.balances, + } + .assimilate_storage(&mut t) + .unwrap(); + + manta_collator_selection::GenesisConfig:: { + invulnerables: self.invulnerables, + eviction_baseline: manta_collator_selection::GenesisConfig::::default() + .eviction_baseline, + eviction_tolerance: manta_collator_selection::GenesisConfig::::default() + .eviction_tolerance, + candidacy_bond: BOND_AMOUNT, + desired_candidates: self.desired_candidates, + } + .assimilate_storage(&mut t) + .unwrap(); + + pallet_session::GenesisConfig:: { + keys: self + .authorities + .iter() + .cloned() + .map(|(acc, aura)| { + ( + acc.clone(), // account id + acc, // validator id + calamari_runtime::opaque::SessionKeys { aura }, // session keys + ) + }) + .collect(), + } + .assimilate_storage(&mut t) + .unwrap(); + + pallet_asset_manager::GenesisConfig:: { + start_id: >::StartNonNativeAssetId::get(), + _marker: PhantomData::::default(), + } + .assimilate_storage(&mut t) + .unwrap(); + + >::assimilate_storage( + &pallet_xcm::GenesisConfig { + safe_xcm_version: self.safe_xcm_version, + }, + &mut t, + ) + .unwrap(); + + let mut ext = sp_io::TestExternalities::new(t); + + ext.execute_with(|| { + System::set_block_number(1); + }); + + ext + } } /// Utility function that advances the chain to the desired block number. pub fn run_to_block(n: u32) { - while System::block_number() < n { - System::on_finalize(System::block_number()); - System::set_block_number(System::block_number() + 1); - System::on_initialize(System::block_number()); - Session::on_initialize(System::block_number()); - Scheduler::on_initialize(System::block_number()); - Democracy::on_initialize(System::block_number()); - } + while System::block_number() < n { + System::on_finalize(System::block_number()); + System::set_block_number(System::block_number() + 1); + System::on_initialize(System::block_number()); + Session::on_initialize(System::block_number()); + Scheduler::on_initialize(System::block_number()); + Democracy::on_initialize(System::block_number()); + } } diff --git a/runtime/calamari/tests/common/mod.rs b/runtime/calamari/tests/common/mod.rs index ed832f70f..d38cdbb6c 100644 --- a/runtime/calamari/tests/common/mod.rs +++ b/runtime/calamari/tests/common/mod.rs @@ -26,17 +26,17 @@ pub const INITIAL_BALANCE: Balance = 1_000_000_000_000 * KMA; /// create a transaction info struct from weight. Handy to avoid building the whole struct. pub fn info_from_weight(w: Weight) -> DispatchInfo { - // pays_fee: Pays::Yes -- class: DispatchClass::Normal - DispatchInfo { - weight: w, - ..Default::default() - } + // pays_fee: Pays::Yes -- class: DispatchClass::Normal + DispatchInfo { + weight: w, + ..Default::default() + } } pub fn last_event() -> Event { - System::events().pop().expect("Event expected").event + System::events().pop().expect("Event expected").event } pub fn root_origin() -> ::Origin { - ::Origin::root() + ::Origin::root() } diff --git a/runtime/calamari/tests/integration_tests.rs b/runtime/calamari/tests/integration_tests.rs index 93c841e0d..e75171f5f 100644 --- a/runtime/calamari/tests/integration_tests.rs +++ b/runtime/calamari/tests/integration_tests.rs @@ -16,45 +16,47 @@ //! Calamari Parachain Integration Tests. +#![allow(clippy::identity_op)] // keep e.g. 1 * DAYS for legibility + mod common; use common::{info_from_weight, last_event, mock::*, root_origin, BOND_AMOUNT, INITIAL_BALANCE}; pub use calamari_runtime::{ - assets_config::{CalamariAssetConfig, CalamariConcreteFungibleLedger}, - currency::KMA, - fee::{ - FEES_PERCENTAGE_TO_AUTHOR, FEES_PERCENTAGE_TO_TREASURY, TIPS_PERCENTAGE_TO_AUTHOR, - TIPS_PERCENTAGE_TO_TREASURY, - }, - xcm_config::XcmFeesAccount, - AssetManager, Assets, Authorship, Balances, CalamariVesting, Council, Democracy, - EnactmentPeriod, LaunchPeriod, NativeTokenExistentialDeposit, Origin, Period, PolkadotXcm, - Runtime, TechnicalCommittee, Timestamp, Treasury, Utility, VotingPeriod, + assets_config::{CalamariAssetConfig, CalamariConcreteFungibleLedger}, + currency::KMA, + fee::{ + FEES_PERCENTAGE_TO_AUTHOR, FEES_PERCENTAGE_TO_TREASURY, TIPS_PERCENTAGE_TO_AUTHOR, + TIPS_PERCENTAGE_TO_TREASURY, + }, + xcm_config::XcmFeesAccount, + AssetManager, Assets, Authorship, Balances, CalamariVesting, Council, Democracy, + EnactmentPeriod, LaunchPeriod, NativeTokenExistentialDeposit, Origin, Period, PolkadotXcm, + Runtime, TechnicalCommittee, Timestamp, Treasury, Utility, VotingPeriod, }; use frame_support::{ - assert_err, assert_ok, - codec::Encode, - dispatch::Dispatchable, - traits::{PalletInfo, StorageInfo, StorageInfoTrait, ValidatorSet}, - weights::constants::*, - StorageHasher, Twox128, + assert_err, assert_ok, + codec::Encode, + dispatch::Dispatchable, + traits::{PalletInfo, StorageInfo, StorageInfoTrait, ValidatorSet}, + weights::constants::*, + StorageHasher, Twox128, }; use manta_primitives::{ - assets::{ - AssetConfig, AssetLocation, AssetRegistrarMetadata, FungibleLedger, FungibleLedgerError, - }, - constants::time::{DAYS, HOURS}, - helpers::{get_account_id_from_seed, get_collator_keys_from_seed}, - types::{AccountId, Header}, + assets::{ + AssetConfig, AssetLocation, AssetRegistrarMetadata, FungibleLedger, FungibleLedgerError, + }, + constants::time::{DAYS, HOURS}, + helpers::{get_account_id_from_seed, get_collator_keys_from_seed}, + types::{AccountId, Header}, }; use xcm::{ - opaque::latest::{ - Junction::{PalletInstance, Parachain}, - Junctions::X2, - MultiLocation, - }, - VersionedMultiLocation, + opaque::latest::{ + Junction::{PalletInstance, Parachain}, + Junctions::X2, + MultiLocation, + }, + VersionedMultiLocation, }; use pallet_transaction_payment::ChargeTransactionPayment; @@ -62,1417 +64,1417 @@ use pallet_transaction_payment::ChargeTransactionPayment; use sp_consensus_aura::AURA_ENGINE_ID; use sp_core::{sr25519, H256}; use sp_runtime::{ - generic::DigestItem, - traits::{BlakeTwo256, Hash, Header as HeaderT, SignedExtension}, - DispatchError, ModuleError, Percent, + generic::DigestItem, + traits::{BlakeTwo256, Hash, Header as HeaderT, SignedExtension}, + DispatchError, ModuleError, Percent, }; fn note_preimage(proposer: &AccountId, proposal_call: &Call) -> H256 { - let preimage = proposal_call.encode(); - let preimage_hash = BlakeTwo256::hash(&preimage[..]); - assert_ok!(Democracy::note_preimage( - Origin::signed(proposer.clone()), - preimage.clone() - )); - preimage_hash + let preimage = proposal_call.encode(); + let preimage_hash = BlakeTwo256::hash(&preimage[..]); + assert_ok!(Democracy::note_preimage( + Origin::signed(proposer.clone()), + preimage + )); + preimage_hash } fn propose_council_motion(council_motion: &Call, proposer: &AccountId) -> H256 { - let council_motion_len: u32 = council_motion.using_encoded(|p| p.len() as u32); - assert_ok!(Council::propose( - Origin::signed(proposer.clone()), - 1, - Box::new(council_motion.clone()), - council_motion_len - )); - let council_motion_hash = BlakeTwo256::hash_of(&council_motion); - council_motion_hash + let council_motion_len: u32 = council_motion.using_encoded(|p| p.len() as u32); + assert_ok!(Council::propose( + Origin::signed(proposer.clone()), + 1, + Box::new(council_motion.clone()), + council_motion_len + )); + + BlakeTwo256::hash_of(&council_motion) } fn start_governance_assertions(proposer: &AccountId) -> H256 { - // Setup the preimage and preimage hash - let preimage_hash = note_preimage( - &proposer, - &Call::System(frame_system::Call::remark { remark: vec![0] }), - ); - - // Setup the Council and Technical Committee - assert_ok!(Council::set_members( - root_origin(), - vec![proposer.clone()], - None, - 0 - )); - assert_ok!(TechnicalCommittee::set_members( - root_origin(), - vec![proposer.clone()], - None, - 0 - )); - - // Setup and propose the Council motion for external_propose_default routine - // No voting required because there's only 1 seat. - let council_motion = Call::Democracy(pallet_democracy::Call::external_propose_default { - proposal_hash: preimage_hash, - }); - let council_motion_hash = propose_council_motion(&council_motion, &proposer); - - assert_eq!( - last_event(), - calamari_runtime::Event::Council(pallet_collective::Event::Executed { - proposal_hash: council_motion_hash, - result: Ok(()) - }) - ); - - preimage_hash + // Setup the preimage and preimage hash + let preimage_hash = note_preimage( + proposer, + &Call::System(frame_system::Call::remark { remark: vec![0] }), + ); + + // Setup the Council and Technical Committee + assert_ok!(Council::set_members( + root_origin(), + vec![proposer.clone()], + None, + 0 + )); + assert_ok!(TechnicalCommittee::set_members( + root_origin(), + vec![proposer.clone()], + None, + 0 + )); + + // Setup and propose the Council motion for external_propose_default routine + // No voting required because there's only 1 seat. + let council_motion = Call::Democracy(pallet_democracy::Call::external_propose_default { + proposal_hash: preimage_hash, + }); + let council_motion_hash = propose_council_motion(&council_motion, proposer); + + assert_eq!( + last_event(), + calamari_runtime::Event::Council(pallet_collective::Event::Executed { + proposal_hash: council_motion_hash, + result: Ok(()) + }) + ); + + preimage_hash } fn end_governance_assertions(referendum_index: u32, end_of_referendum: u32, enactment_period: u32) { - let time_of_enactment = end_of_referendum + enactment_period; - run_to_block(end_of_referendum - 1); - assert_eq!(1, Democracy::referendum_count()); - - // After the voting period the referendum ends and is scheduled for enactment: - run_to_block(end_of_referendum); - assert_eq!( - last_event(), - calamari_runtime::Event::Scheduler(pallet_scheduler::Event::Scheduled { - when: time_of_enactment, - index: referendum_index - }) - ); - - // After the enactment period the proposal is dispatched: - run_to_block(time_of_enactment); - assert_eq!( - last_event(), - calamari_runtime::Event::Scheduler(pallet_scheduler::Event::Dispatched { - task: (time_of_enactment, referendum_index), - id: Some(vec![100, 101, 109, 111, 99, 114, 97, 99, 0, 0, 0, 0]), - result: Ok(()) - }) - ); + let time_of_enactment = end_of_referendum + enactment_period; + run_to_block(end_of_referendum - 1); + assert_eq!(1, Democracy::referendum_count()); + + // After the voting period the referendum ends and is scheduled for enactment: + run_to_block(end_of_referendum); + assert_eq!( + last_event(), + calamari_runtime::Event::Scheduler(pallet_scheduler::Event::Scheduled { + when: time_of_enactment, + index: referendum_index + }) + ); + + // After the enactment period the proposal is dispatched: + run_to_block(time_of_enactment); + assert_eq!( + last_event(), + calamari_runtime::Event::Scheduler(pallet_scheduler::Event::Dispatched { + task: (time_of_enactment, referendum_index), + id: Some(vec![100, 101, 109, 111, 99, 114, 97, 99, 0, 0, 0, 0]), + result: Ok(()) + }) + ); } fn assert_proposal_is_filtered(proposer: &AccountId, motion: &Call) { - let council_motion_hash = propose_council_motion(&motion, &proposer); - - assert_eq!( - last_event(), - calamari_runtime::Event::Council(pallet_collective::Event::Executed { - proposal_hash: council_motion_hash, - result: Err(DispatchError::Module(ModuleError { - index: 0, - error: 5, - message: None - })) - }) - ); + let council_motion_hash = propose_council_motion(motion, proposer); + + assert_eq!( + last_event(), + calamari_runtime::Event::Council(pallet_collective::Event::Executed { + proposal_hash: council_motion_hash, + result: Err(DispatchError::Module(ModuleError { + index: 0, + error: 5, + message: None + })) + }) + ); } #[test] fn fast_track_available() { - assert!(::InstantAllowed::get()); + assert!(::InstantAllowed::get()); } #[test] fn sanity_check_governance_periods() { - assert_eq!(LaunchPeriod::get(), 7 * DAYS); - assert_eq!(VotingPeriod::get(), 7 * DAYS); - assert_eq!(EnactmentPeriod::get(), 1 * DAYS); + assert_eq!(LaunchPeriod::get(), 7 * DAYS); + assert_eq!(VotingPeriod::get(), 7 * DAYS); + assert_eq!(EnactmentPeriod::get(), 1 * DAYS); } #[test] fn slow_governance_works() { - let alice = get_account_id_from_seed::("Alice"); - - ExtBuilder::default().build().execute_with(|| { - let _preimage_hash = start_governance_assertions(&alice); - - let start_of_referendum = LaunchPeriod::get(); - let referendum_index = 0; - - run_to_block(start_of_referendum - 1); - assert_eq!(0, Democracy::referendum_count()); - - // 7 days in the external proposal queue before the referendum starts. - run_to_block(start_of_referendum); - assert_eq!( - last_event(), - calamari_runtime::Event::Democracy(pallet_democracy::Event::Started { - ref_index: referendum_index, - threshold: pallet_democracy::VoteThreshold::SuperMajorityAgainst - }) - ); - // Time to vote for the referendum with some amount - assert_ok!(Democracy::vote( - Origin::signed(alice.clone()), - 0, - pallet_democracy::AccountVote::Standard { - vote: pallet_democracy::Vote { - aye: true, - conviction: pallet_democracy::Conviction::None - }, - balance: 10 * KMA - } - )); - - end_governance_assertions( - referendum_index, - start_of_referendum + VotingPeriod::get(), - EnactmentPeriod::get(), - ); - }); + let alice = get_account_id_from_seed::("Alice"); + + ExtBuilder::default().build().execute_with(|| { + let _preimage_hash = start_governance_assertions(&alice); + + let start_of_referendum = LaunchPeriod::get(); + let referendum_index = 0; + + run_to_block(start_of_referendum - 1); + assert_eq!(0, Democracy::referendum_count()); + + // 7 days in the external proposal queue before the referendum starts. + run_to_block(start_of_referendum); + assert_eq!( + last_event(), + calamari_runtime::Event::Democracy(pallet_democracy::Event::Started { + ref_index: referendum_index, + threshold: pallet_democracy::VoteThreshold::SuperMajorityAgainst + }) + ); + // Time to vote for the referendum with some amount + assert_ok!(Democracy::vote( + Origin::signed(alice.clone()), + 0, + pallet_democracy::AccountVote::Standard { + vote: pallet_democracy::Vote { + aye: true, + conviction: pallet_democracy::Conviction::None + }, + balance: 10 * KMA + } + )); + + end_governance_assertions( + referendum_index, + start_of_referendum + VotingPeriod::get(), + EnactmentPeriod::get(), + ); + }); } #[test] fn fast_track_governance_works() { - let alice = get_account_id_from_seed::("Alice"); - - ExtBuilder::default().build().execute_with(|| { - let preimage_hash = start_governance_assertions(&alice); - - let voting_period = 5; - let enactment_period = 5; - let referendum_index = 0; - - // Setup and propose the Technical Committee motion for the fast_track routine - // No voting required because there's only 1 seat. - // Voting and delay periods of 5 blocks so this should be enacted on block 11 - let tech_committee_motion = Call::Democracy(pallet_democracy::Call::fast_track { - proposal_hash: preimage_hash, - voting_period: voting_period, - delay: enactment_period, - }); - let tech_committee_motion_len: u32 = - tech_committee_motion.using_encoded(|p| p.len() as u32); - let tech_committee_motion_hash = BlakeTwo256::hash_of(&tech_committee_motion); - assert_ok!(TechnicalCommittee::propose( - Origin::signed(alice.clone()), - 1, - Box::new(tech_committee_motion), - tech_committee_motion_len - )); - // Make sure the motion was actually executed - assert_eq!( - last_event(), - calamari_runtime::Event::TechnicalCommittee(pallet_collective::Event::Executed { - proposal_hash: tech_committee_motion_hash, - result: Ok(()) - }) - ); - - // Time to vote for the referendum with some amount - assert_ok!(Democracy::vote( - Origin::signed(alice.clone()), - referendum_index, - pallet_democracy::AccountVote::Standard { - vote: pallet_democracy::Vote { - aye: true, - conviction: pallet_democracy::Conviction::None - }, - balance: 10 * KMA - } - )); - - // No launch period because of the fast track. - end_governance_assertions( - referendum_index, - System::block_number() + voting_period, - enactment_period, - ); - }); + let alice = get_account_id_from_seed::("Alice"); + + ExtBuilder::default().build().execute_with(|| { + let preimage_hash = start_governance_assertions(&alice); + + let voting_period = 5; + let enactment_period = 5; + let referendum_index = 0; + + // Setup and propose the Technical Committee motion for the fast_track routine + // No voting required because there's only 1 seat. + // Voting and delay periods of 5 blocks so this should be enacted on block 11 + let tech_committee_motion = Call::Democracy(pallet_democracy::Call::fast_track { + proposal_hash: preimage_hash, + voting_period, + delay: enactment_period, + }); + let tech_committee_motion_len: u32 = + tech_committee_motion.using_encoded(|p| p.len() as u32); + let tech_committee_motion_hash = BlakeTwo256::hash_of(&tech_committee_motion); + assert_ok!(TechnicalCommittee::propose( + Origin::signed(alice.clone()), + 1, + Box::new(tech_committee_motion), + tech_committee_motion_len + )); + // Make sure the motion was actually executed + assert_eq!( + last_event(), + calamari_runtime::Event::TechnicalCommittee(pallet_collective::Event::Executed { + proposal_hash: tech_committee_motion_hash, + result: Ok(()) + }) + ); + + // Time to vote for the referendum with some amount + assert_ok!(Democracy::vote( + Origin::signed(alice.clone()), + referendum_index, + pallet_democracy::AccountVote::Standard { + vote: pallet_democracy::Vote { + aye: true, + conviction: pallet_democracy::Conviction::None + }, + balance: 10 * KMA + } + )); + + // No launch period because of the fast track. + end_governance_assertions( + referendum_index, + System::block_number() + voting_period, + enactment_period, + ); + }); } #[test] fn governance_filters_work() { - assert!(::InstantAllowed::get()); - - let alice = get_account_id_from_seed::("Alice"); - - ExtBuilder::default().build().execute_with(|| { - // Setup the preimage and preimage hash - let preimage_hash = note_preimage( - &alice, - &Call::System(frame_system::Call::remark { remark: vec![0] }), - ); - - // Setup the Council - assert_ok!(Council::set_members( - root_origin(), - vec![alice.clone()], - None, - 0 - )); - - // Public proposals should be filtered out. - assert_proposal_is_filtered( - &alice, - &Call::Democracy(pallet_democracy::Call::propose { - proposal_hash: preimage_hash, - value: 100 * KMA, - }), - ); - - // External proposals other than external_proposal_default should be filtered out. - assert_proposal_is_filtered( - &alice, - &Call::Democracy(pallet_democracy::Call::external_propose { - proposal_hash: preimage_hash, - }), - ); - - // External proposals other than external_proposal_default should be filtered out. - assert_proposal_is_filtered( - &alice, - &Call::Democracy(pallet_democracy::Call::external_propose_majority { - proposal_hash: preimage_hash, - }), - ); - }); + assert!(::InstantAllowed::get()); + + let alice = get_account_id_from_seed::("Alice"); + + ExtBuilder::default().build().execute_with(|| { + // Setup the preimage and preimage hash + let preimage_hash = note_preimage( + &alice, + &Call::System(frame_system::Call::remark { remark: vec![0] }), + ); + + // Setup the Council + assert_ok!(Council::set_members( + root_origin(), + vec![alice.clone()], + None, + 0 + )); + + // Public proposals should be filtered out. + assert_proposal_is_filtered( + &alice, + &Call::Democracy(pallet_democracy::Call::propose { + proposal_hash: preimage_hash, + value: 100 * KMA, + }), + ); + + // External proposals other than external_proposal_default should be filtered out. + assert_proposal_is_filtered( + &alice, + &Call::Democracy(pallet_democracy::Call::external_propose { + proposal_hash: preimage_hash, + }), + ); + + // External proposals other than external_proposal_default should be filtered out. + assert_proposal_is_filtered( + &alice, + &Call::Democracy(pallet_democracy::Call::external_propose_majority { + proposal_hash: preimage_hash, + }), + ); + }); } #[test] fn balances_operations_should_work() { - let alice = get_account_id_from_seed::("Alice"); - let bob = get_account_id_from_seed::("Bob"); - let charlie = get_account_id_from_seed::("Charlie"); - let dave = get_account_id_from_seed::("Dave"); - - ExtBuilder::default() - .with_balances(vec![ - (alice.clone(), INITIAL_BALANCE), - (bob.clone(), INITIAL_BALANCE), - (charlie.clone(), INITIAL_BALANCE), - (dave.clone(), INITIAL_BALANCE), - ]) - .with_authorities(vec![(alice.clone(), get_collator_keys_from_seed("Alice"))]) - .with_collators(vec![alice.clone()], 0) - .build() - .execute_with(|| { - let transfer_amount = 10 * KMA; - - // Basic transfer should work - assert_ok!(Balances::transfer( - Origin::signed(alice.clone()), - sp_runtime::MultiAddress::Id(charlie.clone()), - transfer_amount, - )); - assert_eq!( - Balances::free_balance(alice.clone()), - INITIAL_BALANCE - transfer_amount - ); - assert_eq!( - Balances::free_balance(charlie.clone()), - INITIAL_BALANCE + transfer_amount - ); - - // Force transfer some tokens from one account to another with Root - assert_ok!(Balances::force_transfer( - root_origin(), - sp_runtime::MultiAddress::Id(charlie.clone()), - sp_runtime::MultiAddress::Id(alice.clone()), - transfer_amount, - )); - assert_eq!(Balances::free_balance(alice.clone()), INITIAL_BALANCE); - assert_eq!(Balances::free_balance(charlie.clone()), INITIAL_BALANCE); - - // Should not be able to transfer all with this call - assert_err!( - Balances::transfer_keep_alive( - Origin::signed(alice.clone()), - sp_runtime::MultiAddress::Id(charlie.clone()), - INITIAL_BALANCE, - ), - pallet_balances::Error::::KeepAlive - ); - - // Transfer all down to zero - assert_ok!(Balances::transfer_all( - Origin::signed(bob.clone()), - sp_runtime::MultiAddress::Id(charlie.clone()), - false - )); - assert_eq!(Balances::free_balance(bob.clone()), 0); - assert_eq!(Balances::free_balance(charlie.clone()), INITIAL_BALANCE * 2); - - // Transfer all but keep alive with ED - assert_ok!(Balances::transfer_all( - Origin::signed(dave.clone()), - sp_runtime::MultiAddress::Id(alice.clone()), - true - )); - assert_eq!( - Balances::free_balance(dave.clone()), - NativeTokenExistentialDeposit::get() - ); - - // Even though keep alive is set to false alice cannot fall below the ED - // because it has an outstanding consumer reference, from being a collator. - assert_ok!(Balances::transfer_all( - Origin::signed(alice.clone()), - sp_runtime::MultiAddress::Id(charlie.clone()), - false - )); - assert_eq!( - Balances::free_balance(alice.clone()), - NativeTokenExistentialDeposit::get() - ); - }); + let alice = get_account_id_from_seed::("Alice"); + let bob = get_account_id_from_seed::("Bob"); + let charlie = get_account_id_from_seed::("Charlie"); + let dave = get_account_id_from_seed::("Dave"); + + ExtBuilder::default() + .with_balances(vec![ + (alice.clone(), INITIAL_BALANCE), + (bob.clone(), INITIAL_BALANCE), + (charlie.clone(), INITIAL_BALANCE), + (dave.clone(), INITIAL_BALANCE), + ]) + .with_authorities(vec![(alice.clone(), get_collator_keys_from_seed("Alice"))]) + .with_collators(vec![alice.clone()], 0) + .build() + .execute_with(|| { + let transfer_amount = 10 * KMA; + + // Basic transfer should work + assert_ok!(Balances::transfer( + Origin::signed(alice.clone()), + sp_runtime::MultiAddress::Id(charlie.clone()), + transfer_amount, + )); + assert_eq!( + Balances::free_balance(alice.clone()), + INITIAL_BALANCE - transfer_amount + ); + assert_eq!( + Balances::free_balance(charlie.clone()), + INITIAL_BALANCE + transfer_amount + ); + + // Force transfer some tokens from one account to another with Root + assert_ok!(Balances::force_transfer( + root_origin(), + sp_runtime::MultiAddress::Id(charlie.clone()), + sp_runtime::MultiAddress::Id(alice.clone()), + transfer_amount, + )); + assert_eq!(Balances::free_balance(alice.clone()), INITIAL_BALANCE); + assert_eq!(Balances::free_balance(charlie.clone()), INITIAL_BALANCE); + + // Should not be able to transfer all with this call + assert_err!( + Balances::transfer_keep_alive( + Origin::signed(alice.clone()), + sp_runtime::MultiAddress::Id(charlie.clone()), + INITIAL_BALANCE, + ), + pallet_balances::Error::::KeepAlive + ); + + // Transfer all down to zero + assert_ok!(Balances::transfer_all( + Origin::signed(bob.clone()), + sp_runtime::MultiAddress::Id(charlie.clone()), + false + )); + assert_eq!(Balances::free_balance(bob.clone()), 0); + assert_eq!(Balances::free_balance(charlie.clone()), INITIAL_BALANCE * 2); + + // Transfer all but keep alive with ED + assert_ok!(Balances::transfer_all( + Origin::signed(dave.clone()), + sp_runtime::MultiAddress::Id(alice.clone()), + true + )); + assert_eq!( + Balances::free_balance(dave.clone()), + NativeTokenExistentialDeposit::get() + ); + + // Even though keep alive is set to false alice cannot fall below the ED + // because it has an outstanding consumer reference, from being a collator. + assert_ok!(Balances::transfer_all( + Origin::signed(alice.clone()), + sp_runtime::MultiAddress::Id(charlie.clone()), + false + )); + assert_eq!( + Balances::free_balance(alice.clone()), + NativeTokenExistentialDeposit::get() + ); + }); } fn seal_header(mut header: Header, author: AccountId) -> Header { - { - let digest = header.digest_mut(); - digest - .logs - .push(DigestItem::PreRuntime(AURA_ENGINE_ID, author.encode())); - digest - .logs - .push(DigestItem::Seal(AURA_ENGINE_ID, author.encode())); - } - - header + { + let digest = header.digest_mut(); + digest + .logs + .push(DigestItem::PreRuntime(AURA_ENGINE_ID, author.encode())); + digest + .logs + .push(DigestItem::Seal(AURA_ENGINE_ID, author.encode())); + } + + header } #[test] fn sanity_check_fees_and_tips_splits() { - assert_eq!(100, TIPS_PERCENTAGE_TO_AUTHOR + TIPS_PERCENTAGE_TO_TREASURY); - assert_eq!(100, FEES_PERCENTAGE_TO_AUTHOR + FEES_PERCENTAGE_TO_TREASURY); + assert_eq!(100, TIPS_PERCENTAGE_TO_AUTHOR + TIPS_PERCENTAGE_TO_TREASURY); + assert_eq!(100, FEES_PERCENTAGE_TO_AUTHOR + FEES_PERCENTAGE_TO_TREASURY); } #[test] fn reward_fees_to_block_author_and_treasury() { - let alice = get_account_id_from_seed::("Alice"); - let bob = get_account_id_from_seed::("Bob"); - let charlie = get_account_id_from_seed::("Charlie"); - let desired_candidates = 0; - - ExtBuilder::default() - .with_balances(vec![ - (alice.clone(), INITIAL_BALANCE), - (bob.clone(), INITIAL_BALANCE), - (charlie.clone(), INITIAL_BALANCE), - ]) - .with_authorities(vec![(alice.clone(), get_collator_keys_from_seed("Alice"))]) - .with_collators(vec![alice.clone()], desired_candidates) - .build() - .execute_with(|| { - let author = alice.clone(); - let mut header = seal_header( - Header::new( - 0, - Default::default(), - Default::default(), - Default::default(), - Default::default(), - ), - author.clone(), - ); - - header.digest_mut().pop(); // pop the seal off. - calamari_runtime::System::initialize(&1, &Default::default(), header.digest()); - assert_eq!(Authorship::author().unwrap(), author); - - let call = Call::Balances(pallet_balances::Call::transfer { - dest: sp_runtime::MultiAddress::Id(charlie), - value: 10 * KMA, - }); - - let len = 10; - let info = info_from_weight(100); - let maybe_pre = ChargeTransactionPayment::::from(0) - .pre_dispatch(&bob, &call, &info, len) - .unwrap(); - - let res = call.clone().dispatch(Origin::signed(bob)); - - let post_info = match res { - Ok(info) => info, - Err(err) => err.post_info, - }; - - let _res = ChargeTransactionPayment::::post_dispatch( - Some(maybe_pre), - &info, - &post_info, - len, - &res.map(|_| ()).map_err(|e| e.error), - ); - - let author_received_reward = Balances::free_balance(alice) - INITIAL_BALANCE; - println!("The rewarded_amount is: {:?}", author_received_reward); - - let author_percent = Percent::from_percent(FEES_PERCENTAGE_TO_AUTHOR); - let expected_fee = - TransactionPayment::compute_actual_fee(len as u32, &info, &post_info, 0); - assert_eq!(author_received_reward, author_percent * expected_fee); - - let treasury_percent = Percent::from_percent(FEES_PERCENTAGE_TO_TREASURY); - assert_eq!( - Balances::free_balance(Treasury::account_id()), - treasury_percent * expected_fee - ); - }); + let alice = get_account_id_from_seed::("Alice"); + let bob = get_account_id_from_seed::("Bob"); + let charlie = get_account_id_from_seed::("Charlie"); + let desired_candidates = 0; + + ExtBuilder::default() + .with_balances(vec![ + (alice.clone(), INITIAL_BALANCE), + (bob.clone(), INITIAL_BALANCE), + (charlie.clone(), INITIAL_BALANCE), + ]) + .with_authorities(vec![(alice.clone(), get_collator_keys_from_seed("Alice"))]) + .with_collators(vec![alice.clone()], desired_candidates) + .build() + .execute_with(|| { + let author = alice.clone(); + let mut header = seal_header( + Header::new( + 0, + Default::default(), + Default::default(), + Default::default(), + Default::default(), + ), + author.clone(), + ); + + header.digest_mut().pop(); // pop the seal off. + calamari_runtime::System::initialize(&1, &Default::default(), header.digest()); + assert_eq!(Authorship::author().unwrap(), author); + + let call = Call::Balances(pallet_balances::Call::transfer { + dest: sp_runtime::MultiAddress::Id(charlie), + value: 10 * KMA, + }); + + let len = 10; + let info = info_from_weight(100); + let maybe_pre = ChargeTransactionPayment::::from(0) + .pre_dispatch(&bob, &call, &info, len) + .unwrap(); + + let res = call.dispatch(Origin::signed(bob)); + + let post_info = match res { + Ok(info) => info, + Err(err) => err.post_info, + }; + + let _res = ChargeTransactionPayment::::post_dispatch( + Some(maybe_pre), + &info, + &post_info, + len, + &res.map(|_| ()).map_err(|e| e.error), + ); + + let author_received_reward = Balances::free_balance(alice) - INITIAL_BALANCE; + println!("The rewarded_amount is: {:?}", author_received_reward); + + let author_percent = Percent::from_percent(FEES_PERCENTAGE_TO_AUTHOR); + let expected_fee = + TransactionPayment::compute_actual_fee(len as u32, &info, &post_info, 0); + assert_eq!(author_received_reward, author_percent * expected_fee); + + let treasury_percent = Percent::from_percent(FEES_PERCENTAGE_TO_TREASURY); + assert_eq!( + Balances::free_balance(Treasury::account_id()), + treasury_percent * expected_fee + ); + }); } #[test] fn root_can_change_default_xcm_vers() { - ExtBuilder::default().build().execute_with(|| { - // Root sets the defaultXcm - assert_ok!(PolkadotXcm::force_default_xcm_version( - root_origin(), - Some(2) - )); - }) + ExtBuilder::default().build().execute_with(|| { + // Root sets the defaultXcm + assert_ok!(PolkadotXcm::force_default_xcm_version( + root_origin(), + Some(2) + )); + }) } #[test] fn sanity_check_session_period() { - assert_eq!(Period::get(), 6 * HOURS); + assert_eq!(Period::get(), 6 * HOURS); } fn advance_session_assertions(session_index: &mut u32, advance_by: u32) { - *session_index += advance_by; + *session_index += advance_by; - run_to_block(*session_index * Period::get() - 1); - assert_eq!(Session::session_index(), *session_index - 1); + run_to_block(*session_index * Period::get() - 1); + assert_eq!(Session::session_index(), *session_index - 1); - run_to_block(*session_index * Period::get()); - assert_eq!(Session::session_index(), *session_index); + run_to_block(*session_index * Period::get()); + assert_eq!(Session::session_index(), *session_index); } #[test] fn session_and_collator_selection_work() { - let alice = get_account_id_from_seed::("Alice"); - let bob = get_account_id_from_seed::("Bob"); - let alice_aura = get_collator_keys_from_seed("Alice"); - let bob_aura = get_collator_keys_from_seed("Bob"); - let desired_candidates = 1; - - ExtBuilder::default() - .with_collators(vec![alice.clone()], desired_candidates) - .with_balances(vec![ - (alice.clone(), INITIAL_BALANCE), - (bob.clone(), INITIAL_BALANCE), - ]) - .build() - .execute_with(|| { - // Alice is in the invulnerables set, so not part of the candidates set. - assert_eq!(CollatorSelection::candidates(), vec![]); - - // Create and bond session keys to Bob's account. - let keys = calamari_runtime::opaque::SessionKeys { - aura: bob_aura.clone(), - }; - assert_ok!(Session::set_keys(Origin::signed(bob.clone()), keys, vec![])); - - assert_ok!(CollatorSelection::register_candidate( - root_origin(), - bob.clone() - )); - let candidate = manta_collator_selection::CandidateInfo { - who: bob.clone(), - deposit: BOND_AMOUNT, - }; - - // Bob is a candidate but only Alice is queued as a collator in this session. - assert_eq!(CollatorSelection::candidates(), vec![candidate.clone()]); - assert_eq!( - Session::queued_keys(), - vec![( - alice.clone(), - calamari_runtime::opaque::SessionKeys { - aura: alice_aura.clone(), - } - )] - ); - assert_eq!(Session::validators(), vec![alice.clone()]); - - let mut session_index = 0; - assert_eq!(Session::session_index(), session_index); - - advance_session_assertions(&mut session_index, 1); - - // After 1 sessions both Alice and Bob are queued for collators - // But only Alice is actually a collator for now. - assert_eq!( - Session::queued_keys(), - vec![ - ( - alice.clone(), - calamari_runtime::opaque::SessionKeys { - aura: alice_aura.clone(), - } - ), - ( - bob.clone(), - calamari_runtime::opaque::SessionKeys { - aura: bob_aura.clone(), - } - ) - ] - ); - assert_eq!(Session::validators(), vec![alice.clone()]); - - advance_session_assertions(&mut session_index, 1); - - // Bob has finally been included as a collator - // Note that we started from block 1, so the delay period of 1 full session - // required us to wait until session index 2. - assert_eq!(Session::validators(), vec![alice.clone(), bob.clone()]); - - // Once Bob decides to leave he will be removed from the candidates set immediately. - assert_ok!(CollatorSelection::leave_intent(Origin::signed(bob.clone()))); - assert_eq!(CollatorSelection::candidates(), vec![]); - - // But will not leave as a validator until after one full session. - assert_eq!(Session::validators(), vec![alice.clone(), bob.clone()]); - - advance_session_assertions(&mut session_index, 1); - - assert_eq!(Session::validators(), vec![alice.clone(), bob.clone()]); - - advance_session_assertions(&mut session_index, 1); - - // Bob was removed as a collator. - assert_eq!(Session::validators(), vec![alice.clone()]); - }); + let alice = get_account_id_from_seed::("Alice"); + let bob = get_account_id_from_seed::("Bob"); + let alice_aura = get_collator_keys_from_seed("Alice"); + let bob_aura = get_collator_keys_from_seed("Bob"); + let desired_candidates = 1; + + ExtBuilder::default() + .with_collators(vec![alice.clone()], desired_candidates) + .with_balances(vec![ + (alice.clone(), INITIAL_BALANCE), + (bob.clone(), INITIAL_BALANCE), + ]) + .build() + .execute_with(|| { + // Alice is in the invulnerables set, so not part of the candidates set. + assert_eq!(CollatorSelection::candidates(), vec![]); + + // Create and bond session keys to Bob's account. + let keys = calamari_runtime::opaque::SessionKeys { + aura: bob_aura.clone(), + }; + assert_ok!(Session::set_keys(Origin::signed(bob.clone()), keys, vec![])); + + assert_ok!(CollatorSelection::register_candidate( + root_origin(), + bob.clone() + )); + let candidate = manta_collator_selection::CandidateInfo { + who: bob.clone(), + deposit: BOND_AMOUNT, + }; + + // Bob is a candidate but only Alice is queued as a collator in this session. + assert_eq!(CollatorSelection::candidates(), vec![candidate]); + assert_eq!( + Session::queued_keys(), + vec![( + alice.clone(), + calamari_runtime::opaque::SessionKeys { + aura: alice_aura.clone(), + } + )] + ); + assert_eq!(Session::validators(), vec![alice.clone()]); + + let mut session_index = 0; + assert_eq!(Session::session_index(), session_index); + + advance_session_assertions(&mut session_index, 1); + + // After 1 sessions both Alice and Bob are queued for collators + // But only Alice is actually a collator for now. + assert_eq!( + Session::queued_keys(), + vec![ + ( + alice.clone(), + calamari_runtime::opaque::SessionKeys { + aura: alice_aura.clone(), + } + ), + ( + bob.clone(), + calamari_runtime::opaque::SessionKeys { + aura: bob_aura.clone(), + } + ) + ] + ); + assert_eq!(Session::validators(), vec![alice.clone()]); + + advance_session_assertions(&mut session_index, 1); + + // Bob has finally been included as a collator + // Note that we started from block 1, so the delay period of 1 full session + // required us to wait until session index 2. + assert_eq!(Session::validators(), vec![alice.clone(), bob.clone()]); + + // Once Bob decides to leave he will be removed from the candidates set immediately. + assert_ok!(CollatorSelection::leave_intent(Origin::signed(bob.clone()))); + assert_eq!(CollatorSelection::candidates(), vec![]); + + // But will not leave as a validator until after one full session. + assert_eq!(Session::validators(), vec![alice.clone(), bob.clone()]); + + advance_session_assertions(&mut session_index, 1); + + assert_eq!(Session::validators(), vec![alice.clone(), bob.clone()]); + + advance_session_assertions(&mut session_index, 1); + + // Bob was removed as a collator. + assert_eq!(Session::validators(), vec![alice.clone()]); + }); } #[test] fn batched_registration_of_collator_candidates_works() { - let alice = get_account_id_from_seed::("Alice"); - let bob = get_account_id_from_seed::("Bob"); - let charlie = get_account_id_from_seed::("Charlie"); - let alice_aura = get_collator_keys_from_seed("Alice"); - let bob_aura = get_collator_keys_from_seed("Bob"); - let charlie_aura = get_collator_keys_from_seed("Charlie"); - let desired_candidates = 2; - - ExtBuilder::default() - .with_balances(vec![ - (alice.clone(), INITIAL_BALANCE), - (bob.clone(), INITIAL_BALANCE), - (charlie.clone(), INITIAL_BALANCE), - ]) - .with_collators(vec![alice.clone()], desired_candidates) - .build() - .execute_with(|| { - let keys = calamari_runtime::opaque::SessionKeys { - aura: bob_aura.clone(), - }; - assert_ok!(Session::set_keys(Origin::signed(bob.clone()), keys, vec![])); - - let keys = calamari_runtime::opaque::SessionKeys { - aura: charlie_aura.clone(), - }; - assert_ok!(Session::set_keys( - Origin::signed(charlie.clone()), - keys, - vec![] - )); - - assert_eq!(CollatorSelection::candidates(), vec![]); - - assert_ok!(Utility::batch( - root_origin(), - vec![ - Call::CollatorSelection(manta_collator_selection::Call::register_candidate { - new_candidate: bob.clone(), - }), - Call::CollatorSelection(manta_collator_selection::Call::register_candidate { - new_candidate: charlie.clone(), - }), - ], - )); - - let candidate_bob = manta_collator_selection::CandidateInfo { - who: bob.clone(), - deposit: BOND_AMOUNT, - }; - let candidate_charlie = manta_collator_selection::CandidateInfo { - who: charlie.clone(), - deposit: BOND_AMOUNT, - }; - assert_eq!( - CollatorSelection::candidates(), - vec![candidate_bob, candidate_charlie] - ); - assert_eq!( - Session::queued_keys(), - vec![( - alice.clone(), - calamari_runtime::opaque::SessionKeys { - aura: alice_aura.clone(), - } - ),] - ); - assert_eq!(Session::validators(), vec![alice.clone()]); - - let mut session_index = 1; - run_to_block(session_index * Period::get()); - - let all_collator_pairs = vec![ - ( - alice.clone(), - calamari_runtime::opaque::SessionKeys { - aura: alice_aura.clone(), - }, - ), - ( - bob.clone(), - calamari_runtime::opaque::SessionKeys { - aura: bob_aura.clone(), - }, - ), - ( - charlie.clone(), - calamari_runtime::opaque::SessionKeys { - aura: charlie_aura.clone(), - }, - ), - ]; - - assert_eq!(Session::queued_keys(), all_collator_pairs); - assert_eq!(Session::validators(), vec![alice.clone()]); - - session_index += 1; - run_to_block(session_index * Period::get()); - - assert_eq!(Session::queued_keys(), all_collator_pairs); - assert_eq!( - Session::validators(), - vec![alice.clone(), bob.clone(), charlie.clone()] - ); - }); + let alice = get_account_id_from_seed::("Alice"); + let bob = get_account_id_from_seed::("Bob"); + let charlie = get_account_id_from_seed::("Charlie"); + let alice_aura = get_collator_keys_from_seed("Alice"); + let bob_aura = get_collator_keys_from_seed("Bob"); + let charlie_aura = get_collator_keys_from_seed("Charlie"); + let desired_candidates = 2; + + ExtBuilder::default() + .with_balances(vec![ + (alice.clone(), INITIAL_BALANCE), + (bob.clone(), INITIAL_BALANCE), + (charlie.clone(), INITIAL_BALANCE), + ]) + .with_collators(vec![alice.clone()], desired_candidates) + .build() + .execute_with(|| { + let keys = calamari_runtime::opaque::SessionKeys { + aura: bob_aura.clone(), + }; + assert_ok!(Session::set_keys(Origin::signed(bob.clone()), keys, vec![])); + + let keys = calamari_runtime::opaque::SessionKeys { + aura: charlie_aura.clone(), + }; + assert_ok!(Session::set_keys( + Origin::signed(charlie.clone()), + keys, + vec![] + )); + + assert_eq!(CollatorSelection::candidates(), vec![]); + + assert_ok!(Utility::batch( + root_origin(), + vec![ + Call::CollatorSelection(manta_collator_selection::Call::register_candidate { + new_candidate: bob.clone(), + }), + Call::CollatorSelection(manta_collator_selection::Call::register_candidate { + new_candidate: charlie.clone(), + }), + ], + )); + + let candidate_bob = manta_collator_selection::CandidateInfo { + who: bob.clone(), + deposit: BOND_AMOUNT, + }; + let candidate_charlie = manta_collator_selection::CandidateInfo { + who: charlie.clone(), + deposit: BOND_AMOUNT, + }; + assert_eq!( + CollatorSelection::candidates(), + vec![candidate_bob, candidate_charlie] + ); + assert_eq!( + Session::queued_keys(), + vec![( + alice.clone(), + calamari_runtime::opaque::SessionKeys { + aura: alice_aura.clone(), + } + ),] + ); + assert_eq!(Session::validators(), vec![alice.clone()]); + + let mut session_index = 1; + run_to_block(session_index * Period::get()); + + let all_collator_pairs = vec![ + ( + alice.clone(), + calamari_runtime::opaque::SessionKeys { + aura: alice_aura.clone(), + }, + ), + ( + bob.clone(), + calamari_runtime::opaque::SessionKeys { + aura: bob_aura.clone(), + }, + ), + ( + charlie.clone(), + calamari_runtime::opaque::SessionKeys { + aura: charlie_aura.clone(), + }, + ), + ]; + + assert_eq!(Session::queued_keys(), all_collator_pairs); + assert_eq!(Session::validators(), vec![alice.clone()]); + + session_index += 1; + run_to_block(session_index * Period::get()); + + assert_eq!(Session::queued_keys(), all_collator_pairs); + assert_eq!( + Session::validators(), + vec![alice.clone(), bob.clone(), charlie.clone()] + ); + }); } #[test] fn sanity_check_weight_per_time_constants_are_as_expected() { - // These values comes from Substrate, we want to make sure that if it - // ever changes we don't accidentally break Polkadot - assert_eq!(WEIGHT_PER_SECOND, 1_000_000_000_000); - assert_eq!(WEIGHT_PER_MILLIS, WEIGHT_PER_SECOND / 1000); - assert_eq!(WEIGHT_PER_MICROS, WEIGHT_PER_MILLIS / 1000); - assert_eq!(WEIGHT_PER_NANOS, WEIGHT_PER_MICROS / 1000); + // These values comes from Substrate, we want to make sure that if it + // ever changes we don't accidentally break Polkadot + assert_eq!(WEIGHT_PER_SECOND, 1_000_000_000_000); + assert_eq!(WEIGHT_PER_MILLIS, WEIGHT_PER_SECOND / 1000); + assert_eq!(WEIGHT_PER_MICROS, WEIGHT_PER_MILLIS / 1000); + assert_eq!(WEIGHT_PER_NANOS, WEIGHT_PER_MICROS / 1000); } #[test] fn calamari_vesting_works() { - ExtBuilder::default().build().execute_with(|| { - let alice = get_account_id_from_seed::("Alice"); - let bob = get_account_id_from_seed::("Bob"); - - let unvested = 100 * KMA; - assert_ok!(CalamariVesting::vested_transfer( - Origin::signed(alice), - sp_runtime::MultiAddress::Id(bob.clone()), - unvested - )); - - assert_eq!(Balances::free_balance(&bob), 100 * KMA); - assert_eq!(Balances::usable_balance(&bob), 0); - - let schedule = calamari_vesting::Pallet::::vesting_schedule(); - let mut vested = 0; - - for period in 0..schedule.len() { - // Timestamp expects milliseconds, so multiply by 1_000 to convert from seconds. - let now = schedule[period].1 * 1_000 + 1; - Timestamp::set_timestamp(now); - assert_ok!(CalamariVesting::vest(Origin::signed(bob.clone()))); - vested += schedule[period].0 * unvested; - assert_eq!(Balances::usable_balance(&bob), vested); - } - }); + ExtBuilder::default().build().execute_with(|| { + let alice = get_account_id_from_seed::("Alice"); + let bob = get_account_id_from_seed::("Bob"); + + let unvested = 100 * KMA; + assert_ok!(CalamariVesting::vested_transfer( + Origin::signed(alice), + sp_runtime::MultiAddress::Id(bob.clone()), + unvested + )); + + assert_eq!(Balances::free_balance(&bob), 100 * KMA); + assert_eq!(Balances::usable_balance(&bob), 0); + + let schedule = calamari_vesting::Pallet::::vesting_schedule(); + let mut vested = 0; + + for period in 0..schedule.len() { + // Timestamp expects milliseconds, so multiply by 1_000 to convert from seconds. + let now = schedule[period].1 * 1_000 + 1; + Timestamp::set_timestamp(now); + assert_ok!(CalamariVesting::vest(Origin::signed(bob.clone()))); + vested += schedule[period].0 * unvested; + assert_eq!(Balances::usable_balance(&bob), vested); + } + }); } #[test] fn verify_pallet_prefixes() { - fn is_pallet_prefix(name: &str) { - // Compares the unhashed pallet prefix in the `StorageInstance` implementation by every - // storage item in the pallet P. This pallet prefix is used in conjunction with the - // item name to get the unique storage key: hash(PalletPrefix) + hash(StorageName) - // https://github.com/paritytech/substrate/blob/master/frame/support/procedural/src/pallet/ - // expand/storage.rs#L389-L401 - assert_eq!( - ::PalletInfo::name::

(), - Some(name) - ); - } - - is_pallet_prefix::("System"); - is_pallet_prefix::("ParachainSystem"); - is_pallet_prefix::("Timestamp"); - is_pallet_prefix::("ParachainInfo"); - is_pallet_prefix::("TransactionPause"); - is_pallet_prefix::("Balances"); - is_pallet_prefix::("TransactionPayment"); - is_pallet_prefix::("Democracy"); - is_pallet_prefix::("Council"); - is_pallet_prefix::("CouncilMembership"); - is_pallet_prefix::("TechnicalCommittee"); - is_pallet_prefix::("TechnicalMembership"); - is_pallet_prefix::("Authorship"); - is_pallet_prefix::("CollatorSelection"); - is_pallet_prefix::("Session"); - is_pallet_prefix::("Aura"); - is_pallet_prefix::("AuraExt"); - is_pallet_prefix::("Treasury"); - is_pallet_prefix::("Scheduler"); - is_pallet_prefix::("XcmpQueue"); - is_pallet_prefix::("PolkadotXcm"); - is_pallet_prefix::("CumulusXcm"); - is_pallet_prefix::("DmpQueue"); - is_pallet_prefix::("Utility"); - is_pallet_prefix::("Multisig"); - is_pallet_prefix::("CalamariVesting"); - - let prefix = |pallet_name, storage_name| { - let mut res = [0u8; 32]; - res[0..16].copy_from_slice(&Twox128::hash(pallet_name)); - res[16..32].copy_from_slice(&Twox128::hash(storage_name)); - res.to_vec() - }; - assert_eq!( - ::storage_info(), - vec![ - StorageInfo { - pallet_name: b"Timestamp".to_vec(), - storage_name: b"Now".to_vec(), - prefix: prefix(b"Timestamp", b"Now"), - max_values: Some(1), - max_size: Some(8), - }, - StorageInfo { - pallet_name: b"Timestamp".to_vec(), - storage_name: b"DidUpdate".to_vec(), - prefix: prefix(b"Timestamp", b"DidUpdate"), - max_values: Some(1), - max_size: Some(1), - } - ] - ); - assert_eq!( - ::storage_info(), - vec![ - StorageInfo { - pallet_name: b"Balances".to_vec(), - storage_name: b"TotalIssuance".to_vec(), - prefix: prefix(b"Balances", b"TotalIssuance"), - max_values: Some(1), - max_size: Some(16), - }, - StorageInfo { - pallet_name: b"Balances".to_vec(), - storage_name: b"Account".to_vec(), - prefix: prefix(b"Balances", b"Account"), - max_values: Some(300_000), - max_size: Some(112), - }, - StorageInfo { - pallet_name: b"Balances".to_vec(), - storage_name: b"Locks".to_vec(), - prefix: prefix(b"Balances", b"Locks"), - max_values: Some(300_000), - max_size: Some(1299), - }, - StorageInfo { - pallet_name: b"Balances".to_vec(), - storage_name: b"Reserves".to_vec(), - prefix: prefix(b"Balances", b"Reserves"), - max_values: None, - max_size: Some(1249), - }, - StorageInfo { - pallet_name: b"Balances".to_vec(), - storage_name: b"StorageVersion".to_vec(), - prefix: prefix(b"Balances", b"StorageVersion"), - max_values: Some(1), - max_size: Some(1), - } - ] - ); + fn is_pallet_prefix(name: &str) { + // Compares the unhashed pallet prefix in the `StorageInstance` implementation by every + // storage item in the pallet P. This pallet prefix is used in conjunction with the + // item name to get the unique storage key: hash(PalletPrefix) + hash(StorageName) + // https://github.com/paritytech/substrate/blob/master/frame/support/procedural/src/pallet/ + // expand/storage.rs#L389-L401 + assert_eq!( + ::PalletInfo::name::

(), + Some(name) + ); + } + + is_pallet_prefix::("System"); + is_pallet_prefix::("ParachainSystem"); + is_pallet_prefix::("Timestamp"); + is_pallet_prefix::("ParachainInfo"); + is_pallet_prefix::("TransactionPause"); + is_pallet_prefix::("Balances"); + is_pallet_prefix::("TransactionPayment"); + is_pallet_prefix::("Democracy"); + is_pallet_prefix::("Council"); + is_pallet_prefix::("CouncilMembership"); + is_pallet_prefix::("TechnicalCommittee"); + is_pallet_prefix::("TechnicalMembership"); + is_pallet_prefix::("Authorship"); + is_pallet_prefix::("CollatorSelection"); + is_pallet_prefix::("Session"); + is_pallet_prefix::("Aura"); + is_pallet_prefix::("AuraExt"); + is_pallet_prefix::("Treasury"); + is_pallet_prefix::("Scheduler"); + is_pallet_prefix::("XcmpQueue"); + is_pallet_prefix::("PolkadotXcm"); + is_pallet_prefix::("CumulusXcm"); + is_pallet_prefix::("DmpQueue"); + is_pallet_prefix::("Utility"); + is_pallet_prefix::("Multisig"); + is_pallet_prefix::("CalamariVesting"); + + let prefix = |pallet_name, storage_name| { + let mut res = [0u8; 32]; + res[0..16].copy_from_slice(&Twox128::hash(pallet_name)); + res[16..32].copy_from_slice(&Twox128::hash(storage_name)); + res.to_vec() + }; + assert_eq!( + ::storage_info(), + vec![ + StorageInfo { + pallet_name: b"Timestamp".to_vec(), + storage_name: b"Now".to_vec(), + prefix: prefix(b"Timestamp", b"Now"), + max_values: Some(1), + max_size: Some(8), + }, + StorageInfo { + pallet_name: b"Timestamp".to_vec(), + storage_name: b"DidUpdate".to_vec(), + prefix: prefix(b"Timestamp", b"DidUpdate"), + max_values: Some(1), + max_size: Some(1), + } + ] + ); + assert_eq!( + ::storage_info(), + vec![ + StorageInfo { + pallet_name: b"Balances".to_vec(), + storage_name: b"TotalIssuance".to_vec(), + prefix: prefix(b"Balances", b"TotalIssuance"), + max_values: Some(1), + max_size: Some(16), + }, + StorageInfo { + pallet_name: b"Balances".to_vec(), + storage_name: b"Account".to_vec(), + prefix: prefix(b"Balances", b"Account"), + max_values: Some(300_000), + max_size: Some(112), + }, + StorageInfo { + pallet_name: b"Balances".to_vec(), + storage_name: b"Locks".to_vec(), + prefix: prefix(b"Balances", b"Locks"), + max_values: Some(300_000), + max_size: Some(1299), + }, + StorageInfo { + pallet_name: b"Balances".to_vec(), + storage_name: b"Reserves".to_vec(), + prefix: prefix(b"Balances", b"Reserves"), + max_values: None, + max_size: Some(1249), + }, + StorageInfo { + pallet_name: b"Balances".to_vec(), + storage_name: b"StorageVersion".to_vec(), + prefix: prefix(b"Balances", b"StorageVersion"), + max_values: Some(1), + max_size: Some(1), + } + ] + ); } #[test] fn test_collectives_storage_item_prefixes() { - for StorageInfo { pallet_name, .. } in - ::storage_info() - { - assert_eq!(pallet_name, b"CouncilMembership".to_vec()); - } - - for StorageInfo { pallet_name, .. } in - ::storage_info() - { - assert_eq!(pallet_name, b"TechnicalMembership".to_vec()); - } + for StorageInfo { pallet_name, .. } in + ::storage_info() + { + assert_eq!(pallet_name, b"CouncilMembership".to_vec()); + } + + for StorageInfo { pallet_name, .. } in + ::storage_info() + { + assert_eq!(pallet_name, b"TechnicalMembership".to_vec()); + } } #[test] fn verify_pallet_indices() { - fn is_pallet_index(index: usize) { - assert_eq!( - ::PalletInfo::index::

(), - Some(index) - ); - } - - is_pallet_index::(0); - is_pallet_index::(1); - is_pallet_index::(2); - is_pallet_index::(3); - is_pallet_index::(9); - is_pallet_index::(10); - is_pallet_index::(11); - is_pallet_index::(14); - is_pallet_index::(15); - is_pallet_index::(16); - is_pallet_index::(17); - is_pallet_index::(18); - is_pallet_index::(20); - is_pallet_index::(21); - is_pallet_index::(22); - is_pallet_index::(23); - is_pallet_index::(24); - is_pallet_index::(26); - is_pallet_index::(28); - is_pallet_index::(29); - is_pallet_index::(30); - is_pallet_index::(31); - is_pallet_index::(32); - is_pallet_index::(33); - is_pallet_index::(34); - is_pallet_index::(40); - is_pallet_index::(41); - is_pallet_index::(45); - is_pallet_index::(46); - is_pallet_index::(50); - - // Check removed pallets. - ExtBuilder::default().build().execute_with(|| { - use frame_support::metadata::{v14::META_RESERVED, RuntimeMetadata}; - - let runtime_metadata = calamari_runtime::Runtime::metadata(); - assert_eq!(runtime_metadata.0, META_RESERVED); - if let RuntimeMetadata::V14(v14) = runtime_metadata.1 { - // Ensure sudo=42 has been removed, no one is taking this index. - assert!(v14.pallets.iter().any(|pallet| pallet.index != 42)); - } - }); + fn is_pallet_index(index: usize) { + assert_eq!( + ::PalletInfo::index::

(), + Some(index) + ); + } + + is_pallet_index::(0); + is_pallet_index::(1); + is_pallet_index::(2); + is_pallet_index::(3); + is_pallet_index::(9); + is_pallet_index::(10); + is_pallet_index::(11); + is_pallet_index::(14); + is_pallet_index::(15); + is_pallet_index::(16); + is_pallet_index::(17); + is_pallet_index::(18); + is_pallet_index::(20); + is_pallet_index::(21); + is_pallet_index::(22); + is_pallet_index::(23); + is_pallet_index::(24); + is_pallet_index::(26); + is_pallet_index::(28); + is_pallet_index::(29); + is_pallet_index::(30); + is_pallet_index::(31); + is_pallet_index::(32); + is_pallet_index::(33); + is_pallet_index::(34); + is_pallet_index::(40); + is_pallet_index::(41); + is_pallet_index::(45); + is_pallet_index::(46); + is_pallet_index::(50); + + // Check removed pallets. + ExtBuilder::default().build().execute_with(|| { + use frame_support::metadata::{v14::META_RESERVED, RuntimeMetadata}; + + let runtime_metadata = calamari_runtime::Runtime::metadata(); + assert_eq!(runtime_metadata.0, META_RESERVED); + if let RuntimeMetadata::V14(v14) = runtime_metadata.1 { + // Ensure sudo=42 has been removed, no one is taking this index. + assert!(v14.pallets.iter().any(|pallet| pallet.index != 42)); + } + }); } #[test] fn concrete_fungible_ledger_transfers_work() { - let alice = get_account_id_from_seed::("Alice"); - let bob = get_account_id_from_seed::("Bob"); - let charlie = get_account_id_from_seed::("Charlie"); - - ExtBuilder::default() - .with_balances(vec![ - (alice.clone(), INITIAL_BALANCE), - (bob.clone(), INITIAL_BALANCE), - (charlie.clone(), INITIAL_BALANCE), - ]) - .build() - .execute_with(|| { - let transfer_amount = 10 * KMA; - let mut current_balance_alice = INITIAL_BALANCE; - let mut current_balance_charlie = INITIAL_BALANCE; - - // Transfer tests for native assets: - - // Try to transfer more than available - assert_err!( - CalamariConcreteFungibleLedger::transfer( - >::NativeAssetId::get(), - &alice.clone(), - &charlie.clone(), - INITIAL_BALANCE + 1, - ), - FungibleLedgerError::InvalidTransfer(DispatchError::Module(ModuleError { - index: ::PalletInfo::index::< - Balances, - >() - .unwrap() as u8, - error: 2, - message: Some("InsufficientBalance") - })) - ); - assert_eq!(Balances::free_balance(alice.clone()), current_balance_alice); - assert_eq!( - Balances::free_balance(charlie.clone()), - current_balance_charlie - ); - - // Try to transfer and go below existential deposit - assert_err!( - CalamariConcreteFungibleLedger::transfer( - >::NativeAssetId::get(), - &alice.clone(), - &charlie.clone(), - INITIAL_BALANCE, - ), - FungibleLedgerError::InvalidTransfer(DispatchError::Module(ModuleError { - index: ::PalletInfo::index::< - Balances, - >() - .unwrap() as u8, - error: 4, - message: Some("KeepAlive") - })) - ); - assert_eq!(Balances::free_balance(alice.clone()), current_balance_alice); - assert_eq!( - Balances::free_balance(charlie.clone()), - current_balance_charlie - ); - - // A normal transfer should work - assert_ok!(CalamariConcreteFungibleLedger::transfer( - >::NativeAssetId::get(), - &alice.clone(), - &charlie.clone(), - transfer_amount, - )); - current_balance_alice -= transfer_amount; - current_balance_charlie += transfer_amount; - assert_eq!(Balances::free_balance(alice.clone()), current_balance_alice); - assert_eq!( - Balances::free_balance(charlie.clone()), - current_balance_charlie - ); - - // Should not be able to create new account with lower than ED balance - let new_account = get_account_id_from_seed::("NewAccount"); - assert_err!( - CalamariConcreteFungibleLedger::transfer( - >::NativeAssetId::get(), - &alice.clone(), - &new_account.clone(), - NativeTokenExistentialDeposit::get() - 1, - ), - FungibleLedgerError::InvalidTransfer(DispatchError::Module(ModuleError { - index: ::PalletInfo::index::< - Balances, - >() - .unwrap() as u8, - error: 3, - message: Some("ExistentialDeposit") - })) - ); - - // Should be able to create new account with enough balance - assert_ok!(CalamariConcreteFungibleLedger::transfer( - >::NativeAssetId::get(), - &alice.clone(), - &new_account.clone(), - NativeTokenExistentialDeposit::get(), - )); - current_balance_alice -= NativeTokenExistentialDeposit::get(); - assert_eq!(Balances::free_balance(alice.clone()), current_balance_alice); - assert_eq!( - Balances::free_balance(new_account.clone()), - NativeTokenExistentialDeposit::get() - ); - - // Transfer all of your balance without dropping below ED should work - assert_ok!(CalamariConcreteFungibleLedger::transfer( - >::NativeAssetId::get(), - &bob.clone(), - &alice.clone(), - INITIAL_BALANCE - NativeTokenExistentialDeposit::get(), - )); - current_balance_alice += INITIAL_BALANCE - NativeTokenExistentialDeposit::get(); - assert_eq!(Balances::free_balance(alice.clone()), current_balance_alice); - assert_eq!( - Balances::free_balance(bob.clone()), - NativeTokenExistentialDeposit::get() - ); - - // Transfer tests for non-native assets: - - let min_balance = 10u128; - let asset_metadata = AssetRegistrarMetadata { - name: b"Kusama".to_vec(), - symbol: b"KSM".to_vec(), - decimals: 12, - min_balance: min_balance, - evm_address: None, - is_frozen: false, - is_sufficient: true, - }; - let source_location = - AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); - assert_ok!(AssetManager::register_asset( - root_origin(), - source_location.clone(), - asset_metadata.clone() - ),); - - // Register and mint for testing. - // TODO:: Switch to u128::MAX when we start using https://github.com/paritytech/substrate/pull/11241 - let amount = INITIAL_BALANCE; - assert_ok!(CalamariConcreteFungibleLedger::mint( - >::StartNonNativeAssetId::get(), - &alice.clone(), - amount, - ),); - assert_eq!( - Assets::balance( - >::StartNonNativeAssetId::get(), - alice.clone() - ), - amount - ); - - // Transferring and falling below ED of the asset should not work. - assert_err!( - CalamariConcreteFungibleLedger::transfer( - >::StartNonNativeAssetId::get(), - &alice.clone(), - &bob.clone(), - amount, - ), - FungibleLedgerError::InvalidTransfer(DispatchError::Module(ModuleError { - index: ::PalletInfo::index::< - Assets, - >() - .unwrap() as u8, - error: 0, - message: Some("BalanceLow") - })) - ); - assert_eq!( - Assets::balance( - >::StartNonNativeAssetId::get(), - alice.clone() - ), - amount - ); - - assert_err!( - CalamariConcreteFungibleLedger::transfer( - >::StartNonNativeAssetId::get(), - &alice.clone(), - &bob.clone(), - min_balance - 1, - ), - FungibleLedgerError::InvalidTransfer(DispatchError::Token( - sp_runtime::TokenError::BelowMinimum - )) - ); - assert_eq!( - Assets::balance( - >::StartNonNativeAssetId::get(), - alice.clone() - ), - amount - ); - - // Transferring normal amounts should work. - assert_ok!(CalamariConcreteFungibleLedger::transfer( - >::StartNonNativeAssetId::get(), - &alice.clone(), - &bob.clone(), - transfer_amount, - ),); - assert_eq!( - Assets::balance( - >::StartNonNativeAssetId::get(), - alice.clone() - ), - INITIAL_BALANCE - transfer_amount - ); - assert_eq!( - Assets::balance( - >::StartNonNativeAssetId::get(), - bob.clone() - ), - transfer_amount - ); - - // Transferring invalid asset ID should not work. - assert_err!( - CalamariConcreteFungibleLedger::transfer( - >::DummyAssetId::get(), - &alice.clone(), - &charlie.clone(), - transfer_amount, - ), - FungibleLedgerError::InvalidAssetId - ); - assert_eq!(Balances::free_balance(alice.clone()), current_balance_alice); - assert_eq!( - Balances::free_balance(charlie.clone()), - current_balance_charlie - ); - - // Transferring unregistered asset ID should not work. - assert_err!( - CalamariConcreteFungibleLedger::transfer( - u32::MAX, - &alice.clone(), - &charlie.clone(), - transfer_amount, - ), - FungibleLedgerError::InvalidTransfer(DispatchError::Module(ModuleError { - index: ::PalletInfo::index::< - Assets, - >() - .unwrap() as u8, - error: 3, - message: Some("Unknown") - })) - ); - }); + let alice = get_account_id_from_seed::("Alice"); + let bob = get_account_id_from_seed::("Bob"); + let charlie = get_account_id_from_seed::("Charlie"); + + ExtBuilder::default() + .with_balances(vec![ + (alice.clone(), INITIAL_BALANCE), + (bob.clone(), INITIAL_BALANCE), + (charlie.clone(), INITIAL_BALANCE), + ]) + .build() + .execute_with(|| { + let transfer_amount = 10 * KMA; + let mut current_balance_alice = INITIAL_BALANCE; + let mut current_balance_charlie = INITIAL_BALANCE; + + // Transfer tests for native assets: + + // Try to transfer more than available + assert_err!( + CalamariConcreteFungibleLedger::transfer( + >::NativeAssetId::get(), + &alice.clone(), + &charlie.clone(), + INITIAL_BALANCE + 1, + ), + FungibleLedgerError::InvalidTransfer(DispatchError::Module(ModuleError { + index: ::PalletInfo::index::< + Balances, + >() + .unwrap() as u8, + error: 2, + message: Some("InsufficientBalance") + })) + ); + assert_eq!(Balances::free_balance(alice.clone()), current_balance_alice); + assert_eq!( + Balances::free_balance(charlie.clone()), + current_balance_charlie + ); + + // Try to transfer and go below existential deposit + assert_err!( + CalamariConcreteFungibleLedger::transfer( + >::NativeAssetId::get(), + &alice.clone(), + &charlie.clone(), + INITIAL_BALANCE, + ), + FungibleLedgerError::InvalidTransfer(DispatchError::Module(ModuleError { + index: ::PalletInfo::index::< + Balances, + >() + .unwrap() as u8, + error: 4, + message: Some("KeepAlive") + })) + ); + assert_eq!(Balances::free_balance(alice.clone()), current_balance_alice); + assert_eq!( + Balances::free_balance(charlie.clone()), + current_balance_charlie + ); + + // A normal transfer should work + assert_ok!(CalamariConcreteFungibleLedger::transfer( + >::NativeAssetId::get(), + &alice.clone(), + &charlie.clone(), + transfer_amount, + )); + current_balance_alice -= transfer_amount; + current_balance_charlie += transfer_amount; + assert_eq!(Balances::free_balance(alice.clone()), current_balance_alice); + assert_eq!( + Balances::free_balance(charlie.clone()), + current_balance_charlie + ); + + // Should not be able to create new account with lower than ED balance + let new_account = get_account_id_from_seed::("NewAccount"); + assert_err!( + CalamariConcreteFungibleLedger::transfer( + >::NativeAssetId::get(), + &alice.clone(), + &new_account, + NativeTokenExistentialDeposit::get() - 1, + ), + FungibleLedgerError::InvalidTransfer(DispatchError::Module(ModuleError { + index: ::PalletInfo::index::< + Balances, + >() + .unwrap() as u8, + error: 3, + message: Some("ExistentialDeposit") + })) + ); + + // Should be able to create new account with enough balance + assert_ok!(CalamariConcreteFungibleLedger::transfer( + >::NativeAssetId::get(), + &alice.clone(), + &new_account, + NativeTokenExistentialDeposit::get(), + )); + current_balance_alice -= NativeTokenExistentialDeposit::get(); + assert_eq!(Balances::free_balance(alice.clone()), current_balance_alice); + assert_eq!( + Balances::free_balance(new_account), + NativeTokenExistentialDeposit::get() + ); + + // Transfer all of your balance without dropping below ED should work + assert_ok!(CalamariConcreteFungibleLedger::transfer( + >::NativeAssetId::get(), + &bob.clone(), + &alice.clone(), + INITIAL_BALANCE - NativeTokenExistentialDeposit::get(), + )); + current_balance_alice += INITIAL_BALANCE - NativeTokenExistentialDeposit::get(); + assert_eq!(Balances::free_balance(alice.clone()), current_balance_alice); + assert_eq!( + Balances::free_balance(bob.clone()), + NativeTokenExistentialDeposit::get() + ); + + // Transfer tests for non-native assets: + + let min_balance = 10u128; + let asset_metadata = AssetRegistrarMetadata { + name: b"Kusama".to_vec(), + symbol: b"KSM".to_vec(), + decimals: 12, + min_balance, + evm_address: None, + is_frozen: false, + is_sufficient: true, + }; + let source_location = + AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); + assert_ok!(AssetManager::register_asset( + root_origin(), + source_location, + asset_metadata + ),); + + // Register and mint for testing. + // TODO:: Switch to u128::MAX when we start using https://github.com/paritytech/substrate/pull/11241 + let amount = INITIAL_BALANCE; + assert_ok!(CalamariConcreteFungibleLedger::mint( + >::StartNonNativeAssetId::get(), + &alice.clone(), + amount, + ),); + assert_eq!( + Assets::balance( + >::StartNonNativeAssetId::get(), + alice.clone() + ), + amount + ); + + // Transferring and falling below ED of the asset should not work. + assert_err!( + CalamariConcreteFungibleLedger::transfer( + >::StartNonNativeAssetId::get(), + &alice.clone(), + &bob.clone(), + amount, + ), + FungibleLedgerError::InvalidTransfer(DispatchError::Module(ModuleError { + index: ::PalletInfo::index::< + Assets, + >() + .unwrap() as u8, + error: 0, + message: Some("BalanceLow") + })) + ); + assert_eq!( + Assets::balance( + >::StartNonNativeAssetId::get(), + alice.clone() + ), + amount + ); + + assert_err!( + CalamariConcreteFungibleLedger::transfer( + >::StartNonNativeAssetId::get(), + &alice.clone(), + &bob.clone(), + min_balance - 1, + ), + FungibleLedgerError::InvalidTransfer(DispatchError::Token( + sp_runtime::TokenError::BelowMinimum + )) + ); + assert_eq!( + Assets::balance( + >::StartNonNativeAssetId::get(), + alice.clone() + ), + amount + ); + + // Transferring normal amounts should work. + assert_ok!(CalamariConcreteFungibleLedger::transfer( + >::StartNonNativeAssetId::get(), + &alice.clone(), + &bob.clone(), + transfer_amount, + ),); + assert_eq!( + Assets::balance( + >::StartNonNativeAssetId::get(), + alice.clone() + ), + INITIAL_BALANCE - transfer_amount + ); + assert_eq!( + Assets::balance( + >::StartNonNativeAssetId::get(), + bob.clone() + ), + transfer_amount + ); + + // Transferring invalid asset ID should not work. + assert_err!( + CalamariConcreteFungibleLedger::transfer( + >::DummyAssetId::get(), + &alice.clone(), + &charlie.clone(), + transfer_amount, + ), + FungibleLedgerError::InvalidAssetId + ); + assert_eq!(Balances::free_balance(alice.clone()), current_balance_alice); + assert_eq!( + Balances::free_balance(charlie.clone()), + current_balance_charlie + ); + + // Transferring unregistered asset ID should not work. + assert_err!( + CalamariConcreteFungibleLedger::transfer( + u32::MAX, + &alice.clone(), + &charlie.clone(), + transfer_amount, + ), + FungibleLedgerError::InvalidTransfer(DispatchError::Module(ModuleError { + index: ::PalletInfo::index::< + Assets, + >() + .unwrap() as u8, + error: 3, + message: Some("Unknown") + })) + ); + }); } #[test] fn concrete_fungible_ledger_can_deposit_and_mint_works() { - let alice = get_account_id_from_seed::("Alice"); - - ExtBuilder::default() - .with_balances(vec![(alice.clone(), INITIAL_BALANCE)]) - .build() - .execute_with(|| { - // Native asset tests: - - let new_account = get_account_id_from_seed::("NewAccount"); - assert_err!( - CalamariConcreteFungibleLedger::can_deposit( - >::NativeAssetId::get(), - &new_account.clone(), - NativeTokenExistentialDeposit::get() - 1, - ), - FungibleLedgerError::BelowMinimum - ); - - let remaining_to_max = u128::MAX - Balances::total_issuance(); - assert_ok!(CalamariConcreteFungibleLedger::mint( - >::NativeAssetId::get(), - &new_account.clone(), - remaining_to_max, - ),); - assert_eq!( - Balances::free_balance(new_account.clone()), - remaining_to_max - ); - assert_err!( - CalamariConcreteFungibleLedger::can_deposit( - >::NativeAssetId::get(), - &new_account.clone(), - 1, - ), - FungibleLedgerError::Overflow - ); - - // Non-native asset tests: - - let min_balance = 10u128; - let asset_metadata = AssetRegistrarMetadata { - name: b"Kusama".to_vec(), - symbol: b"KSM".to_vec(), - decimals: 12, - min_balance: min_balance, - evm_address: None, - is_frozen: false, - is_sufficient: true, - }; - let source_location = - AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); - assert_ok!(AssetManager::register_asset( - root_origin(), - source_location.clone(), - asset_metadata.clone() - ),); - - assert_err!( - CalamariConcreteFungibleLedger::can_deposit( - >::StartNonNativeAssetId::get(), - &alice.clone(), - 0, - ), - FungibleLedgerError::BelowMinimum - ); - assert_err!( - CalamariConcreteFungibleLedger::can_deposit( - >::StartNonNativeAssetId::get() + 1, - &alice.clone(), - 11, - ), - FungibleLedgerError::UnknownAsset - ); - assert_ok!(CalamariConcreteFungibleLedger::mint( - >::StartNonNativeAssetId::get(), - &alice.clone(), - u128::MAX, - ),); - assert_eq!( - Assets::balance( - >::StartNonNativeAssetId::get(), - alice.clone() - ), - u128::MAX - ); - assert_err!( - CalamariConcreteFungibleLedger::can_deposit( - >::StartNonNativeAssetId::get(), - &alice.clone(), - 1, - ), - FungibleLedgerError::Overflow - ); - - let asset_metadata = AssetRegistrarMetadata { - name: b"Rococo".to_vec(), - symbol: b"Roc".to_vec(), - decimals: 12, - min_balance: min_balance, - evm_address: None, - is_frozen: false, - is_sufficient: false, - }; - - let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( - 1, - X2(Parachain(1), PalletInstance(1)), - ))); - assert_ok!(AssetManager::register_asset( - root_origin(), - source_location.clone(), - asset_metadata.clone() - ),); - assert_err!( - CalamariConcreteFungibleLedger::can_deposit( - >::StartNonNativeAssetId::get() + 1, - &XcmFeesAccount::get(), - 11, - ), - FungibleLedgerError::CannotCreate - ); - }); + let alice = get_account_id_from_seed::("Alice"); + + ExtBuilder::default() + .with_balances(vec![(alice.clone(), INITIAL_BALANCE)]) + .build() + .execute_with(|| { + // Native asset tests: + + let new_account = get_account_id_from_seed::("NewAccount"); + assert_err!( + CalamariConcreteFungibleLedger::can_deposit( + >::NativeAssetId::get(), + &new_account, + NativeTokenExistentialDeposit::get() - 1, + ), + FungibleLedgerError::BelowMinimum + ); + + let remaining_to_max = u128::MAX - Balances::total_issuance(); + assert_ok!(CalamariConcreteFungibleLedger::mint( + >::NativeAssetId::get(), + &new_account, + remaining_to_max, + ),); + assert_eq!( + Balances::free_balance(new_account.clone()), + remaining_to_max + ); + assert_err!( + CalamariConcreteFungibleLedger::can_deposit( + >::NativeAssetId::get(), + &new_account, + 1, + ), + FungibleLedgerError::Overflow + ); + + // Non-native asset tests: + + let min_balance = 10u128; + let asset_metadata = AssetRegistrarMetadata { + name: b"Kusama".to_vec(), + symbol: b"KSM".to_vec(), + decimals: 12, + min_balance, + evm_address: None, + is_frozen: false, + is_sufficient: true, + }; + let source_location = + AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); + assert_ok!(AssetManager::register_asset( + root_origin(), + source_location, + asset_metadata + ),); + + assert_err!( + CalamariConcreteFungibleLedger::can_deposit( + >::StartNonNativeAssetId::get(), + &alice.clone(), + 0, + ), + FungibleLedgerError::BelowMinimum + ); + assert_err!( + CalamariConcreteFungibleLedger::can_deposit( + >::StartNonNativeAssetId::get() + 1, + &alice.clone(), + 11, + ), + FungibleLedgerError::UnknownAsset + ); + assert_ok!(CalamariConcreteFungibleLedger::mint( + >::StartNonNativeAssetId::get(), + &alice.clone(), + u128::MAX, + ),); + assert_eq!( + Assets::balance( + >::StartNonNativeAssetId::get(), + alice.clone() + ), + u128::MAX + ); + assert_err!( + CalamariConcreteFungibleLedger::can_deposit( + >::StartNonNativeAssetId::get(), + &alice.clone(), + 1, + ), + FungibleLedgerError::Overflow + ); + + let asset_metadata = AssetRegistrarMetadata { + name: b"Rococo".to_vec(), + symbol: b"Roc".to_vec(), + decimals: 12, + min_balance, + evm_address: None, + is_frozen: false, + is_sufficient: false, + }; + + let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( + 1, + X2(Parachain(1), PalletInstance(1)), + ))); + assert_ok!(AssetManager::register_asset( + root_origin(), + source_location, + asset_metadata + ),); + assert_err!( + CalamariConcreteFungibleLedger::can_deposit( + >::StartNonNativeAssetId::get() + 1, + &XcmFeesAccount::get(), + 11, + ), + FungibleLedgerError::CannotCreate + ); + }); } #[test] fn concrete_fungible_ledger_can_withdraw_works() { - let alice = get_account_id_from_seed::("Alice"); - let bob = get_account_id_from_seed::("Bob"); - - ExtBuilder::default() - .with_balances(vec![(alice.clone(), INITIAL_BALANCE)]) - .build() - .execute_with(|| { - // Native asset tests: - - assert_err!( - CalamariConcreteFungibleLedger::can_withdraw( - >::NativeAssetId::get(), - &alice.clone(), - INITIAL_BALANCE + 1, - ), - FungibleLedgerError::Underflow - ); - - assert_err!( - CalamariConcreteFungibleLedger::can_withdraw( - >::NativeAssetId::get(), - &alice.clone(), - INITIAL_BALANCE, - ), - FungibleLedgerError::WouldDie - ); - - assert_err!( - CalamariConcreteFungibleLedger::can_withdraw( - >::NativeAssetId::get(), - &bob.clone(), - INITIAL_BALANCE, - ), - FungibleLedgerError::NoFunds - ); - - // Non-native asset tests: - - let min_balance = 10u128; - let asset_metadata = AssetRegistrarMetadata { - name: b"Kusama".to_vec(), - symbol: b"KSM".to_vec(), - decimals: 12, - min_balance: min_balance, - evm_address: None, - is_frozen: false, - is_sufficient: true, - }; - let source_location = - AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); - assert_ok!(AssetManager::register_asset( - root_origin(), - source_location.clone(), - asset_metadata.clone() - ),); - - assert_ok!(CalamariConcreteFungibleLedger::mint( - >::StartNonNativeAssetId::get(), - &alice.clone(), - INITIAL_BALANCE, - ),); - assert_eq!( - Assets::balance( - >::StartNonNativeAssetId::get(), - alice.clone() - ), - INITIAL_BALANCE - ); - - assert_err!( - CalamariConcreteFungibleLedger::can_withdraw( - >::StartNonNativeAssetId::get(), - &alice.clone(), - INITIAL_BALANCE + 1, - ), - FungibleLedgerError::Underflow - ); - - assert_err!( - CalamariConcreteFungibleLedger::can_withdraw( - >::StartNonNativeAssetId::get(), - &alice.clone(), - INITIAL_BALANCE, - ), - FungibleLedgerError::ReducedToZero(0) - ); - - assert_ok!(CalamariConcreteFungibleLedger::can_withdraw( - >::StartNonNativeAssetId::get(), - &alice.clone(), - INITIAL_BALANCE - min_balance, - ),); - - assert_err!( - CalamariConcreteFungibleLedger::can_withdraw( - >::StartNonNativeAssetId::get(), - &bob.clone(), - 10, - ), - FungibleLedgerError::NoFunds - ); - - assert_ok!(Assets::freeze( - Origin::signed(AssetManager::account_id()), - >::StartNonNativeAssetId::get(), - sp_runtime::MultiAddress::Id(alice.clone()), - )); - assert_err!( - CalamariConcreteFungibleLedger::can_withdraw( - >::StartNonNativeAssetId::get(), - &alice.clone(), - 10, - ), - FungibleLedgerError::Frozen - ); - }); + let alice = get_account_id_from_seed::("Alice"); + let bob = get_account_id_from_seed::("Bob"); + + ExtBuilder::default() + .with_balances(vec![(alice.clone(), INITIAL_BALANCE)]) + .build() + .execute_with(|| { + // Native asset tests: + + assert_err!( + CalamariConcreteFungibleLedger::can_withdraw( + >::NativeAssetId::get(), + &alice.clone(), + INITIAL_BALANCE + 1, + ), + FungibleLedgerError::Underflow + ); + + assert_err!( + CalamariConcreteFungibleLedger::can_withdraw( + >::NativeAssetId::get(), + &alice.clone(), + INITIAL_BALANCE, + ), + FungibleLedgerError::WouldDie + ); + + assert_err!( + CalamariConcreteFungibleLedger::can_withdraw( + >::NativeAssetId::get(), + &bob.clone(), + INITIAL_BALANCE, + ), + FungibleLedgerError::NoFunds + ); + + // Non-native asset tests: + + let min_balance = 10u128; + let asset_metadata = AssetRegistrarMetadata { + name: b"Kusama".to_vec(), + symbol: b"KSM".to_vec(), + decimals: 12, + min_balance, + evm_address: None, + is_frozen: false, + is_sufficient: true, + }; + let source_location = + AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); + assert_ok!(AssetManager::register_asset( + root_origin(), + source_location, + asset_metadata + ),); + + assert_ok!(CalamariConcreteFungibleLedger::mint( + >::StartNonNativeAssetId::get(), + &alice.clone(), + INITIAL_BALANCE, + ),); + assert_eq!( + Assets::balance( + >::StartNonNativeAssetId::get(), + alice.clone() + ), + INITIAL_BALANCE + ); + + assert_err!( + CalamariConcreteFungibleLedger::can_withdraw( + >::StartNonNativeAssetId::get(), + &alice.clone(), + INITIAL_BALANCE + 1, + ), + FungibleLedgerError::Underflow + ); + + assert_err!( + CalamariConcreteFungibleLedger::can_withdraw( + >::StartNonNativeAssetId::get(), + &alice.clone(), + INITIAL_BALANCE, + ), + FungibleLedgerError::ReducedToZero(0) + ); + + assert_ok!(CalamariConcreteFungibleLedger::can_withdraw( + >::StartNonNativeAssetId::get(), + &alice.clone(), + INITIAL_BALANCE - min_balance, + ),); + + assert_err!( + CalamariConcreteFungibleLedger::can_withdraw( + >::StartNonNativeAssetId::get(), + &bob.clone(), + 10, + ), + FungibleLedgerError::NoFunds + ); + + assert_ok!(Assets::freeze( + Origin::signed(AssetManager::account_id()), + >::StartNonNativeAssetId::get(), + sp_runtime::MultiAddress::Id(alice.clone()), + )); + assert_err!( + CalamariConcreteFungibleLedger::can_withdraw( + >::StartNonNativeAssetId::get(), + &alice.clone(), + 10, + ), + FungibleLedgerError::Frozen + ); + }); } diff --git a/runtime/common/Cargo.toml b/runtime/common/Cargo.toml index 0eebd875e..facf2b35e 100644 --- a/runtime/common/Cargo.toml +++ b/runtime/common/Cargo.toml @@ -1,56 +1,56 @@ [package] authors = ['Manta Network'] -name = "runtime-common" -version = '3.2.0' edition = "2021" homepage = 'https://manta.network' license = 'GPL-3.0' +name = "runtime-common" repository = 'https://github.com/Manta-Network/Manta/' +version = '3.2.0' [dependencies] [dev-dependencies] # 3rd dependencies codec = { package = "parity-scale-codec", version = "3.0" } -scale-info = { version = "2.0", features = [ "derive" ] } +scale-info = { version = "2.0", features = ["derive"] } # Substrate dependencies frame-support = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } frame-system = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } +pallet-assets = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } +pallet-balances = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } +pallet-utility = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sp-core = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } -sp-std = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sp-io = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } sp-runtime = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } -pallet-balances = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } -pallet-utility = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } -pallet-assets = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } +sp-std = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.18" } # Polkadot dependencies +pallet-xcm = { git = 'https://github.com/paritytech/polkadot.git', branch = "release-v0.9.18" } polkadot-core-primitives = { git = 'https://github.com/paritytech/polkadot.git', branch = "release-v0.9.18" } -polkadot-runtime-parachains = { git = 'https://github.com/paritytech/polkadot.git', branch = "release-v0.9.18" } polkadot-parachain = { git = 'https://github.com/paritytech/polkadot.git', branch = "release-v0.9.18" } -pallet-xcm = { git = 'https://github.com/paritytech/polkadot.git', branch = "release-v0.9.18" } +polkadot-runtime-parachains = { git = 'https://github.com/paritytech/polkadot.git', branch = "release-v0.9.18" } xcm = { git = 'https://github.com/paritytech/polkadot.git', branch = "release-v0.9.18" } -xcm-builder = { git = 'https://github.com/paritytech/polkadot.git', branch = "release-v0.9.18"} -xcm-executor = { git = 'https://github.com/paritytech/polkadot.git', branch = "release-v0.9.18"} -xcm-simulator = { git = 'https://github.com/paritytech/polkadot.git', branch = "release-v0.9.18"} +xcm-builder = { git = 'https://github.com/paritytech/polkadot.git', branch = "release-v0.9.18" } +xcm-executor = { git = 'https://github.com/paritytech/polkadot.git', branch = "release-v0.9.18" } +xcm-simulator = { git = 'https://github.com/paritytech/polkadot.git', branch = "release-v0.9.18" } # Cumulus dependencies -parachain-info = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } +cumulus-pallet-dmp-queue = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } +cumulus-pallet-parachain-system = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } cumulus-pallet-xcm = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } +cumulus-pallet-xcmp-queue = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } cumulus-primitives-parachain-inherent = { git = "https://github.com/paritytech/cumulus.git", branch = "polkadot-v0.9.18" } cumulus-test-relay-sproof-builder = { git = "https://github.com/paritytech/cumulus.git", branch = "polkadot-v0.9.18" } -cumulus-pallet-parachain-system = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } -cumulus-pallet-dmp-queue = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } -cumulus-pallet-xcmp-queue = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } +parachain-info = { git = 'https://github.com/paritytech/cumulus.git', branch = "polkadot-v0.9.18" } # Orml dependencies -orml-traits = { git = "https://github.com/manta-network/open-runtime-module-library.git", rev="7e2f985" } -orml-xtokens = { git = "https://github.com/manta-network/open-runtime-module-library.git", rev="7e2f985" } +orml-traits = { git = "https://github.com/manta-network/open-runtime-module-library.git", rev = "7e2f985" } +orml-xtokens = { git = "https://github.com/manta-network/open-runtime-module-library.git", rev = "7e2f985" } # Self dependencies -pallet-asset-manager = { path = '../../pallets/asset-manager' } manta-primitives = { path = '../../primitives' } +pallet-asset-manager = { path = '../../pallets/asset-manager' } [features] default = ["std"] diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs index 3cca9e8c1..7aaaaeab3 100644 --- a/runtime/common/src/lib.rs +++ b/runtime/common/src/lib.rs @@ -33,21 +33,21 @@ /// } #[macro_export] macro_rules! prod_or_fast { - ($prod:expr, $test:expr) => { - if cfg!(feature = "fast-runtime") { - $test - } else { - $prod - } - }; - ($prod:expr, $test:expr, $env:expr) => { - if cfg!(feature = "fast-runtime") { - core::option_env!($env) - .map(|s| s.parse().ok()) - .flatten() - .unwrap_or($test) - } else { - $prod - } - }; + ($prod:expr, $test:expr) => { + if cfg!(feature = "fast-runtime") { + $test + } else { + $prod + } + }; + ($prod:expr, $test:expr, $env:expr) => { + if cfg!(feature = "fast-runtime") { + core::option_env!($env) + .map(|s| s.parse().ok()) + .flatten() + .unwrap_or($test) + } else { + $prod + } + }; } diff --git a/runtime/common/tests/xcm_mock/mod.rs b/runtime/common/tests/xcm_mock/mod.rs index 5791e6089..b5472a0ce 100644 --- a/runtime/common/tests/xcm_mock/mod.rs +++ b/runtime/common/tests/xcm_mock/mod.rs @@ -25,104 +25,104 @@ pub const ALICE: sp_runtime::AccountId32 = sp_runtime::AccountId32::new([0u8; 32 pub const INITIAL_BALANCE: u128 = 10_000_000_000_000_000; decl_test_parachain! { - pub struct ParaA { - Runtime = parachain::Runtime, - XcmpMessageHandler = parachain::XcmpQueue, - DmpMessageHandler = parachain::MsgQueue, - new_ext = para_ext(1), - } + pub struct ParaA { + Runtime = parachain::Runtime, + XcmpMessageHandler = parachain::XcmpQueue, + DmpMessageHandler = parachain::MsgQueue, + new_ext = para_ext(1), + } } decl_test_parachain! { - pub struct ParaB { - Runtime = parachain::Runtime, - XcmpMessageHandler = parachain::XcmpQueue, - DmpMessageHandler = parachain::MsgQueue, - new_ext = para_ext(2), - } + pub struct ParaB { + Runtime = parachain::Runtime, + XcmpMessageHandler = parachain::XcmpQueue, + DmpMessageHandler = parachain::MsgQueue, + new_ext = para_ext(2), + } } decl_test_parachain! { - pub struct ParaC { - Runtime = parachain::Runtime, - XcmpMessageHandler = parachain::XcmpQueue, - DmpMessageHandler = parachain::MsgQueue, - new_ext = para_ext(3), - } + pub struct ParaC { + Runtime = parachain::Runtime, + XcmpMessageHandler = parachain::XcmpQueue, + DmpMessageHandler = parachain::MsgQueue, + new_ext = para_ext(3), + } } decl_test_relay_chain! { - pub struct Relay { - Runtime = relay_chain::Runtime, - XcmConfig = relay_chain::XcmExecutorConfig, - new_ext = relay_ext(), - } + pub struct Relay { + Runtime = relay_chain::Runtime, + XcmConfig = relay_chain::XcmExecutorConfig, + new_ext = relay_ext(), + } } decl_test_network! { - pub struct MockNet { - relay_chain = Relay, - parachains = vec![ - (1, ParaA), - (2, ParaB), - (3, ParaC), - ], - } + pub struct MockNet { + relay_chain = Relay, + parachains = vec![ + (1, ParaA), + (2, ParaB), + (3, ParaC), + ], + } } pub fn para_account_id(id: u32) -> relay_chain::AccountId { - ParaId::from(id).into_account() + ParaId::from(id).into_account() } 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)], - } - .assimilate_storage(&mut t) - .unwrap(); - - let parachain_info_config = parachain_info::GenesisConfig { - parachain_id: para_id.into(), - }; - >::assimilate_storage( - ¶chain_info_config, - &mut t, - ) - .unwrap(); - - let mut ext = sp_io::TestExternalities::new(t); - ext.execute_with(|| { - System::set_block_number(1); - MsgQueue::set_para_id(para_id.into()); - }); - ext + use parachain::{MsgQueue, Runtime, System}; + + let mut t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); + + pallet_balances::GenesisConfig:: { + balances: vec![(ALICE, INITIAL_BALANCE)], + } + .assimilate_storage(&mut t) + .unwrap(); + + let parachain_info_config = parachain_info::GenesisConfig { + parachain_id: para_id.into(), + }; + >::assimilate_storage( + ¶chain_info_config, + &mut t, + ) + .unwrap(); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| { + 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), - (para_account_id(1), INITIAL_BALANCE), - ], - } - .assimilate_storage(&mut t) - .unwrap(); - - let mut ext = sp_io::TestExternalities::new(t); - ext.execute_with(|| System::set_block_number(1)); - ext + use relay_chain::{Runtime, System}; + + let mut t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); + + pallet_balances::GenesisConfig:: { + balances: vec![ + (ALICE, INITIAL_BALANCE), + (para_account_id(1), 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 RelayChainPalletXcm = pallet_xcm::Pallet; diff --git a/runtime/common/tests/xcm_mock/parachain.rs b/runtime/common/tests/xcm_mock/parachain.rs index b81ad029d..5a93db670 100644 --- a/runtime/common/tests/xcm_mock/parachain.rs +++ b/runtime/common/tests/xcm_mock/parachain.rs @@ -18,145 +18,145 @@ use codec::{Decode, Encode}; use frame_support::{ - assert_ok, construct_runtime, parameter_types, - traits::{ConstU32, Everything, Nothing}, - weights::{constants::WEIGHT_PER_SECOND, Weight}, - PalletId, + assert_ok, construct_runtime, parameter_types, + traits::{ConstU32, Everything, Nothing}, + weights::{constants::WEIGHT_PER_SECOND, Weight}, + PalletId, }; use frame_system::EnsureRoot; use scale_info::TypeInfo; use sp_core::{H160, H256}; use sp_runtime::{ - testing::Header, - traits::{Hash, IdentityLookup}, - AccountId32, + testing::Header, + traits::{Hash, IdentityLookup}, + AccountId32, }; use sp_std::prelude::*; use pallet_xcm::XcmPassthrough; use polkadot_core_primitives::BlockNumber as RelayBlockNumber; use polkadot_parachain::primitives::{ - DmpMessageHandler, Id as ParaId, Sibling, XcmpMessageFormat, XcmpMessageHandler, + DmpMessageHandler, Id as ParaId, Sibling, XcmpMessageFormat, XcmpMessageHandler, }; use xcm::{latest::prelude::*, Version as XcmVersion, VersionedMultiLocation, VersionedXcm}; use xcm_builder::{ - AccountId32Aliases, AllowUnpaidExecutionFrom, ConvertedConcreteAssetId, - CurrencyAdapter as XcmCurrencyAdapter, EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, - FungiblesAdapter, LocationInverter, ParentIsPreset, SiblingParachainAsNative, - SiblingParachainConvertsVia, SignedAccountId32AsNative, SovereignSignedViaLocation, + AccountId32Aliases, AllowUnpaidExecutionFrom, ConvertedConcreteAssetId, + CurrencyAdapter as XcmCurrencyAdapter, EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, + FungiblesAdapter, LocationInverter, ParentIsPreset, SiblingParachainAsNative, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SovereignSignedViaLocation, }; use xcm_executor::{traits::JustTry, Config, XcmExecutor}; use xcm_simulator::{DmpMessageHandlerT, Get, TestExt, XcmpMessageHandlerT}; use manta_primitives::{ - assets::{ - AssetConfig, AssetIdLocationConvert, AssetLocation, AssetRegistrar, AssetRegistrarMetadata, - AssetStorageMetadata, ConcreteFungibleLedger, - }, - constants::{ASSET_MANAGER_PALLET_ID, CALAMARI_DECIMAL}, - types::AssetId, - xcm::{FirstAssetTrader, IsNativeConcrete, MultiNativeAsset}, + assets::{ + AssetConfig, AssetIdLocationConvert, AssetLocation, AssetRegistrar, AssetRegistrarMetadata, + AssetStorageMetadata, ConcreteFungibleLedger, + }, + constants::{ASSET_MANAGER_PALLET_ID, CALAMARI_DECIMAL}, + types::AssetId, + xcm::{FirstAssetTrader, IsNativeConcrete, MultiNativeAsset}, }; pub type AccountId = AccountId32; pub type Balance = u128; parameter_types! { - pub const BlockHashCount: u64 = 250; + pub const BlockHashCount: u64 = 250; } impl frame_system::Config for Runtime { - type Origin = Origin; - type Call = Call; - type Index = u64; - type BlockNumber = u64; - type Hash = H256; - type Hashing = ::sp_runtime::traits::BlakeTwo256; - type AccountId = AccountId; - type Lookup = IdentityLookup; - type Header = Header; - type Event = Event; - type BlockHashCount = BlockHashCount; - 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 = cumulus_pallet_parachain_system::ParachainSetCode; - type MaxConsumers = ConstU32<16>; + type Origin = Origin; + type Call = Call; + type Index = u64; + type BlockNumber = u64; + type Hash = H256; + type Hashing = ::sp_runtime::traits::BlakeTwo256; + type AccountId = AccountId; + type Lookup = IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = BlockHashCount; + 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 = cumulus_pallet_parachain_system::ParachainSetCode; + type MaxConsumers = ConstU32<16>; } parameter_types! { - pub ExistentialDeposit: Balance = 1; - pub const MaxLocks: u32 = 50; - pub const MaxReserves: u32 = 50; + 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 Event = Event; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; - type WeightInfo = (); - type MaxReserves = MaxReserves; - type ReserveIdentifier = [u8; 8]; + type MaxLocks = MaxLocks; + type Balance = Balance; + type Event = Event; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = (); + type MaxReserves = MaxReserves; + type ReserveIdentifier = [u8; 8]; } parameter_types! { - pub const ReservedXcmpWeight: Weight = WEIGHT_PER_SECOND / 4; - pub const ReservedDmpWeight: Weight = WEIGHT_PER_SECOND / 4; + pub const ReservedXcmpWeight: Weight = WEIGHT_PER_SECOND / 4; + pub const ReservedDmpWeight: Weight = WEIGHT_PER_SECOND / 4; } parameter_types! { - pub const KsmLocation: MultiLocation = MultiLocation::parent(); - pub const RelayNetwork: NetworkId = NetworkId::Kusama; - pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into(); - pub SelfReserve: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::parachain_id().into()))); - pub CheckingAccount: AccountId = PolkadotXcm::check_account(); + pub const KsmLocation: MultiLocation = MultiLocation::parent(); + pub const RelayNetwork: NetworkId = NetworkId::Kusama; + pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into(); + pub SelfReserve: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::parachain_id().into()))); + pub CheckingAccount: AccountId = PolkadotXcm::check_account(); } parameter_types! { - pub const AssetDeposit: Balance = 0; // Does not really matter as this will be only called by root - pub const AssetAccountDeposit: Balance = 0; - pub const ApprovalDeposit: Balance = 0; - pub const AssetsStringLimit: u32 = 50; - pub const MetadataDepositBase: Balance = 0; - pub const MetadataDepositPerByte: Balance = 0; + pub const AssetDeposit: Balance = 0; // Does not really matter as this will be only called by root + pub const AssetAccountDeposit: Balance = 0; + pub const ApprovalDeposit: Balance = 0; + pub const AssetsStringLimit: u32 = 50; + pub const MetadataDepositBase: Balance = 0; + pub const MetadataDepositPerByte: Balance = 0; } impl pallet_assets::Config for Runtime { - type Event = Event; - type Balance = Balance; - type AssetId = AssetId; - type Currency = Balances; - type ForceOrigin = EnsureRoot; - type AssetDeposit = AssetDeposit; - type AssetAccountDeposit = AssetAccountDeposit; - type MetadataDepositBase = MetadataDepositBase; - type MetadataDepositPerByte = MetadataDepositPerByte; - type ApprovalDeposit = ApprovalDeposit; - type StringLimit = AssetsStringLimit; - type Freezer = (); - type Extra = (); - type WeightInfo = pallet_assets::weights::SubstrateWeight; + type Event = Event; + type Balance = Balance; + type AssetId = AssetId; + type Currency = Balances; + type ForceOrigin = EnsureRoot; + type AssetDeposit = AssetDeposit; + type AssetAccountDeposit = AssetAccountDeposit; + type MetadataDepositBase = MetadataDepositBase; + type MetadataDepositPerByte = MetadataDepositPerByte; + type ApprovalDeposit = ApprovalDeposit; + type StringLimit = AssetsStringLimit; + type Freezer = (); + type Extra = (); + type WeightInfo = pallet_assets::weights::SubstrateWeight; } /// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used /// when determining ownership of accounts for asset transacting and when attempting to use XCM /// `Transact` in order to determine the dispatch Origin. pub type LocationToAccountId = ( - // The parent (Relay-chain) origin converts to the default `AccountId`. - ParentIsPreset, - // Sibling parachain origins convert to AccountId via the `ParaId::into`. - SiblingParachainConvertsVia, - AccountId32Aliases, + // The parent (Relay-chain) origin converts to the default `AccountId`. + ParentIsPreset, + // Sibling parachain origins convert to AccountId via the `ParaId::into`. + SiblingParachainConvertsVia, + AccountId32Aliases, ); /// This is the type to convert an (incoming) XCM origin into a local `Origin` instance, @@ -164,439 +164,439 @@ pub type LocationToAccountId = ( /// It uses some Rust magic macro to do the pattern matching sequentially. /// There is an `OriginKind` which can biases the kind of local `Origin` it will become. pub type XcmOriginToCallOrigin = ( - // Sovereign account converter; this attempts to derive an `AccountId` from the origin location - // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for - // foreign chains who want to have a local sovereign account on this chain which they control. - SovereignSignedViaLocation, - // If the incoming XCM origin is of type `AccountId32` and the Network is Network::Any - // or `RelayNetwork`, convert it to a Native 32 byte account. - SignedAccountId32AsNative, - // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when - // recognised. - SiblingParachainAsNative, - // Xcm origins can be represented natively under the Xcm pallet's Xcm origin. - XcmPassthrough, + // Sovereign account converter; this attempts to derive an `AccountId` from the origin location + // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for + // foreign chains who want to have a local sovereign account on this chain which they control. + SovereignSignedViaLocation, + // If the incoming XCM origin is of type `AccountId32` and the Network is Network::Any + // or `RelayNetwork`, convert it to a Native 32 byte account. + SignedAccountId32AsNative, + // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when + // recognised. + SiblingParachainAsNative, + // Xcm origins can be represented natively under the Xcm pallet's Xcm origin. + XcmPassthrough, ); parameter_types! { - pub const UnitWeightCost: Weight = 1_000_000_000; - // Used in native traders - // This might be able to skipped. - // We have to use `here()` because of reanchoring logic - pub ParaTokenPerSecond: (xcm::v2::AssetId, u128) = (Concrete(MultiLocation::here()), 1_000_000_000); - pub const MaxInstructions: u32 = 100; + pub const UnitWeightCost: Weight = 1_000_000_000; + // Used in native traders + // This might be able to skipped. + // We have to use `here()` because of reanchoring logic + pub ParaTokenPerSecond: (xcm::v2::AssetId, u128) = (Concrete(MultiLocation::here()), 1_000_000_000); + pub const MaxInstructions: u32 = 100; } /// Transactor for native currency, i.e. implements `fungible` trait pub type LocalAssetTransactor = XcmCurrencyAdapter< - // Transacting native currency, i.e. MANTA, KMA, DOL - Balances, - IsNativeConcrete, - LocationToAccountId, - AccountId, - (), + // Transacting native currency, i.e. MANTA, KMA, DOL + Balances, + IsNativeConcrete, + LocationToAccountId, + AccountId, + (), >; /// Transactor for currency in pallet-assets, i.e. implements `fungibles` trait pub type FungiblesTransactor = FungiblesAdapter< - Assets, - ConvertedConcreteAssetId< - AssetId, - Balance, - AssetIdLocationConvert, - JustTry, - >, - // "default" implementation of converting a `MultiLocation` to an `AccountId` - LocationToAccountId, - AccountId, - // No teleport support. - Nothing, - // No teleport tracking. - CheckingAccount, + Assets, + ConvertedConcreteAssetId< + AssetId, + Balance, + AssetIdLocationConvert, + JustTry, + >, + // "default" implementation of converting a `MultiLocation` to an `AccountId` + LocationToAccountId, + AccountId, + // No teleport support. + Nothing, + // No teleport tracking. + CheckingAccount, >; pub type XcmRouter = super::ParachainXcmRouter; pub type Barrier = AllowUnpaidExecutionFrom; parameter_types! { - /// Xcm fees will go to the asset manager (we don't implement treasury yet) - pub XcmFeesAccount: AccountId = AssetManager::account_id(); + /// Xcm fees will go to the asset manager (we don't implement treasury yet) + pub XcmFeesAccount: AccountId = AssetManager::account_id(); } pub type XcmFeesToAccount = manta_primitives::xcm::XcmFeesToAccount< - Assets, - ConvertedConcreteAssetId< - AssetId, - Balance, - AssetIdLocationConvert, - JustTry, - >, - AccountId, - XcmFeesAccount, + Assets, + ConvertedConcreteAssetId< + AssetId, + Balance, + AssetIdLocationConvert, + JustTry, + >, + AccountId, + XcmFeesAccount, >; pub struct XcmExecutorConfig; impl Config for XcmExecutorConfig { - type Call = Call; - type XcmSender = XcmRouter; - // Defines how to Withdraw and Deposit instruction work - // Under the hood, substrate framework will do pattern matching in macro, - // as a result, the order of the following tuple matters. - type AssetTransactor = (LocalAssetTransactor, FungiblesTransactor); - type OriginConverter = XcmOriginToCallOrigin; - // Combinations of (Location, Asset) pairs which we trust as reserves. - type IsReserve = MultiNativeAsset; - type IsTeleporter = (); - type LocationInverter = LocationInverter; - type Barrier = Barrier; - type Weigher = FixedWeightBounds; - // Trader is the means to purchasing weight credit for XCM execution. - // We define two traders: - // The first one will charge parachain's native currency, who's `MultiLocation` - // is defined in `SelfReserve`. - // The second one will charge the first asset in the MultiAssets with pre-defined rate - // i.e. units_per_second in `AssetManager` - type Trader = ( - FixedRateOfFungible, - FirstAssetTrader, - ); - type ResponseHandler = PolkadotXcm; - type AssetTrap = PolkadotXcm; - type AssetClaims = PolkadotXcm; - // This is needed for the version change notifier work - type SubscriptionService = PolkadotXcm; + type Call = Call; + type XcmSender = XcmRouter; + // Defines how to Withdraw and Deposit instruction work + // Under the hood, substrate framework will do pattern matching in macro, + // as a result, the order of the following tuple matters. + type AssetTransactor = (LocalAssetTransactor, FungiblesTransactor); + type OriginConverter = XcmOriginToCallOrigin; + // Combinations of (Location, Asset) pairs which we trust as reserves. + type IsReserve = MultiNativeAsset; + type IsTeleporter = (); + type LocationInverter = LocationInverter; + type Barrier = Barrier; + type Weigher = FixedWeightBounds; + // Trader is the means to purchasing weight credit for XCM execution. + // We define two traders: + // The first one will charge parachain's native currency, who's `MultiLocation` + // is defined in `SelfReserve`. + // The second one will charge the first asset in the MultiAssets with pre-defined rate + // i.e. units_per_second in `AssetManager` + type Trader = ( + FixedRateOfFungible, + FirstAssetTrader, + ); + type ResponseHandler = PolkadotXcm; + type AssetTrap = PolkadotXcm; + type AssetClaims = PolkadotXcm; + // This is needed for the version change notifier work + type SubscriptionService = PolkadotXcm; } impl cumulus_pallet_xcmp_queue::Config for Runtime { - type Event = Event; - type XcmExecutor = XcmExecutor; - type ChannelInfo = ParachainSystem; - type VersionWrapper = PolkadotXcm; - type ExecuteOverweightOrigin = EnsureRoot; - type ControllerOrigin = EnsureRoot; - type ControllerOriginConverter = XcmOriginToCallOrigin; - type WeightInfo = (); + type Event = Event; + type XcmExecutor = XcmExecutor; + type ChannelInfo = ParachainSystem; + type VersionWrapper = PolkadotXcm; + type ExecuteOverweightOrigin = EnsureRoot; + type ControllerOrigin = EnsureRoot; + type ControllerOriginConverter = XcmOriginToCallOrigin; + type WeightInfo = (); } #[frame_support::pallet] pub mod mock_msg_queue { - use super::*; - use frame_support::pallet_prelude::*; - - #[pallet::config] - pub trait Config: frame_system::Config { - type Event: From> + IsType<::Event>; - type XcmExecutor: ExecuteXcm; - } - - #[pallet::call] - impl Pallet {} - - // without storage info is a work around - #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] - pub struct Pallet(_); - - #[pallet::storage] - #[pallet::getter(fn parachain_id)] - pub(super) type ParachainId = StorageValue<_, ParaId, ValueQuery>; - - #[pallet::storage] - #[pallet::getter(fn received_dmp)] - /// A queue of received DMP messages - pub(super) type ReceivedDmp = StorageValue<_, Vec>, ValueQuery>; - - impl Get for Pallet { - fn get() -> ParaId { - Self::parachain_id() - } - } - - pub type MessageId = [u8; 32]; - - #[pallet::event] - #[pallet::generate_deposit(pub(super) fn deposit_event)] - pub enum Event { - // XCMP - /// 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); - } - - 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 (result, event) = match Xcm::::try_from(xcm) { - Ok(xcm) => { - let location = (1, Parachain(sender.into())); - match T::XcmExecutor::execute_xcm(location, xcm, max_weight) { - Outcome::Error(e) => (Err(e.clone()), Event::Fail(Some(hash), e)), - Outcome::Complete(w) => (Ok(w), 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(w, e) => (Ok(w), Event::Fail(Some(hash), e)), - } - } - 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 id = sp_io::hashing::blake2_256(&data[..]); - let maybe_msg = - VersionedXcm::::decode(&mut &data[..]).map(Xcm::::try_from); - match maybe_msg { - Err(_) => { - Self::deposit_event(Event::InvalidFormat(id)); - } - Ok(Err(())) => { - Self::deposit_event(Event::UnsupportedVersion(id)); - } - Ok(Ok(x)) => { - let outcome = T::XcmExecutor::execute_xcm(Parent, x.clone(), limit); - >::append(x); - Self::deposit_event(Event::ExecutedDownward(id, outcome)); - } - } - } - limit - } - } + use super::*; + use frame_support::pallet_prelude::*; + + #[pallet::config] + pub trait Config: frame_system::Config { + type Event: From> + IsType<::Event>; + type XcmExecutor: ExecuteXcm; + } + + #[pallet::call] + impl Pallet {} + + // without storage info is a work around + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + #[pallet::without_storage_info] + pub struct Pallet(_); + + #[pallet::storage] + #[pallet::getter(fn parachain_id)] + pub(super) type ParachainId = StorageValue<_, ParaId, ValueQuery>; + + #[pallet::storage] + #[pallet::getter(fn received_dmp)] + /// A queue of received DMP messages + pub(super) type ReceivedDmp = StorageValue<_, Vec>, ValueQuery>; + + impl Get for Pallet { + fn get() -> ParaId { + Self::parachain_id() + } + } + + pub type MessageId = [u8; 32]; + + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { + // XCMP + /// 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); + } + + 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 (result, event) = match Xcm::::try_from(xcm) { + Ok(xcm) => { + let location = (1, Parachain(sender.into())); + match T::XcmExecutor::execute_xcm(location, xcm, max_weight) { + Outcome::Error(e) => (Err(e), Event::Fail(Some(hash), e)), + Outcome::Complete(w) => (Ok(w), 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(w, e) => (Ok(w), Event::Fail(Some(hash), e)), + } + } + 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 id = sp_io::hashing::blake2_256(&data[..]); + let maybe_msg = + VersionedXcm::::decode(&mut &data[..]).map(Xcm::::try_from); + match maybe_msg { + Err(_) => { + Self::deposit_event(Event::InvalidFormat(id)); + } + Ok(Err(())) => { + Self::deposit_event(Event::UnsupportedVersion(id)); + } + Ok(Ok(x)) => { + let outcome = T::XcmExecutor::execute_xcm(Parent, x.clone(), limit); + >::append(x); + Self::deposit_event(Event::ExecutedDownward(id, outcome)); + } + } + } + limit + } + } } impl mock_msg_queue::Config for Runtime { - type Event = Event; - type XcmExecutor = XcmExecutor; + type Event = Event; + type XcmExecutor = XcmExecutor; } impl cumulus_pallet_parachain_system::Config for Runtime { - type Event = Event; - type SelfParaId = parachain_info::Pallet; - type DmpMessageHandler = MsgQueue; - type ReservedDmpWeight = ReservedDmpWeight; - type OutboundXcmpMessageSource = XcmpQueue; - type XcmpMessageHandler = XcmpQueue; - type ReservedXcmpWeight = ReservedXcmpWeight; - type OnSystemEvent = (); + type Event = Event; + type SelfParaId = parachain_info::Pallet; + type DmpMessageHandler = MsgQueue; + type ReservedDmpWeight = ReservedDmpWeight; + type OutboundXcmpMessageSource = XcmpQueue; + type XcmpMessageHandler = XcmpQueue; + type ReservedXcmpWeight = ReservedXcmpWeight; + type OnSystemEvent = (); } pub type LocalOriginToLocation = (); impl pallet_xcm::Config for Runtime { - type Event = Event; - type SendXcmOrigin = EnsureXcmOrigin; - type XcmRouter = XcmRouter; - type ExecuteXcmOrigin = EnsureXcmOrigin; - type XcmExecuteFilter = Nothing; - type XcmExecutor = XcmExecutor; - // Do not allow teleports - type XcmTeleportFilter = Nothing; - type XcmReserveTransferFilter = Nothing; - type Weigher = FixedWeightBounds; - type LocationInverter = LocationInverter; - type Origin = Origin; - type Call = Call; - const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; - type AdvertisedXcmVersion = CurrentXcmVersion; + type Event = Event; + type SendXcmOrigin = EnsureXcmOrigin; + type XcmRouter = XcmRouter; + type ExecuteXcmOrigin = EnsureXcmOrigin; + type XcmExecuteFilter = Nothing; + type XcmExecutor = XcmExecutor; + // Do not allow teleports + type XcmTeleportFilter = Nothing; + type XcmReserveTransferFilter = Nothing; + type Weigher = FixedWeightBounds; + type LocationInverter = LocationInverter; + type Origin = Origin; + type Call = Call; + const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; + type AdvertisedXcmVersion = CurrentXcmVersion; } parameter_types! { - /// An implementation of `Get` which just returns the latest XCM version which we can - /// support. - pub static CurrentXcmVersion: u32 = 0; + /// An implementation of `Get` which just returns the latest XCM version which we can + /// support. + pub static CurrentXcmVersion: u32 = 0; } pub(crate) fn set_current_xcm_version(version: XcmVersion) { - CurrentXcmVersion::set(version); + CurrentXcmVersion::set(version); } pub struct CalamariAssetRegistrar; use frame_support::pallet_prelude::DispatchResult; impl AssetRegistrar for CalamariAssetRegistrar { - fn create_asset( - asset_id: AssetId, - min_balance: Balance, - metadata: AssetStorageMetadata, - is_sufficient: bool, - ) -> DispatchResult { - Assets::force_create( - Origin::root(), - asset_id, - AssetManager::account_id(), - is_sufficient, - min_balance, - )?; - - Assets::force_set_metadata( - Origin::root(), - asset_id, - metadata.name, - metadata.symbol, - metadata.decimals, - metadata.is_frozen, - ) - } - - fn update_asset_metadata(asset_id: AssetId, metadata: AssetStorageMetadata) -> DispatchResult { - Assets::force_set_metadata( - Origin::root(), - asset_id, - metadata.name, - metadata.symbol, - metadata.decimals, - metadata.is_frozen, - ) - } + fn create_asset( + asset_id: AssetId, + min_balance: Balance, + metadata: AssetStorageMetadata, + is_sufficient: bool, + ) -> DispatchResult { + Assets::force_create( + Origin::root(), + asset_id, + AssetManager::account_id(), + is_sufficient, + min_balance, + )?; + + Assets::force_set_metadata( + Origin::root(), + asset_id, + metadata.name, + metadata.symbol, + metadata.decimals, + metadata.is_frozen, + ) + } + + fn update_asset_metadata(asset_id: AssetId, metadata: AssetStorageMetadata) -> DispatchResult { + Assets::force_set_metadata( + Origin::root(), + asset_id, + metadata.name, + metadata.symbol, + metadata.decimals, + metadata.is_frozen, + ) + } } parameter_types! { - pub const DummyAssetId: AssetId = 0; - pub const NativeAssetId: AssetId = 1; - pub const StartNonNativeAssetId: AssetId = 8; - pub NativeAssetLocation: AssetLocation = AssetLocation( - VersionedMultiLocation::V1(SelfReserve::get())); - pub NativeAssetMetadata: AssetRegistrarMetadata = AssetRegistrarMetadata { - name: b"Calamari".to_vec(), - symbol: b"KMA".to_vec(), - decimals: CALAMARI_DECIMAL, - min_balance: 1, - evm_address: None, - is_frozen: false, - is_sufficient: true, - }; - pub const AssetManagerPalletId: PalletId = ASSET_MANAGER_PALLET_ID; + pub const DummyAssetId: AssetId = 0; + pub const NativeAssetId: AssetId = 1; + pub const StartNonNativeAssetId: AssetId = 8; + pub NativeAssetLocation: AssetLocation = AssetLocation( + VersionedMultiLocation::V1(SelfReserve::get())); + pub NativeAssetMetadata: AssetRegistrarMetadata = AssetRegistrarMetadata { + name: b"Calamari".to_vec(), + symbol: b"KMA".to_vec(), + decimals: CALAMARI_DECIMAL, + min_balance: 1, + evm_address: None, + is_frozen: false, + is_sufficient: true, + }; + pub const AssetManagerPalletId: PalletId = ASSET_MANAGER_PALLET_ID; } #[derive(Clone, Eq, PartialEq)] pub struct CalamariAssetConfig; impl AssetConfig for CalamariAssetConfig { - type DummyAssetId = DummyAssetId; - type NativeAssetId = NativeAssetId; - type StartNonNativeAssetId = StartNonNativeAssetId; - type AssetRegistrarMetadata = AssetRegistrarMetadata; - type NativeAssetLocation = NativeAssetLocation; - type NativeAssetMetadata = NativeAssetMetadata; - type StorageMetadata = AssetStorageMetadata; - type AssetLocation = AssetLocation; - type AssetRegistrar = CalamariAssetRegistrar; - type FungibleLedger = ConcreteFungibleLedger; + type DummyAssetId = DummyAssetId; + type NativeAssetId = NativeAssetId; + type StartNonNativeAssetId = StartNonNativeAssetId; + type AssetRegistrarMetadata = AssetRegistrarMetadata; + type NativeAssetLocation = NativeAssetLocation; + type NativeAssetMetadata = NativeAssetMetadata; + type StorageMetadata = AssetStorageMetadata; + type AssetLocation = AssetLocation; + type AssetRegistrar = CalamariAssetRegistrar; + type FungibleLedger = ConcreteFungibleLedger; } impl pallet_asset_manager::Config for Runtime { - type Event = Event; - type AssetConfig = CalamariAssetConfig; - type ModifierOrigin = EnsureRoot; - type PalletId = AssetManagerPalletId; - type WeightInfo = (); + type Event = Event; + type AssetConfig = CalamariAssetConfig; + type ModifierOrigin = EnsureRoot; + type PalletId = AssetManagerPalletId; + type WeightInfo = (); } impl cumulus_pallet_xcm::Config for Runtime { - type Event = Event; - type XcmExecutor = XcmExecutor; + type Event = Event; + type XcmExecutor = XcmExecutor; } // We wrap AssetId for XToken #[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)] pub enum CurrencyId { - MantaCurrency(AssetId), + MantaCurrency(AssetId), } pub struct CurrencyIdtoMultiLocation(sp_std::marker::PhantomData); impl sp_runtime::traits::Convert> - for CurrencyIdtoMultiLocation + for CurrencyIdtoMultiLocation where - AssetXConverter: xcm_executor::traits::Convert, + AssetXConverter: xcm_executor::traits::Convert, { - fn convert(currency: CurrencyId) -> Option { - match currency { - CurrencyId::MantaCurrency(asset_id) => match AssetXConverter::reverse_ref(&asset_id) { - Ok(location) => Some(location), - Err(_) => None, - }, - } - } + fn convert(currency: CurrencyId) -> Option { + match currency { + CurrencyId::MantaCurrency(asset_id) => match AssetXConverter::reverse_ref(&asset_id) { + Ok(location) => Some(location), + Err(_) => None, + }, + } + } } parameter_types! { - pub const BaseXcmWeight: Weight = 100_000_000; - pub const MaxAssetsForTransfer: usize = 2; + pub const BaseXcmWeight: Weight = 100_000_000; + pub const MaxAssetsForTransfer: usize = 2; } // The XCM message wrapper wrapper impl orml_xtokens::Config for Runtime { - type Event = Event; - type Balance = Balance; - type CurrencyId = CurrencyId; - type AccountIdToMultiLocation = manta_primitives::xcm::AccountIdToMultiLocation; - type CurrencyIdConvert = - CurrencyIdtoMultiLocation>; - type XcmExecutor = XcmExecutor; - type SelfLocation = SelfReserve; - type Weigher = xcm_builder::FixedWeightBounds; - type BaseXcmWeight = BaseXcmWeight; - type LocationInverter = LocationInverter; - type MaxAssetsForTransfer = MaxAssetsForTransfer; - type MinXcmFee = AssetManager; - type MultiLocationsFilter = AssetManager; - type ReserveProvider = orml_traits::location::AbsoluteReserveProvider; + type Event = Event; + type Balance = Balance; + type CurrencyId = CurrencyId; + type AccountIdToMultiLocation = manta_primitives::xcm::AccountIdToMultiLocation; + type CurrencyIdConvert = + CurrencyIdtoMultiLocation>; + type XcmExecutor = XcmExecutor; + type SelfLocation = SelfReserve; + type Weigher = xcm_builder::FixedWeightBounds; + type BaseXcmWeight = BaseXcmWeight; + type LocationInverter = LocationInverter; + type MaxAssetsForTransfer = MaxAssetsForTransfer; + type MinXcmFee = AssetManager; + type MultiLocationsFilter = AssetManager; + type ReserveProvider = orml_traits::location::AbsoluteReserveProvider; } impl parachain_info::Config for Runtime {} @@ -607,121 +607,121 @@ type Block = frame_system::mocking::MockBlock; pub const PALLET_ASSET_INDEX: u8 = 1; construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - System: frame_system::{Pallet, Call, Storage, Config, Event} = 0, - Assets: pallet_assets::{Pallet, Storage, Event} = 1, - AssetManager: pallet_asset_manager::{Pallet, Call, Storage, Event} = 2, - Balances: pallet_balances::{Pallet, Call, Storage, Config, Event} = 3, - MsgQueue: mock_msg_queue::{Pallet, Storage, Event} = 4, - PolkadotXcm: pallet_xcm::{Pallet, Call, Event, Origin} = 5, - XTokens: orml_xtokens::{Pallet, Call, Event, Storage} = 6, - CumulusXcm: cumulus_pallet_xcm::{Pallet, Event, Origin} = 7, - ParachainInfo: parachain_info::{Pallet, Storage, Config} = 8, - XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event} = 9, - ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event, ValidateUnsigned} = 10, - } + pub enum Runtime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Storage, Config, Event} = 0, + Assets: pallet_assets::{Pallet, Storage, Event} = 1, + AssetManager: pallet_asset_manager::{Pallet, Call, Storage, Event} = 2, + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event} = 3, + MsgQueue: mock_msg_queue::{Pallet, Storage, Event} = 4, + PolkadotXcm: pallet_xcm::{Pallet, Call, Event, Origin} = 5, + XTokens: orml_xtokens::{Pallet, Call, Event, Storage} = 6, + CumulusXcm: cumulus_pallet_xcm::{Pallet, Event, Origin} = 7, + ParachainInfo: parachain_info::{Pallet, Storage, Config} = 8, + XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event} = 9, + ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event, ValidateUnsigned} = 10, + } ); pub(crate) fn para_events() -> Vec { - System::events() - .into_iter() - .map(|r| r.event) - .filter_map(|e| Some(e)) - .collect::>() + System::events() + .into_iter() + .map(|r| r.event) + .filter_map(Some) + .collect::>() } use frame_support::traits::{OnFinalize, OnInitialize, OnRuntimeUpgrade}; pub(crate) fn on_runtime_upgrade() { - PolkadotXcm::on_runtime_upgrade(); + PolkadotXcm::on_runtime_upgrade(); } pub(crate) fn para_roll_to(n: u64) { - while System::block_number() < n { - PolkadotXcm::on_finalize(System::block_number()); - Balances::on_finalize(System::block_number()); - System::on_finalize(System::block_number()); - System::set_block_number(System::block_number() + 1); - System::on_initialize(System::block_number()); - Balances::on_initialize(System::block_number()); - PolkadotXcm::on_initialize(System::block_number()); - } + while System::block_number() < n { + PolkadotXcm::on_finalize(System::block_number()); + Balances::on_finalize(System::block_number()); + System::on_finalize(System::block_number()); + System::set_block_number(System::block_number() + 1); + System::on_initialize(System::block_number()); + Balances::on_initialize(System::block_number()); + PolkadotXcm::on_initialize(System::block_number()); + } } pub(crate) fn create_asset_metadata( - name: &str, - symbol: &str, - decimals: u8, - min_balance: u128, - evm_address: Option, - is_frozen: bool, - is_sufficient: bool, + name: &str, + symbol: &str, + decimals: u8, + min_balance: u128, + evm_address: Option, + is_frozen: bool, + is_sufficient: bool, ) -> AssetRegistrarMetadata { - AssetRegistrarMetadata { - name: name.as_bytes().to_vec(), - symbol: symbol.as_bytes().to_vec(), - decimals, - min_balance, - evm_address, - is_frozen, - is_sufficient, - } + AssetRegistrarMetadata { + name: name.as_bytes().to_vec(), + symbol: symbol.as_bytes().to_vec(), + decimals, + min_balance, + evm_address, + is_frozen, + is_sufficient, + } } pub(crate) fn create_asset_location(parents: u8, para_id: u32) -> AssetLocation { - AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( - parents, - X1(Parachain(para_id)), - ))) + AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( + parents, + X1(Parachain(para_id)), + ))) } pub(crate) fn register_assets_on_parachain

( - source_location: &AssetLocation, - asset_metadata: &AssetRegistrarMetadata, - units_per_second: Option, - mint_asset: Option<(AccountId, Balance, bool, bool)>, + source_location: &AssetLocation, + asset_metadata: &AssetRegistrarMetadata, + units_per_second: Option, + mint_asset: Option<(AccountId, Balance, bool, bool)>, ) -> AssetId where - P: XcmpMessageHandlerT + DmpMessageHandlerT + TestExt, + P: XcmpMessageHandlerT + DmpMessageHandlerT + TestExt, { - let mut currency_id = 0u32; - P::execute_with(|| { - currency_id = AssetManager::next_asset_id(); - assert_ok!(AssetManager::register_asset( - self::Origin::root(), - source_location.clone(), - asset_metadata.clone() - )); - - if let Some((owner, min_balance, is_sufficient, is_frozen)) = mint_asset { - assert_ok!(self::Assets::force_asset_status( - self::Origin::root(), - currency_id, - owner.clone().into(), - owner.clone().into(), - owner.clone().into(), - owner.into(), - min_balance, - is_sufficient, - is_frozen, - )); - } - - if let Some(ups) = units_per_second { - assert_ok!(AssetManager::set_units_per_second( - self::Origin::root(), - currency_id, - ups, - )); - } - - assert_eq!( - Some(currency_id), - AssetManager::location_asset_id(source_location.clone()) - ); - }); - currency_id + let mut currency_id = 0u32; + P::execute_with(|| { + currency_id = AssetManager::next_asset_id(); + assert_ok!(AssetManager::register_asset( + self::Origin::root(), + source_location.clone(), + asset_metadata.clone() + )); + + if let Some((owner, min_balance, is_sufficient, is_frozen)) = mint_asset { + assert_ok!(self::Assets::force_asset_status( + self::Origin::root(), + currency_id, + owner.clone(), + owner.clone(), + owner.clone(), + owner, + min_balance, + is_sufficient, + is_frozen, + )); + } + + if let Some(ups) = units_per_second { + assert_ok!(AssetManager::set_units_per_second( + self::Origin::root(), + currency_id, + ups, + )); + } + + assert_eq!( + Some(currency_id), + AssetManager::location_asset_id(source_location.clone()) + ); + }); + currency_id } diff --git a/runtime/common/tests/xcm_mock/relay_chain.rs b/runtime/common/tests/xcm_mock/relay_chain.rs index 39b60bf52..36ce77e83 100644 --- a/runtime/common/tests/xcm_mock/relay_chain.rs +++ b/runtime/common/tests/xcm_mock/relay_chain.rs @@ -17,9 +17,9 @@ //! Relay chain runtime mock. use frame_support::{ - construct_runtime, parameter_types, - traits::{ConstU32, Everything, Nothing}, - weights::Weight, + construct_runtime, parameter_types, + traits::{ConstU32, Everything, Nothing}, + weights::Weight, }; use sp_core::H256; use sp_runtime::{testing::Header, traits::IdentityLookup, AccountId32}; @@ -28,168 +28,168 @@ use polkadot_parachain::primitives::Id as ParaId; use polkadot_runtime_parachains::{configuration, origin, shared, ump}; use xcm::latest::prelude::*; use xcm_builder::{ - AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, - AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, ChildParachainAsNative, - ChildParachainConvertsVia, ChildSystemParachainAsSuperuser, - CurrencyAdapter as XcmCurrencyAdapter, FixedRateOfFungible, FixedWeightBounds, IsConcrete, - LocationInverter, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, - TakeWeightCredit, + AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, + AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, ChildParachainAsNative, + ChildParachainConvertsVia, ChildSystemParachainAsSuperuser, + CurrencyAdapter as XcmCurrencyAdapter, FixedRateOfFungible, FixedWeightBounds, IsConcrete, + LocationInverter, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, + TakeWeightCredit, }; use xcm_executor::{Config, XcmExecutor}; pub type AccountId = AccountId32; pub type Balance = u128; parameter_types! { - pub const BlockHashCount: u64 = 250; + pub const BlockHashCount: u64 = 250; } impl frame_system::Config for Runtime { - type Origin = Origin; - type Call = Call; - type Index = u64; - type BlockNumber = u64; - type Hash = H256; - type Hashing = ::sp_runtime::traits::BlakeTwo256; - type AccountId = AccountId; - type Lookup = IdentityLookup; - type Header = Header; - type Event = Event; - type BlockHashCount = BlockHashCount; - 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>; + type Origin = Origin; + type Call = Call; + type Index = u64; + type BlockNumber = u64; + type Hash = H256; + type Hashing = ::sp_runtime::traits::BlakeTwo256; + type AccountId = AccountId; + type Lookup = IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = BlockHashCount; + 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; + 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 Event = Event; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; - type WeightInfo = (); - type MaxReserves = MaxReserves; - type ReserveIdentifier = [u8; 8]; + type MaxLocks = MaxLocks; + type Balance = Balance; + type Event = Event; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = (); + type MaxReserves = MaxReserves; + type ReserveIdentifier = [u8; 8]; } impl pallet_utility::Config for Runtime { - type Event = Event; - type Call = Call; - type WeightInfo = (); - type PalletsOrigin = OriginCaller; + type Event = Event; + type Call = Call; + type WeightInfo = (); + type PalletsOrigin = OriginCaller; } impl shared::Config for Runtime {} impl configuration::Config for Runtime { - type WeightInfo = configuration::TestWeightInfo; + type WeightInfo = configuration::TestWeightInfo; } parameter_types! { - pub const KsmLocation: MultiLocation = Here.into(); - pub const KusamaNetwork: NetworkId = NetworkId::Kusama; - pub const AnyNetwork: NetworkId = NetworkId::Any; - pub Ancestry: MultiLocation = Here.into(); - pub UnitWeightCost: Weight = 1_000; + pub const KsmLocation: MultiLocation = Here.into(); + pub const KusamaNetwork: NetworkId = NetworkId::Kusama; + pub const AnyNetwork: NetworkId = NetworkId::Any; + pub Ancestry: MultiLocation = Here.into(); + pub UnitWeightCost: Weight = 1_000; } pub type SovereignAccountOf = ( - ChildParachainConvertsVia, - AccountId32Aliases, + ChildParachainConvertsVia, + AccountId32Aliases, ); pub type LocalAssetTransactor = - XcmCurrencyAdapter, SovereignAccountOf, AccountId, ()>; + XcmCurrencyAdapter, SovereignAccountOf, AccountId, ()>; type LocalOriginConverter = ( - SovereignSignedViaLocation, - ChildParachainAsNative, - SignedAccountId32AsNative, - ChildSystemParachainAsSuperuser, + SovereignSignedViaLocation, + ChildParachainAsNative, + SignedAccountId32AsNative, + ChildSystemParachainAsSuperuser, ); parameter_types! { - pub const BaseXcmWeight: Weight = 1_000; - pub KsmPerSecond: (AssetId, u128) = (Concrete(KsmLocation::get()), 1); - pub const MaxInstructions: u32 = 100; + pub const BaseXcmWeight: Weight = 1_000; + pub KsmPerSecond: (AssetId, u128) = (Concrete(KsmLocation::get()), 1); + pub const MaxInstructions: u32 = 100; } pub type XcmRouter = super::RelayChainXcmRouter; pub type Barrier = ( - TakeWeightCredit, - AllowTopLevelPaidExecutionFrom, - // Expected responses are OK. - AllowKnownQueryResponses, - // Subscriptions for version tracking are OK. - AllowSubscriptionsFrom, - // The following is purely for testing ump - AllowUnpaidExecutionFrom, + TakeWeightCredit, + AllowTopLevelPaidExecutionFrom, + // Expected responses are OK. + AllowKnownQueryResponses, + // Subscriptions for version tracking are OK. + AllowSubscriptionsFrom, + // The following is purely for testing ump + AllowUnpaidExecutionFrom, ); pub struct XcmExecutorConfig; impl Config for XcmExecutorConfig { - type Call = Call; - type XcmSender = XcmRouter; - type AssetTransactor = LocalAssetTransactor; - type OriginConverter = LocalOriginConverter; - type IsReserve = (); - type IsTeleporter = (); - type LocationInverter = LocationInverter; - type Barrier = Barrier; - type Weigher = FixedWeightBounds; - type Trader = FixedRateOfFungible; - type ResponseHandler = XcmPallet; - type AssetTrap = XcmPallet; - type AssetClaims = XcmPallet; - type SubscriptionService = XcmPallet; + type Call = Call; + type XcmSender = XcmRouter; + type AssetTransactor = LocalAssetTransactor; + type OriginConverter = LocalOriginConverter; + type IsReserve = (); + type IsTeleporter = (); + type LocationInverter = LocationInverter; + type Barrier = Barrier; + type Weigher = FixedWeightBounds; + type Trader = FixedRateOfFungible; + type ResponseHandler = XcmPallet; + type AssetTrap = XcmPallet; + type AssetClaims = XcmPallet; + type SubscriptionService = XcmPallet; } pub type LocalOriginToLocation = SignedToAccountId32; impl pallet_xcm::Config for Runtime { - type Event = Event; - type SendXcmOrigin = xcm_builder::EnsureXcmOrigin; - type XcmRouter = XcmRouter; - // Anyone can execute XCM messages locally... - type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin; - type XcmExecuteFilter = Nothing; - type XcmExecutor = XcmExecutor; - type XcmTeleportFilter = Everything; - type XcmReserveTransferFilter = Everything; - type Weigher = FixedWeightBounds; - type LocationInverter = LocationInverter; - type Origin = Origin; - type Call = Call; - const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; - type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; + type Event = Event; + type SendXcmOrigin = xcm_builder::EnsureXcmOrigin; + type XcmRouter = XcmRouter; + // Anyone can execute XCM messages locally... + type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin; + type XcmExecuteFilter = Nothing; + type XcmExecutor = XcmExecutor; + type XcmTeleportFilter = Everything; + type XcmReserveTransferFilter = Everything; + type Weigher = FixedWeightBounds; + type LocationInverter = LocationInverter; + type Origin = Origin; + type Call = Call; + const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; + type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; } parameter_types! { - pub const FirstMessageFactorPercent: u64 = 100; + pub const FirstMessageFactorPercent: u64 = 100; } impl ump::Config for Runtime { - type Event = Event; - type UmpSink = ump::XcmSink, Runtime>; - type FirstMessageFactorPercent = FirstMessageFactorPercent; - type ExecuteOverweightOrigin = frame_system::EnsureRoot; - type WeightInfo = polkadot_runtime_parachains::ump::TestWeightInfo; + type Event = Event; + type UmpSink = ump::XcmSink, Runtime>; + type FirstMessageFactorPercent = FirstMessageFactorPercent; + type ExecuteOverweightOrigin = frame_system::EnsureRoot; + type WeightInfo = polkadot_runtime_parachains::ump::TestWeightInfo; } impl origin::Config for Runtime {} @@ -198,37 +198,37 @@ type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic type Block = frame_system::mocking::MockBlock; construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - System: frame_system::{Pallet, Call, Storage, Config, Event}, - Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - ParasOrigin: origin::{Pallet, Origin}, - ParasUmp: ump::{Pallet, Call, Storage, Event}, - XcmPallet: pallet_xcm::{Pallet, Call, Storage, Event, Origin}, - Utility: pallet_utility::{Pallet, Call, Event}, - } + pub enum Runtime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Storage, Config, Event}, + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, + ParasOrigin: origin::{Pallet, Origin}, + ParasUmp: ump::{Pallet, Call, Storage, Event}, + XcmPallet: pallet_xcm::{Pallet, Call, Storage, Event, Origin}, + Utility: pallet_utility::{Pallet, Call, Event}, + } ); pub(crate) fn relay_events() -> Vec { - System::events() - .into_iter() - .map(|r| r.event) - .filter_map(|e| Some(e)) - .collect::>() + System::events() + .into_iter() + .map(|r| r.event) + .filter_map(Some) + .collect::>() } use frame_support::traits::{OnFinalize, OnInitialize}; pub(crate) fn relay_roll_to(n: u64) { - while System::block_number() < n { - XcmPallet::on_finalize(System::block_number()); - Balances::on_finalize(System::block_number()); - System::on_finalize(System::block_number()); - System::set_block_number(System::block_number() + 1); - System::on_initialize(System::block_number()); - Balances::on_initialize(System::block_number()); - XcmPallet::on_initialize(System::block_number()); - } + while System::block_number() < n { + XcmPallet::on_finalize(System::block_number()); + Balances::on_finalize(System::block_number()); + System::on_finalize(System::block_number()); + System::set_block_number(System::block_number() + 1); + System::on_initialize(System::block_number()); + Balances::on_initialize(System::block_number()); + XcmPallet::on_initialize(System::block_number()); + } } diff --git a/runtime/common/tests/xcm_tests.rs b/runtime/common/tests/xcm_tests.rs index 2a2670d82..6ad420f47 100644 --- a/runtime/common/tests/xcm_tests.rs +++ b/runtime/common/tests/xcm_tests.rs @@ -28,8 +28,8 @@ use xcm_mock::{parachain::PALLET_ASSET_INDEX, *}; use xcm_simulator::TestExt; use crate::xcm_mock::parachain::{ - create_asset_location, create_asset_metadata, register_assets_on_parachain, AssetManager, - ParaTokenPerSecond, + create_asset_location, create_asset_metadata, register_assets_on_parachain, AssetManager, + ParaTokenPerSecond, }; // `reserved_transfer_asset` contains the following 4 instructions @@ -41,1400 +41,1385 @@ use crate::xcm_mock::parachain::{ const RESERVE_TRANSFER_WEIGHT: u64 = 4000; fn calculate_fee(units_per_seconds: u128, weight: u64) -> u128 { - units_per_seconds * (weight as u128) / (WEIGHT_PER_SECOND as u128) + units_per_seconds * (weight as u128) / (WEIGHT_PER_SECOND as u128) } // Helper function for forming buy execution message fn buy_execution(fees: impl Into) -> Instruction { - BuyExecution { - fees: fees.into(), - weight_limit: Unlimited, - } + BuyExecution { + fees: fees.into(), + weight_limit: Unlimited, + } } #[test] fn dmp() { - MockNet::reset(); - - let remark = parachain::Call::System( - frame_system::Call::::remark_with_event { - remark: vec![1, 2, 3], - }, - ); - Relay::execute_with(|| { - assert_ok!(RelayChainPalletXcm::send_xcm( - Here, - Parachain(1), - Xcm(vec![Transact { - origin_type: OriginKind::SovereignAccount, - require_weight_at_most: INITIAL_BALANCE as u64, - call: remark.encode().into(), - }]), - )); - }); - - ParaA::execute_with(|| { - use parachain::{Event, System}; - assert!(System::events() - .iter() - .any(|r| matches!(r.event, Event::System(frame_system::Event::Remarked { .. })))); - }); + MockNet::reset(); + + let remark = parachain::Call::System( + frame_system::Call::::remark_with_event { + remark: vec![1, 2, 3], + }, + ); + Relay::execute_with(|| { + assert_ok!(RelayChainPalletXcm::send_xcm( + Here, + Parachain(1), + Xcm(vec![Transact { + origin_type: OriginKind::SovereignAccount, + require_weight_at_most: INITIAL_BALANCE as u64, + call: remark.encode().into(), + }]), + )); + }); + + ParaA::execute_with(|| { + use parachain::{Event, System}; + assert!(System::events() + .iter() + .any(|r| matches!(r.event, Event::System(frame_system::Event::Remarked { .. })))); + }); } #[test] fn ump() { - MockNet::reset(); - - let remark = relay_chain::Call::System( - frame_system::Call::::remark_with_event { - remark: vec![1, 2, 3], - }, - ); - ParaA::execute_with(|| { - assert_ok!(ParachainPalletXcm::send_xcm( - Here, - Parent, - Xcm(vec![Transact { - origin_type: OriginKind::SovereignAccount, - require_weight_at_most: INITIAL_BALANCE as u64, - call: remark.encode().into(), - }]), - )); - }); - - Relay::execute_with(|| { - use relay_chain::{Event, System}; - assert!(System::events() - .iter() - .any(|r| matches!(r.event, Event::System(frame_system::Event::Remarked { .. })))); - }); + MockNet::reset(); + + let remark = relay_chain::Call::System( + frame_system::Call::::remark_with_event { + remark: vec![1, 2, 3], + }, + ); + ParaA::execute_with(|| { + assert_ok!(ParachainPalletXcm::send_xcm( + Here, + Parent, + Xcm(vec![Transact { + origin_type: OriginKind::SovereignAccount, + require_weight_at_most: INITIAL_BALANCE as u64, + call: remark.encode().into(), + }]), + )); + }); + + Relay::execute_with(|| { + use relay_chain::{Event, System}; + assert!(System::events() + .iter() + .any(|r| matches!(r.event, Event::System(frame_system::Event::Remarked { .. })))); + }); } #[test] fn xcmp() { - MockNet::reset(); - - let remark = parachain::Call::System( - frame_system::Call::::remark_with_event { - remark: vec![1, 2, 3], - }, - ); - ParaA::execute_with(|| { - assert_ok!(ParachainPalletXcm::send_xcm( - Here, - (Parent, Parachain(2)), - Xcm(vec![Transact { - origin_type: OriginKind::SovereignAccount, - require_weight_at_most: INITIAL_BALANCE as u64, - call: remark.encode().into(), - }]), - )); - }); - - ParaB::execute_with(|| { - use parachain::{Event, System}; - assert!(System::events() - .iter() - .any(|r| matches!(r.event, Event::System(frame_system::Event::Remarked { .. })))); - }); + MockNet::reset(); + + let remark = parachain::Call::System( + frame_system::Call::::remark_with_event { + remark: vec![1, 2, 3], + }, + ); + ParaA::execute_with(|| { + assert_ok!(ParachainPalletXcm::send_xcm( + Here, + (Parent, Parachain(2)), + Xcm(vec![Transact { + origin_type: OriginKind::SovereignAccount, + require_weight_at_most: INITIAL_BALANCE as u64, + call: remark.encode().into(), + }]), + )); + }); + + ParaB::execute_with(|| { + use parachain::{Event, System}; + assert!(System::events() + .iter() + .any(|r| matches!(r.event, Event::System(frame_system::Event::Remarked { .. })))); + }); } #[test] fn reserve_transfer_relaychain_to_parachain_a() { - MockNet::reset(); - - let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); - - let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1, None, false, true); - - // Register relay chain asset in parachain A - let relay_asset_id = - register_assets_on_parachain::(&source_location, &asset_metadata, Some(0u128), None); - - let withdraw_amount = 123; - - Relay::execute_with(|| { - assert_ok!(RelayChainPalletXcm::reserve_transfer_assets( - relay_chain::Origin::signed(ALICE), - Box::new(X1(Parachain(1)).into().into()), - Box::new( - X1(AccountId32 { - network: Any, - id: ALICE.into() - }) - .into() - .into() - ), - Box::new((Here, withdraw_amount).into()), - 0, - )); - assert_eq!( - relay_chain::Balances::free_balance(¶_account_id(1)), - INITIAL_BALANCE + withdraw_amount - ); - }); - - ParaA::execute_with(|| { - // free execution, full amount received - assert_eq!( - pallet_assets::Pallet::::balance(relay_asset_id, &ALICE.into()), - withdraw_amount - ); - }); + MockNet::reset(); + + let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); + + let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1, None, false, true); + + // Register relay chain asset in parachain A + let relay_asset_id = + register_assets_on_parachain::(&source_location, &asset_metadata, Some(0u128), None); + + let withdraw_amount = 123; + + Relay::execute_with(|| { + assert_ok!(RelayChainPalletXcm::reserve_transfer_assets( + relay_chain::Origin::signed(ALICE), + Box::new(X1(Parachain(1)).into().into()), + Box::new( + X1(AccountId32 { + network: Any, + id: ALICE.into() + }) + .into() + .into() + ), + Box::new((Here, withdraw_amount).into()), + 0, + )); + assert_eq!( + relay_chain::Balances::free_balance(¶_account_id(1)), + INITIAL_BALANCE + withdraw_amount + ); + }); + + ParaA::execute_with(|| { + // free execution, full amount received + assert_eq!( + pallet_assets::Pallet::::balance(relay_asset_id, &ALICE), + withdraw_amount + ); + }); } #[test] fn reserve_transfer_relaychain_to_parachain_a_then_back() { - MockNet::reset(); - - let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); - let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1, None, false, true); - - // Register relay chain asset in parachain A - let relay_asset_id = - register_assets_on_parachain::(&source_location, &asset_metadata, Some(0u128), None); - - let amount = 123; - - Relay::execute_with(|| { - assert_ok!(RelayChainPalletXcm::reserve_transfer_assets( - relay_chain::Origin::signed(ALICE), - Box::new(X1(Parachain(1)).into().into()), - Box::new( - X1(AccountId32 { - network: Any, - id: ALICE.into() - }) - .into() - .into() - ), - Box::new((Here, amount).into()), - 0, - )); - assert_eq!( - parachain::Balances::free_balance(¶_account_id(1)), - INITIAL_BALANCE + amount - ); - }); - - ParaA::execute_with(|| { - // free execution, full amount received - assert_eq!( - pallet_assets::Pallet::::balance(relay_asset_id, &ALICE.into()), - amount - ); - }); - - // Checking the balance of relay chain before sending token back - let mut balance_before_sending = 0; - Relay::execute_with(|| { - balance_before_sending = RelayBalances::free_balance(&ALICE); - }); - - let dest = MultiLocation { - parents: 1, - interior: X1(AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }), - }; - - ParaA::execute_with(|| { - // free execution, full amount received - assert_ok!(parachain::XTokens::transfer( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(relay_asset_id), - amount, - Box::new(VersionedMultiLocation::V1(dest)), - 40000 - )); - }); - - ParaA::execute_with(|| { - // free execution, this will drain the parachain asset account - assert_eq!(parachain::Assets::balance(relay_asset_id, &ALICE.into()), 0); - }); - - Relay::execute_with(|| { - // free execution, full amount received - assert_eq!( - RelayBalances::free_balance(&ALICE), - balance_before_sending + amount - ); - }); + MockNet::reset(); + + let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); + let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1, None, false, true); + + // Register relay chain asset in parachain A + let relay_asset_id = + register_assets_on_parachain::(&source_location, &asset_metadata, Some(0u128), None); + + let amount = 123; + + Relay::execute_with(|| { + assert_ok!(RelayChainPalletXcm::reserve_transfer_assets( + relay_chain::Origin::signed(ALICE), + Box::new(X1(Parachain(1)).into().into()), + Box::new( + X1(AccountId32 { + network: Any, + id: ALICE.into() + }) + .into() + .into() + ), + Box::new((Here, amount).into()), + 0, + )); + assert_eq!( + parachain::Balances::free_balance(¶_account_id(1)), + INITIAL_BALANCE + amount + ); + }); + + ParaA::execute_with(|| { + // free execution, full amount received + assert_eq!( + pallet_assets::Pallet::::balance(relay_asset_id, &ALICE), + amount + ); + }); + + // Checking the balance of relay chain before sending token back + let mut balance_before_sending = 0; + Relay::execute_with(|| { + balance_before_sending = RelayBalances::free_balance(&ALICE); + }); + + let dest = MultiLocation { + parents: 1, + interior: X1(AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }), + }; + + ParaA::execute_with(|| { + // free execution, full amount received + assert_ok!(parachain::XTokens::transfer( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(relay_asset_id), + amount, + Box::new(VersionedMultiLocation::V1(dest)), + 40000 + )); + }); + + ParaA::execute_with(|| { + // free execution, this will drain the parachain asset account + assert_eq!(parachain::Assets::balance(relay_asset_id, &ALICE), 0); + }); + + Relay::execute_with(|| { + // free execution, full amount received + assert_eq!( + RelayBalances::free_balance(&ALICE), + balance_before_sending + amount + ); + }); } #[test] fn send_para_a_native_asset_to_para_b() { - MockNet::reset(); - - // We use an opinionated source location here: - // Ideally, we could use `here()`, however, we always prefer to use the location from - // `root` when possible. - let para_a_id = 1; - let para_b_id = 2; - let para_a_source_location = create_asset_location(1, para_a_id); - let para_b_source_location = create_asset_location(1, para_b_id); - let amount = 100u128; - - let para_a_asset_metadata = - create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, false); - let para_b_asset_metadata = - create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, false); - - // Register ParaA native asset in ParaB - let _ = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(0u128), - None, - ); - - // Register ParaA native asset in ParaA - let a_currency_id = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(0u128), - None, - ); - let _ = register_assets_on_parachain::( - ¶_b_source_location, - ¶_b_asset_metadata, - Some(0u128), - None, - ); - - let dest = MultiLocation { - parents: 1, - interior: X2( - Parachain(2), - AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }, - ), - }; - - // Transfer ParaA balance to B - ParaA::execute_with(|| { - assert_ok!(parachain::XTokens::transfer( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(a_currency_id), - amount, - Box::new(VersionedMultiLocation::V1(dest)), - 800000 - )); - assert_eq!( - parachain::Balances::free_balance(&ALICE.into()), - INITIAL_BALANCE - amount - ) - }); - - // Make sure B received the token - ParaB::execute_with(|| { - // free execution, full amount received - assert_eq!( - parachain::Assets::balance(a_currency_id, &ALICE.into()), - amount - ); - }); + MockNet::reset(); + + // We use an opinionated source location here: + // Ideally, we could use `here()`, however, we always prefer to use the location from + // `root` when possible. + let para_a_id = 1; + let para_b_id = 2; + let para_a_source_location = create_asset_location(1, para_a_id); + let para_b_source_location = create_asset_location(1, para_b_id); + let amount = 100u128; + + let para_a_asset_metadata = + create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, false); + let para_b_asset_metadata = + create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, false); + + // Register ParaA native asset in ParaB + let _ = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(0u128), + None, + ); + + // Register ParaA native asset in ParaA + let a_currency_id = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(0u128), + None, + ); + let _ = register_assets_on_parachain::( + ¶_b_source_location, + ¶_b_asset_metadata, + Some(0u128), + None, + ); + + let dest = MultiLocation { + parents: 1, + interior: X2( + Parachain(2), + AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }, + ), + }; + + // Transfer ParaA balance to B + ParaA::execute_with(|| { + assert_ok!(parachain::XTokens::transfer( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(a_currency_id), + amount, + Box::new(VersionedMultiLocation::V1(dest)), + 800000 + )); + assert_eq!( + parachain::Balances::free_balance(&ALICE), + INITIAL_BALANCE - amount + ) + }); + + // Make sure B received the token + ParaB::execute_with(|| { + // free execution, full amount received + assert_eq!(parachain::Assets::balance(a_currency_id, &ALICE), amount); + }); } #[test] fn send_not_sufficient_asset_from_para_a_to_para_b() { - MockNet::reset(); - - let para_a_id = 1; - let para_b_id = 2; - let para_a_source_location = create_asset_location(1, para_a_id); - let para_b_source_location = create_asset_location(1, para_b_id); - - let amount = 8888u128; - let units_per_second_at_b = 1_250_000u128; - let dest_weight = 1600_000u64; - let fee_at_b = calculate_fee(units_per_second_at_b, dest_weight); - - let para_a_asset_metadata = - create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, false); - let para_b_asset_metadata = - create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, false); - - // Register ParaA native asset in ParaA - let a_currency_id = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(0u128), - None, - ); - let _ = register_assets_on_parachain::( - ¶_b_source_location, - ¶_b_asset_metadata, - Some(0u128), - None, - ); - - // Register ParaA native asset in ParaB - let _ = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(units_per_second_at_b), - None, - ); - - let dest = MultiLocation { - parents: 1, - interior: X2( - Parachain(2), - AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }, - ), - }; - - assert!(amount >= fee_at_b); - // Transfer ParaA balance to B - ParaA::execute_with(|| { - assert_ok!(parachain::XTokens::transfer( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(a_currency_id), - amount, - Box::new(VersionedMultiLocation::V1(dest.clone())), - dest_weight - )); - assert_eq!( - parachain::Balances::free_balance(&ALICE.into()), - INITIAL_BALANCE - amount - ) - }); - - ParaB::execute_with(|| { - // The total supply should not include the paid fee, - // because the XcmFeesAccount had 0 providers with is_sufficient set to false, - // so the mint_into() operation for the refund amount failed. - assert_eq!( - parachain::Assets::total_supply(a_currency_id), - amount - fee_at_b - ); - assert_eq!( - parachain::Assets::balance(a_currency_id, &ALICE.into()), - amount - fee_at_b - ); - }); - - // Setting the balance will in effect create the account - // incrementing its providers counter to from 0 to 1 - ParaB::execute_with(|| { - assert_ok!(pallet_balances::Pallet::::set_balance( - parachain::Origin::root(), - parachain::AssetManager::account_id(), - 1000000000000000, - 1000000000000000 - )); - }); - - ParaA::execute_with(|| { - assert_ok!(parachain::XTokens::transfer( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(a_currency_id), - amount, - Box::new(VersionedMultiLocation::V1(dest.clone())), - dest_weight - )); - assert_eq!( - parachain::Balances::free_balance(&ALICE.into()), - INITIAL_BALANCE - amount * 2 - ) - }); - - ParaB::execute_with(|| { - // This time we expect the total supply to be the full amount - // as the refund will be deposited to the XcmFeesAccount - assert_eq!( - parachain::Assets::total_supply(a_currency_id), - (amount - fee_at_b) + amount - ); - assert_eq!( - parachain::Assets::balance(a_currency_id, &ALICE.into()), - (amount - fee_at_b) * 2 - ); - }); + MockNet::reset(); + + let para_a_id = 1; + let para_b_id = 2; + let para_a_source_location = create_asset_location(1, para_a_id); + let para_b_source_location = create_asset_location(1, para_b_id); + + let amount = 8888u128; + let units_per_second_at_b = 1_250_000u128; + let dest_weight = 1_600_000_u64; + let fee_at_b = calculate_fee(units_per_second_at_b, dest_weight); + + let para_a_asset_metadata = + create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, false); + let para_b_asset_metadata = + create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, false); + + // Register ParaA native asset in ParaA + let a_currency_id = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(0u128), + None, + ); + let _ = register_assets_on_parachain::( + ¶_b_source_location, + ¶_b_asset_metadata, + Some(0u128), + None, + ); + + // Register ParaA native asset in ParaB + let _ = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(units_per_second_at_b), + None, + ); + + let dest = MultiLocation { + parents: 1, + interior: X2( + Parachain(2), + AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }, + ), + }; + + assert!(amount >= fee_at_b); + // Transfer ParaA balance to B + ParaA::execute_with(|| { + assert_ok!(parachain::XTokens::transfer( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(a_currency_id), + amount, + Box::new(VersionedMultiLocation::V1(dest.clone())), + dest_weight + )); + assert_eq!( + parachain::Balances::free_balance(&ALICE), + INITIAL_BALANCE - amount + ) + }); + + ParaB::execute_with(|| { + // The total supply should not include the paid fee, + // because the XcmFeesAccount had 0 providers with is_sufficient set to false, + // so the mint_into() operation for the refund amount failed. + assert_eq!( + parachain::Assets::total_supply(a_currency_id), + amount - fee_at_b + ); + assert_eq!( + parachain::Assets::balance(a_currency_id, &ALICE), + amount - fee_at_b + ); + }); + + // Setting the balance will in effect create the account + // incrementing its providers counter to from 0 to 1 + ParaB::execute_with(|| { + assert_ok!(pallet_balances::Pallet::::set_balance( + parachain::Origin::root(), + parachain::AssetManager::account_id(), + 1000000000000000, + 1000000000000000 + )); + }); + + ParaA::execute_with(|| { + assert_ok!(parachain::XTokens::transfer( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(a_currency_id), + amount, + Box::new(VersionedMultiLocation::V1(dest.clone())), + dest_weight + )); + assert_eq!( + parachain::Balances::free_balance(&ALICE), + INITIAL_BALANCE - amount * 2 + ) + }); + + ParaB::execute_with(|| { + // This time we expect the total supply to be the full amount + // as the refund will be deposited to the XcmFeesAccount + assert_eq!( + parachain::Assets::total_supply(a_currency_id), + (amount - fee_at_b) + amount + ); + assert_eq!( + parachain::Assets::balance(a_currency_id, &ALICE), + (amount - fee_at_b) * 2 + ); + }); } #[test] fn register_with_is_sufficient_false_and_zero_min_balance_should_fail() { - MockNet::reset(); - - let para_a_id = 1; - let source_location = create_asset_location(1, para_a_id); - - let asset_metadata = create_asset_metadata("ParaAToken", "ParaA", 18, 0, None, false, false); - - ParaB::execute_with(|| { - assert_err!( - AssetManager::register_asset( - parachain::Origin::root(), - source_location.clone(), - asset_metadata.clone() - ), - pallet_asset_manager::Error::::ErrorCreatingAsset - ); - }); + MockNet::reset(); + + let para_a_id = 1; + let source_location = create_asset_location(1, para_a_id); + + let asset_metadata = create_asset_metadata("ParaAToken", "ParaA", 18, 0, None, false, false); + + ParaB::execute_with(|| { + assert_err!( + AssetManager::register_asset( + parachain::Origin::root(), + source_location.clone(), + asset_metadata.clone() + ), + pallet_asset_manager::Error::::ErrorCreatingAsset + ); + }); } #[test] fn send_para_a_custom_asset_to_para_b() { - let amount = 321; - - let para_a_id = 1; - let para_b_id = 2; - let para_a_source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( - 1, - X3( - Parachain(para_a_id), - PalletInstance(PALLET_ASSET_INDEX), - GeneralIndex(0), - ), - ))); - let para_b_source_location = create_asset_location(1, para_b_id); - - let para_a_doge_asset_metadata = - create_asset_metadata("ParaADoge", "Doge", 18, 1, None, false, true); - let para_b_asset_metadata = - create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, false); - - // register doge in ParaA, ParaB - let doge_currency_id_on_a = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_doge_asset_metadata, - Some(0u128), - Some((ALICE, 1, true, false)), - ); - // register ParaB native asset on ParaA - let _ = register_assets_on_parachain::( - ¶_b_source_location, - ¶_b_asset_metadata, - Some(0u128), - None, - ); - - // register ParaA native asset on ParaB - let doge_currency_id_on_b = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_doge_asset_metadata, - Some(0u128), - None, - ); - - let alice_on_b = MultiLocation { - parents: 1, - interior: X2( - Parachain(2), - AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }, - ), - }; - - ParaA::execute_with(|| { - // Force customized asset balance for Alice - assert_ok!(parachain::Assets::mint( - parachain::Origin::signed(ALICE.into()), - doge_currency_id_on_a, - ALICE.into(), - INITIAL_BALANCE - )); - assert_ok!(parachain::XTokens::transfer( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(doge_currency_id_on_a), - amount, - Box::new(VersionedMultiLocation::V1(alice_on_b)), - 800000 - )); - assert_eq!( - parachain::Assets::balance(doge_currency_id_on_a, &ALICE.into()), - INITIAL_BALANCE - amount - ); - }); - - // Make sure B received the token - ParaB::execute_with(|| { - // free execution, full amount received - assert_eq!( - parachain::Assets::balance(doge_currency_id_on_b, &ALICE.into()), - amount - ); - }); + let amount = 321; + + let para_a_id = 1; + let para_b_id = 2; + let para_a_source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( + 1, + X3( + Parachain(para_a_id), + PalletInstance(PALLET_ASSET_INDEX), + GeneralIndex(0), + ), + ))); + let para_b_source_location = create_asset_location(1, para_b_id); + + let para_a_doge_asset_metadata = + create_asset_metadata("ParaADoge", "Doge", 18, 1, None, false, true); + let para_b_asset_metadata = + create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, false); + + // register doge in ParaA, ParaB + let doge_currency_id_on_a = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_doge_asset_metadata, + Some(0u128), + Some((ALICE, 1, true, false)), + ); + // register ParaB native asset on ParaA + let _ = register_assets_on_parachain::( + ¶_b_source_location, + ¶_b_asset_metadata, + Some(0u128), + None, + ); + + // register ParaA native asset on ParaB + let doge_currency_id_on_b = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_doge_asset_metadata, + Some(0u128), + None, + ); + + let alice_on_b = MultiLocation { + parents: 1, + interior: X2( + Parachain(2), + AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }, + ), + }; + + ParaA::execute_with(|| { + // Force customized asset balance for Alice + assert_ok!(parachain::Assets::mint( + parachain::Origin::signed(ALICE), + doge_currency_id_on_a, + ALICE, + INITIAL_BALANCE + )); + assert_ok!(parachain::XTokens::transfer( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(doge_currency_id_on_a), + amount, + Box::new(VersionedMultiLocation::V1(alice_on_b)), + 800000 + )); + assert_eq!( + parachain::Assets::balance(doge_currency_id_on_a, &ALICE), + INITIAL_BALANCE - amount + ); + }); + + // Make sure B received the token + ParaB::execute_with(|| { + // free execution, full amount received + assert_eq!( + parachain::Assets::balance(doge_currency_id_on_b, &ALICE), + amount + ); + }); } #[test] fn send_para_a_native_asset_para_b_and_then_send_back() { - MockNet::reset(); - - // para a native asset location - let para_a_id = 1; - let para_b_id = 2; - let para_a_source_location = create_asset_location(1, para_a_id); - let para_b_source_location = create_asset_location(1, para_b_id); - // a's currency id in para a, para b, and para c - let amount = 5000u128; - let weight = 800000u64; - let fee_on_b_when_send_back = calculate_fee(ParaTokenPerSecond::get().1, weight); - assert!(fee_on_b_when_send_back < amount); - - let para_a_asset_metadata = - create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, false); - let para_b_asset_metadata = - create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, false); - - // register ParaA native asset on ParaA - let a_currency_id = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(0u128), - None, - ); - // register ParaB native asset on ParaA - let _ = register_assets_on_parachain::( - ¶_b_source_location, - ¶_b_asset_metadata, - Some(0u128), - None, - ); - // register ParaA native asset on ParaB - let _ = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(0u128), - None, - ); - - let alice_on_b = MultiLocation { - parents: 1, - interior: X2( - Parachain(2), - AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }, - ), - }; - - ParaA::execute_with(|| { - assert_ok!(parachain::XTokens::transfer( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(a_currency_id), - amount, - Box::new(VersionedMultiLocation::V1(alice_on_b)), - 800000 - )); - assert_eq!( - parachain::Balances::free_balance(&ALICE.into()), - INITIAL_BALANCE - amount - ) - }); - - // Make sure B received the token - ParaB::execute_with(|| { - // free execution, full amount received - assert_eq!( - parachain::Assets::balance(a_currency_id, &ALICE.into()), - amount - ); - }); - - let alice_on_a = MultiLocation { - parents: 1, - interior: X2( - Parachain(1), - AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }, - ), - }; - - // Send wrapped a back to a - ParaB::execute_with(|| { - assert_ok!(parachain::XTokens::transfer( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(a_currency_id), - amount, - Box::new(VersionedMultiLocation::V1(alice_on_a)), - 800000 - )); - assert_eq!(parachain::Assets::balance(a_currency_id, &ALICE.into()), 0); - }); - - // make sure that a received the token - ParaA::execute_with(|| { - assert_eq!( - parachain::Balances::free_balance(&ALICE.into()), - INITIAL_BALANCE - fee_on_b_when_send_back - ) - }); + MockNet::reset(); + + // para a native asset location + let para_a_id = 1; + let para_b_id = 2; + let para_a_source_location = create_asset_location(1, para_a_id); + let para_b_source_location = create_asset_location(1, para_b_id); + // a's currency id in para a, para b, and para c + let amount = 5000u128; + let weight = 800000u64; + let fee_on_b_when_send_back = calculate_fee(ParaTokenPerSecond::get().1, weight); + assert!(fee_on_b_when_send_back < amount); + + let para_a_asset_metadata = + create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, false); + let para_b_asset_metadata = + create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, false); + + // register ParaA native asset on ParaA + let a_currency_id = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(0u128), + None, + ); + // register ParaB native asset on ParaA + let _ = register_assets_on_parachain::( + ¶_b_source_location, + ¶_b_asset_metadata, + Some(0u128), + None, + ); + // register ParaA native asset on ParaB + let _ = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(0u128), + None, + ); + + let alice_on_b = MultiLocation { + parents: 1, + interior: X2( + Parachain(2), + AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }, + ), + }; + + ParaA::execute_with(|| { + assert_ok!(parachain::XTokens::transfer( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(a_currency_id), + amount, + Box::new(VersionedMultiLocation::V1(alice_on_b)), + 800000 + )); + assert_eq!( + parachain::Balances::free_balance(&ALICE), + INITIAL_BALANCE - amount + ) + }); + + // Make sure B received the token + ParaB::execute_with(|| { + // free execution, full amount received + assert_eq!(parachain::Assets::balance(a_currency_id, &ALICE), amount); + }); + + let alice_on_a = MultiLocation { + parents: 1, + interior: X2( + Parachain(1), + AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }, + ), + }; + + // Send wrapped a back to a + ParaB::execute_with(|| { + assert_ok!(parachain::XTokens::transfer( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(a_currency_id), + amount, + Box::new(VersionedMultiLocation::V1(alice_on_a)), + 800000 + )); + assert_eq!(parachain::Assets::balance(a_currency_id, &ALICE), 0); + }); + + // make sure that a received the token + ParaA::execute_with(|| { + assert_eq!( + parachain::Balances::free_balance(&ALICE), + INITIAL_BALANCE - fee_on_b_when_send_back + ) + }); } #[test] fn send_para_a_native_asset_from_para_b_to_para_c() { - MockNet::reset(); - - // para a asset location - let para_a_id = 1; - let para_b_id = 2; - let para_c_id = 3; - let para_a_source_location = create_asset_location(1, para_a_id); - let para_b_source_location = create_asset_location(1, para_b_id); - let para_c_source_location = create_asset_location(1, para_c_id); - - let amount = 8888u128; - let weight = 800_000u64; - let fee_at_reserve = calculate_fee(ParaTokenPerSecond::get().1, weight); - assert!(amount >= fee_at_reserve * 2 as u128); - - let para_a_asset_metadata = - create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, false); - let para_b_asset_metadata = - create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, false); - let para_c_asset_metadata = - create_asset_metadata("ParaCToken", "ParaC", 18, 1, None, false, false); - - // register ParaA native asset on ParaA - let a_currency_id = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(0u128), - None, - ); - // register ParaB native asset on ParaA - let _ = register_assets_on_parachain::( - ¶_b_source_location, - ¶_b_asset_metadata, - Some(0u128), - None, - ); - - // register ParaA native asset on ParaB - let _ = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(0u128), - None, - ); - - // register ParaC native asset on ParaB - let _ = register_assets_on_parachain::( - ¶_c_source_location, - ¶_c_asset_metadata, - Some(0u128), - None, - ); - - // register ParaA native asset on ParaC - let _ = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(0u128), - None, - ); - - // A send B some token - let alice_on_b = MultiLocation { - parents: 1, - interior: X2( - Parachain(2), - AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }, - ), - }; - - ParaA::execute_with(|| { - assert_ok!(parachain::XTokens::transfer( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(a_currency_id), - amount, - Box::new(VersionedMultiLocation::V1(alice_on_b.clone())), - 800000 - )); - assert_eq!( - parachain::Balances::free_balance(&ALICE.into()), - INITIAL_BALANCE - amount - ) - }); - - ParaB::execute_with(|| { - // free execution, full amount received - assert_eq!( - parachain::Assets::balance(a_currency_id, &ALICE.into()), - amount - ); - }); - - // B send C para A asset - let alice_on_c = MultiLocation { - parents: 1, - interior: X2( - Parachain(3), - AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }, - ), - }; - - ParaB::execute_with(|| { - assert_ok!(parachain::XTokens::transfer( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(a_currency_id), - amount, - Box::new(VersionedMultiLocation::V1(alice_on_c)), - weight, - )); - assert_eq!(parachain::Assets::balance(a_currency_id, &ALICE.into()), 0); - }); - - // Make sure C received the token - ParaC::execute_with(|| { - // free execution, full amount received - assert_eq!( - parachain::Assets::balance(a_currency_id, &ALICE.into()), - amount - fee_at_reserve - ); - }); + MockNet::reset(); + + // para a asset location + let para_a_id = 1; + let para_b_id = 2; + let para_c_id = 3; + let para_a_source_location = create_asset_location(1, para_a_id); + let para_b_source_location = create_asset_location(1, para_b_id); + let para_c_source_location = create_asset_location(1, para_c_id); + + let amount = 8888u128; + let weight = 800_000u64; + let fee_at_reserve = calculate_fee(ParaTokenPerSecond::get().1, weight); + assert!(amount >= fee_at_reserve * 2_u128); + + let para_a_asset_metadata = + create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, false); + let para_b_asset_metadata = + create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, false); + let para_c_asset_metadata = + create_asset_metadata("ParaCToken", "ParaC", 18, 1, None, false, false); + + // register ParaA native asset on ParaA + let a_currency_id = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(0u128), + None, + ); + // register ParaB native asset on ParaA + let _ = register_assets_on_parachain::( + ¶_b_source_location, + ¶_b_asset_metadata, + Some(0u128), + None, + ); + + // register ParaA native asset on ParaB + let _ = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(0u128), + None, + ); + + // register ParaC native asset on ParaB + let _ = register_assets_on_parachain::( + ¶_c_source_location, + ¶_c_asset_metadata, + Some(0u128), + None, + ); + + // register ParaA native asset on ParaC + let _ = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(0u128), + None, + ); + + // A send B some token + let alice_on_b = MultiLocation { + parents: 1, + interior: X2( + Parachain(2), + AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }, + ), + }; + + ParaA::execute_with(|| { + assert_ok!(parachain::XTokens::transfer( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(a_currency_id), + amount, + Box::new(VersionedMultiLocation::V1(alice_on_b.clone())), + 800000 + )); + assert_eq!( + parachain::Balances::free_balance(&ALICE), + INITIAL_BALANCE - amount + ) + }); + + ParaB::execute_with(|| { + // free execution, full amount received + assert_eq!(parachain::Assets::balance(a_currency_id, &ALICE), amount); + }); + + // B send C para A asset + let alice_on_c = MultiLocation { + parents: 1, + interior: X2( + Parachain(3), + AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }, + ), + }; + + ParaB::execute_with(|| { + assert_ok!(parachain::XTokens::transfer( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(a_currency_id), + amount, + Box::new(VersionedMultiLocation::V1(alice_on_c)), + weight, + )); + assert_eq!(parachain::Assets::balance(a_currency_id, &ALICE), 0); + }); + + // Make sure C received the token + ParaC::execute_with(|| { + // free execution, full amount received + assert_eq!( + parachain::Assets::balance(a_currency_id, &ALICE), + amount - fee_at_reserve + ); + }); } #[test] fn receive_relay_asset_with_trader() { - MockNet::reset(); - - let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); - let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1, None, false, true); - - let amount = 666u128; - // We charge 10^9 as units per second on ParaA - let units_per_second = 1_000_000_000u128; - let fee = calculate_fee(units_per_second, RESERVE_TRANSFER_WEIGHT); - assert!(fee > 0); - - // Register relaychain native asset in ParaA - let relay_asset_id = register_assets_on_parachain::( - &source_location, - &asset_metadata, - Some(units_per_second), - None, - ); - - let dest: MultiLocation = AccountId32 { - network: Any, - id: ALICE.into(), - } - .into(); - - Relay::execute_with(|| { - assert_ok!(RelayChainPalletXcm::reserve_transfer_assets( - relay_chain::Origin::signed(ALICE), - Box::new(X1(Parachain(1)).into().into()), - Box::new(VersionedMultiLocation::V1(dest).clone().into()), - Box::new((Here, amount).into()), - 0, - )); - assert_eq!( - relay_chain::Balances::free_balance(¶_account_id(1)), - INITIAL_BALANCE + amount - ); - }); - - ParaA::execute_with(|| { - // ALICE gets amount - fee - assert_eq!( - parachain::Assets::balance(relay_asset_id, &ALICE.into()), - amount - fee - ); - // Fee sink gets fee - assert_eq!( - parachain::Assets::balance(relay_asset_id, AssetManager::account_id()), - fee - ); - }); + MockNet::reset(); + + let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); + let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1, None, false, true); + + let amount = 666u128; + // We charge 10^9 as units per second on ParaA + let units_per_second = 1_000_000_000u128; + let fee = calculate_fee(units_per_second, RESERVE_TRANSFER_WEIGHT); + assert!(fee > 0); + + // Register relaychain native asset in ParaA + let relay_asset_id = register_assets_on_parachain::( + &source_location, + &asset_metadata, + Some(units_per_second), + None, + ); + + let dest: MultiLocation = AccountId32 { + network: Any, + id: ALICE.into(), + } + .into(); + + Relay::execute_with(|| { + assert_ok!(RelayChainPalletXcm::reserve_transfer_assets( + relay_chain::Origin::signed(ALICE), + Box::new(X1(Parachain(1)).into().into()), + Box::new(VersionedMultiLocation::V1(dest)), + Box::new((Here, amount).into()), + 0, + )); + assert_eq!( + relay_chain::Balances::free_balance(¶_account_id(1)), + INITIAL_BALANCE + amount + ); + }); + + ParaA::execute_with(|| { + // ALICE gets amount - fee + assert_eq!( + parachain::Assets::balance(relay_asset_id, &ALICE), + amount - fee + ); + // Fee sink gets fee + assert_eq!( + parachain::Assets::balance(relay_asset_id, AssetManager::account_id()), + fee + ); + }); } #[test] fn send_para_a_asset_to_para_b_with_trader_and_fee() { - MockNet::reset(); - - // para a balance location - let para_a_id = 1; - let para_b_id = 2; - let para_a_source_location = create_asset_location(1, para_a_id); - let para_b_source_location = create_asset_location(1, para_b_id); - - let amount = 222u128; - let units_per_second = 1_250_000u128; - let dest_weight = 800_000u64; - let fee = calculate_fee(units_per_second, dest_weight); - - let para_a_asset_metadata = - create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, true); - let para_b_asset_metadata = - create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, true); - - // Register ParaA native asset in ParaA - let a_currency_id = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(0u128), - None, - ); - // register ParaB native asset on ParaA - let _ = register_assets_on_parachain::( - ¶_b_source_location, - ¶_b_asset_metadata, - Some(0u128), - None, - ); - - // register ParaA native asset on ParaB - let _ = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(units_per_second), - None, - ); - - let dest = MultiLocation { - parents: 1, - interior: X2( - Parachain(2), - AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }, - ), - }; - - // Transfer ParaA balance to B - ParaA::execute_with(|| { - assert_ok!(parachain::XTokens::transfer_with_fee( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(a_currency_id), - amount, - 1, - Box::new(VersionedMultiLocation::V1(dest)), - dest_weight, - )); - assert_eq!( - parachain::Balances::free_balance(&ALICE.into()), - INITIAL_BALANCE - amount - fee - ) - }); - - ParaB::execute_with(|| { - assert_eq!( - parachain::Assets::balance(a_currency_id, &ALICE.into()), - amount - ); - }); + MockNet::reset(); + + // para a balance location + let para_a_id = 1; + let para_b_id = 2; + let para_a_source_location = create_asset_location(1, para_a_id); + let para_b_source_location = create_asset_location(1, para_b_id); + + let amount = 222u128; + let units_per_second = 1_250_000u128; + let dest_weight = 800_000u64; + let fee = calculate_fee(units_per_second, dest_weight); + + let para_a_asset_metadata = + create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, true); + let para_b_asset_metadata = + create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, true); + + // Register ParaA native asset in ParaA + let a_currency_id = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(0u128), + None, + ); + // register ParaB native asset on ParaA + let _ = register_assets_on_parachain::( + ¶_b_source_location, + ¶_b_asset_metadata, + Some(0u128), + None, + ); + + // register ParaA native asset on ParaB + let _ = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(units_per_second), + None, + ); + + let dest = MultiLocation { + parents: 1, + interior: X2( + Parachain(2), + AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }, + ), + }; + + // Transfer ParaA balance to B + ParaA::execute_with(|| { + assert_ok!(parachain::XTokens::transfer_with_fee( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(a_currency_id), + amount, + 1, + Box::new(VersionedMultiLocation::V1(dest)), + dest_weight, + )); + assert_eq!( + parachain::Balances::free_balance(&ALICE), + INITIAL_BALANCE - amount - fee + ) + }); + + ParaB::execute_with(|| { + assert_eq!(parachain::Assets::balance(a_currency_id, &ALICE), amount); + }); } #[test] fn send_para_a_asset_from_para_b_to_para_c_with_trader() { - MockNet::reset(); - - // para a balance location - let para_a_id = 1; - let para_b_id = 2; - let para_c_id = 3; - let para_a_source_location = create_asset_location(1, para_a_id); - let para_b_source_location = create_asset_location(1, para_b_id); - let para_c_source_location = create_asset_location(1, para_c_id); - - let mut amount = 8888u128; - let units_per_second_at_b = 1_250_000u128; - let dest_weight = 800_000u64; - let fee_at_b = calculate_fee(units_per_second_at_b, dest_weight); - let fee_at_a = calculate_fee(ParaTokenPerSecond::get().1, dest_weight); - - let para_a_asset_metadata = - create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, true); - let para_b_asset_metadata = - create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, true); - let para_c_asset_metadata = - create_asset_metadata("ParaCToken", "ParaC", 18, 1, None, false, true); - - // register a_currency in ParaA, ParaB and ParaC - - // we don't charge any fee in A - // Register ParaA native asset in ParaA - let a_currency_id_on_a = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(0u128), - None, - ); - // register ParaB native asset on ParaA - let _ = register_assets_on_parachain::( - ¶_b_source_location, - ¶_b_asset_metadata, - Some(0u128), - None, - ); - - // We set units_per_seconds on ParaB to 1_250_000, - // register ParaA native asset on ParaB - let _ = register_assets_on_parachain::( - ¶_c_source_location, - ¶_c_asset_metadata, - Some(units_per_second_at_b), - None, - ); - let a_currency_id_on_b = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(units_per_second_at_b), - None, - ); - - let a_currency_id_on_c = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(units_per_second_at_b), - None, - ); - - // A send B some token - let alice_on_b = MultiLocation { - parents: 1, - interior: X2( - Parachain(2), - AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }, - ), - }; - - assert!(amount >= fee_at_b); - ParaA::execute_with(|| { - assert_ok!(parachain::XTokens::transfer( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(a_currency_id_on_a), - amount, - Box::new(VersionedMultiLocation::V1(alice_on_b.clone())), - dest_weight - )); - assert_eq!( - parachain::Balances::free_balance(&ALICE.into()), - INITIAL_BALANCE - amount - ) - }); - - ParaB::execute_with(|| { - assert_eq!(parachain::Assets::total_supply(a_currency_id_on_b), amount); - amount = amount - fee_at_b; - assert_eq!( - parachain::Assets::balance(a_currency_id_on_b, &ALICE.into()), - amount - ); - }); - - // B send C para A asset - let alice_on_c = MultiLocation { - parents: 1, - interior: X2( - Parachain(3), - AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }, - ), - }; - - assert!(amount >= fee_at_b + fee_at_a); - ParaB::execute_with(|| { - assert_ok!(parachain::XTokens::transfer( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(a_currency_id_on_b), - amount, - Box::new(VersionedMultiLocation::V1(alice_on_c)), - dest_weight - )); - assert_eq!( - parachain::Assets::balance(a_currency_id_on_b, &ALICE.into()), - 0 - ); - }); - - // Make sure C received the token - ParaC::execute_with(|| { - amount = amount - fee_at_b - fee_at_a; - assert_eq!( - parachain::Assets::balance(a_currency_id_on_c, &ALICE.into()), - amount - ); - }); + MockNet::reset(); + + // para a balance location + let para_a_id = 1; + let para_b_id = 2; + let para_c_id = 3; + let para_a_source_location = create_asset_location(1, para_a_id); + let para_b_source_location = create_asset_location(1, para_b_id); + let para_c_source_location = create_asset_location(1, para_c_id); + + let mut amount = 8888u128; + let units_per_second_at_b = 1_250_000u128; + let dest_weight = 800_000u64; + let fee_at_b = calculate_fee(units_per_second_at_b, dest_weight); + let fee_at_a = calculate_fee(ParaTokenPerSecond::get().1, dest_weight); + + let para_a_asset_metadata = + create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, true); + let para_b_asset_metadata = + create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, true); + let para_c_asset_metadata = + create_asset_metadata("ParaCToken", "ParaC", 18, 1, None, false, true); + + // register a_currency in ParaA, ParaB and ParaC + + // we don't charge any fee in A + // Register ParaA native asset in ParaA + let a_currency_id_on_a = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(0u128), + None, + ); + // register ParaB native asset on ParaA + let _ = register_assets_on_parachain::( + ¶_b_source_location, + ¶_b_asset_metadata, + Some(0u128), + None, + ); + + // We set units_per_seconds on ParaB to 1_250_000, + // register ParaA native asset on ParaB + let _ = register_assets_on_parachain::( + ¶_c_source_location, + ¶_c_asset_metadata, + Some(units_per_second_at_b), + None, + ); + let a_currency_id_on_b = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(units_per_second_at_b), + None, + ); + + let a_currency_id_on_c = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(units_per_second_at_b), + None, + ); + + // A send B some token + let alice_on_b = MultiLocation { + parents: 1, + interior: X2( + Parachain(2), + AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }, + ), + }; + + assert!(amount >= fee_at_b); + ParaA::execute_with(|| { + assert_ok!(parachain::XTokens::transfer( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(a_currency_id_on_a), + amount, + Box::new(VersionedMultiLocation::V1(alice_on_b.clone())), + dest_weight + )); + assert_eq!( + parachain::Balances::free_balance(&ALICE), + INITIAL_BALANCE - amount + ) + }); + + ParaB::execute_with(|| { + assert_eq!(parachain::Assets::total_supply(a_currency_id_on_b), amount); + amount -= fee_at_b; + assert_eq!( + parachain::Assets::balance(a_currency_id_on_b, &ALICE), + amount + ); + }); + + // B send C para A asset + let alice_on_c = MultiLocation { + parents: 1, + interior: X2( + Parachain(3), + AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }, + ), + }; + + assert!(amount >= fee_at_b + fee_at_a); + ParaB::execute_with(|| { + assert_ok!(parachain::XTokens::transfer( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(a_currency_id_on_b), + amount, + Box::new(VersionedMultiLocation::V1(alice_on_c)), + dest_weight + )); + assert_eq!(parachain::Assets::balance(a_currency_id_on_b, &ALICE), 0); + }); + + // Make sure C received the token + ParaC::execute_with(|| { + amount = amount - fee_at_b - fee_at_a; + assert_eq!( + parachain::Assets::balance(a_currency_id_on_c, &ALICE), + amount + ); + }); } #[test] fn receive_relay_with_insufficient_fee_payment() { - MockNet::reset(); - - let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); - let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1, None, false, true); - - let amount = 20u128; - // We charge 2 x 10^10 as units per second on ParaA - let units_per_second = 20_000_000_000u128; - let fee = calculate_fee(units_per_second, RESERVE_TRANSFER_WEIGHT); - assert!(fee > amount); - - // Register relaychain native asset in ParaA - let relay_asset_id = register_assets_on_parachain::( - &source_location, - &asset_metadata, - Some(units_per_second), - None, - ); - - let dest: MultiLocation = AccountId32 { - network: Any, - id: ALICE.into(), - } - .into(); - - Relay::execute_with(|| { - assert_ok!(RelayChainPalletXcm::reserve_transfer_assets( - relay_chain::Origin::signed(ALICE), - Box::new(X1(Parachain(1)).into().into()), - Box::new(VersionedMultiLocation::V1(dest).clone().into()), - Box::new((Here, amount).into()), - 0, - )); - assert_eq!( - relay_chain::Balances::free_balance(¶_account_id(1)), - INITIAL_BALANCE + amount - ); - }); - - ParaA::execute_with(|| { - // ALICE gets nothing - assert_eq!(parachain::Assets::balance(relay_asset_id, &ALICE.into()), 0); - // Asset manager gets nothing, all balance stuck - assert_eq!( - parachain::Assets::balance(relay_asset_id, AssetManager::account_id()), - 0 - ); - }); + MockNet::reset(); + + let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); + let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1, None, false, true); + + let amount = 20u128; + // We charge 2 x 10^10 as units per second on ParaA + let units_per_second = 20_000_000_000u128; + let fee = calculate_fee(units_per_second, RESERVE_TRANSFER_WEIGHT); + assert!(fee > amount); + + // Register relaychain native asset in ParaA + let relay_asset_id = register_assets_on_parachain::( + &source_location, + &asset_metadata, + Some(units_per_second), + None, + ); + + let dest: MultiLocation = AccountId32 { + network: Any, + id: ALICE.into(), + } + .into(); + + Relay::execute_with(|| { + assert_ok!(RelayChainPalletXcm::reserve_transfer_assets( + relay_chain::Origin::signed(ALICE), + Box::new(X1(Parachain(1)).into().into()), + Box::new(VersionedMultiLocation::V1(dest)), + Box::new((Here, amount).into()), + 0, + )); + assert_eq!( + relay_chain::Balances::free_balance(¶_account_id(1)), + INITIAL_BALANCE + amount + ); + }); + + ParaA::execute_with(|| { + // ALICE gets nothing + assert_eq!(parachain::Assets::balance(relay_asset_id, &ALICE), 0); + // Asset manager gets nothing, all balance stuck + assert_eq!( + parachain::Assets::balance(relay_asset_id, AssetManager::account_id()), + 0 + ); + }); } #[test] fn receive_relay_should_fail_without_specifying_units_per_second() { - MockNet::reset(); - - let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); - let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1, None, false, true); - let amount = 333u128; - - // Register relaychain native asset in ParaA - let relay_asset_id = - register_assets_on_parachain::(&source_location, &asset_metadata, None, None); - - let dest: MultiLocation = AccountId32 { - network: Any, - id: ALICE.into(), - } - .into(); - - Relay::execute_with(|| { - assert_ok!(RelayChainPalletXcm::reserve_transfer_assets( - relay_chain::Origin::signed(ALICE), - Box::new(X1(Parachain(1)).into().into()), - Box::new(VersionedMultiLocation::V1(dest).clone().into()), - Box::new((Here, amount).into()), - 0, - )); - assert_eq!( - relay_chain::Balances::free_balance(¶_account_id(1)), - INITIAL_BALANCE + amount - ); - }); - - ParaA::execute_with(|| { - // ALICE gets nothing - assert_eq!(parachain::Assets::balance(relay_asset_id, &ALICE.into()), 0); - // Asset manager gets nothing, all balance stuck - assert_eq!( - parachain::Assets::balance(relay_asset_id, AssetManager::account_id()), - 0 - ); - }); + MockNet::reset(); + + let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); + let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1, None, false, true); + let amount = 333u128; + + // Register relaychain native asset in ParaA + let relay_asset_id = + register_assets_on_parachain::(&source_location, &asset_metadata, None, None); + + let dest: MultiLocation = AccountId32 { + network: Any, + id: ALICE.into(), + } + .into(); + + Relay::execute_with(|| { + assert_ok!(RelayChainPalletXcm::reserve_transfer_assets( + relay_chain::Origin::signed(ALICE), + Box::new(X1(Parachain(1)).into().into()), + Box::new(VersionedMultiLocation::V1(dest)), + Box::new((Here, amount).into()), + 0, + )); + assert_eq!( + relay_chain::Balances::free_balance(¶_account_id(1)), + INITIAL_BALANCE + amount + ); + }); + + ParaA::execute_with(|| { + // ALICE gets nothing + assert_eq!(parachain::Assets::balance(relay_asset_id, &ALICE), 0); + // Asset manager gets nothing, all balance stuck + assert_eq!( + parachain::Assets::balance(relay_asset_id, AssetManager::account_id()), + 0 + ); + }); } #[test] fn send_para_a_asset_to_para_b_with_insufficient_fee() { - MockNet::reset(); - - // para a balance location - let para_a_id = 1; - let para_b_id = 2; - let para_a_source_location = create_asset_location(1, para_a_id); - let para_b_source_location = create_asset_location(1, para_b_id); - - let amount = 15u128; - let units_per_second = 20_000_000u128; - let dest_weight = 800_000u64; - let fee = calculate_fee(units_per_second, dest_weight); - assert!(fee > amount); - - let para_a_asset_metadata = - create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, true); - let para_b_asset_metadata = - create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, true); - - // Register ParaA native asset in ParaA - let a_currency_id = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(0u128), - None, - ); - // register ParaB native asset on ParaA - let _ = register_assets_on_parachain::( - ¶_b_source_location, - ¶_b_asset_metadata, - Some(0u128), - None, - ); - - // register ParaA native asset on ParaB - let _ = register_assets_on_parachain::( - ¶_b_source_location, - ¶_b_asset_metadata, - Some(units_per_second), - None, - ); - - let dest = MultiLocation { - parents: 1, - interior: X2( - Parachain(2), - AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }, - ), - }; - - // Transfer ParaA balance to B - ParaA::execute_with(|| { - assert_ok!(parachain::XTokens::transfer( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(a_currency_id), - amount, - Box::new(VersionedMultiLocation::V1(dest)), - dest_weight, - )); - assert_eq!( - parachain::Balances::free_balance(&ALICE.into()), - INITIAL_BALANCE - amount - ) - }); - - // Alice on B should receive nothing since the fee is insufficient - ParaB::execute_with(|| { - assert_eq!(parachain::Assets::balance(a_currency_id, &ALICE.into()), 0); - }); + MockNet::reset(); + + // para a balance location + let para_a_id = 1; + let para_b_id = 2; + let para_a_source_location = create_asset_location(1, para_a_id); + let para_b_source_location = create_asset_location(1, para_b_id); + + let amount = 15u128; + let units_per_second = 20_000_000u128; + let dest_weight = 800_000u64; + let fee = calculate_fee(units_per_second, dest_weight); + assert!(fee > amount); + + let para_a_asset_metadata = + create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, true); + let para_b_asset_metadata = + create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, true); + + // Register ParaA native asset in ParaA + let a_currency_id = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(0u128), + None, + ); + // register ParaB native asset on ParaA + let _ = register_assets_on_parachain::( + ¶_b_source_location, + ¶_b_asset_metadata, + Some(0u128), + None, + ); + + // register ParaA native asset on ParaB + let _ = register_assets_on_parachain::( + ¶_b_source_location, + ¶_b_asset_metadata, + Some(units_per_second), + None, + ); + + let dest = MultiLocation { + parents: 1, + interior: X2( + Parachain(2), + AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }, + ), + }; + + // Transfer ParaA balance to B + ParaA::execute_with(|| { + assert_ok!(parachain::XTokens::transfer( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(a_currency_id), + amount, + Box::new(VersionedMultiLocation::V1(dest)), + dest_weight, + )); + assert_eq!( + parachain::Balances::free_balance(&ALICE), + INITIAL_BALANCE - amount + ) + }); + + // Alice on B should receive nothing since the fee is insufficient + ParaB::execute_with(|| { + assert_eq!(parachain::Assets::balance(a_currency_id, &ALICE), 0); + }); } #[test] fn send_para_a_asset_to_para_b_without_specifying_units_per_second() { - MockNet::reset(); - - // para a balance location - let para_a_id = 1; - let para_b_id = 2; - let para_a_source_location = create_asset_location(1, para_a_id); - let para_b_source_location = create_asset_location(1, para_b_id); - - let amount = 567u128; - let dest_weight = 800_000u64; - - let para_a_asset_metadata = - create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, true); - let para_b_asset_metadata = - create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, true); - - // Register ParaA native asset in ParaA - // Register ParaA native asset in ParaA - let a_currency_id = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(0u128), - None, - ); - // register ParaB native asset on ParaA - let _ = register_assets_on_parachain::( - ¶_b_source_location, - ¶_b_asset_metadata, - Some(0u128), - None, - ); - - // register ParaA native asset on ParaB - let _ = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - None, - None, - ); - - let dest = MultiLocation { - parents: 1, - interior: X2( - Parachain(2), - AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }, - ), - }; - - // Transfer ParaA balance to B - ParaA::execute_with(|| { - assert_ok!(parachain::XTokens::transfer( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(a_currency_id), - amount, - Box::new(VersionedMultiLocation::V1(dest)), - dest_weight, - )); - assert_eq!( - parachain::Balances::free_balance(&ALICE.into()), - INITIAL_BALANCE - amount - ) - }); - - // Alice on B should receive nothing since we didn't specify the unit per second - ParaB::execute_with(|| { - assert_eq!(parachain::Assets::balance(a_currency_id, &ALICE.into()), 0); - }); + MockNet::reset(); + + // para a balance location + let para_a_id = 1; + let para_b_id = 2; + let para_a_source_location = create_asset_location(1, para_a_id); + let para_b_source_location = create_asset_location(1, para_b_id); + + let amount = 567u128; + let dest_weight = 800_000u64; + + let para_a_asset_metadata = + create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, true); + let para_b_asset_metadata = + create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, true); + + // Register ParaA native asset in ParaA + // Register ParaA native asset in ParaA + let a_currency_id = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(0u128), + None, + ); + // register ParaB native asset on ParaA + let _ = register_assets_on_parachain::( + ¶_b_source_location, + ¶_b_asset_metadata, + Some(0u128), + None, + ); + + // register ParaA native asset on ParaB + let _ = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + None, + None, + ); + + let dest = MultiLocation { + parents: 1, + interior: X2( + Parachain(2), + AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }, + ), + }; + + // Transfer ParaA balance to B + ParaA::execute_with(|| { + assert_ok!(parachain::XTokens::transfer( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(a_currency_id), + amount, + Box::new(VersionedMultiLocation::V1(dest)), + dest_weight, + )); + assert_eq!( + parachain::Balances::free_balance(&ALICE), + INITIAL_BALANCE - amount + ) + }); + + // Alice on B should receive nothing since we didn't specify the unit per second + ParaB::execute_with(|| { + assert_eq!(parachain::Assets::balance(a_currency_id, &ALICE), 0); + }); } #[test] fn receive_asset_with_is_sufficient_false() { - MockNet::reset(); - - let new_account = [5u8; 32]; - let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); - let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1, None, false, false); - let amount = 123u128; - - // register relay asset in parachain A - let relay_asset_id = - register_assets_on_parachain::(&source_location, &asset_metadata, Some(0u128), None); - - let dest: MultiLocation = AccountId32 { - network: Any, - id: new_account.into(), - } - .into(); - - Relay::execute_with(|| { - assert_ok!(RelayChainPalletXcm::reserve_transfer_assets( - relay_chain::Origin::signed(ALICE), - Box::new(X1(Parachain(1)).into().into()), - Box::new(VersionedMultiLocation::V1(dest.clone()).clone().into()), - Box::new((Here, amount).into()), - 0, - )); - assert_eq!( - relay_chain::Balances::free_balance(¶_account_id(1)), - INITIAL_BALANCE + amount - ); - }); - - // parachain should not have received assets - ParaA::execute_with(|| { - assert_eq!( - parachain::Assets::balance(relay_asset_id, &new_account.into()), - 0 - ); - }); - - // Send native token to fresh_account - ParaA::execute_with(|| { - assert_ok!(parachain::Balances::transfer( - parachain::Origin::signed(ALICE.into()), - new_account.into(), - 100 - )); - }); - - Relay::execute_with(|| { - assert_ok!(RelayChainPalletXcm::reserve_transfer_assets( - relay_chain::Origin::signed(ALICE), - Box::new(X1(Parachain(1)).into().into()), - Box::new(VersionedMultiLocation::V1(dest).clone().into()), - Box::new((Here, amount).into()), - 0, - )); - assert_eq!( - relay_chain::Balances::free_balance(¶_account_id(1)), - INITIAL_BALANCE + amount + amount - ); - }); - - // parachain should not have received assets - ParaA::execute_with(|| { - println!( - "fresh account bal: {}", - parachain::Assets::balance(relay_asset_id, &new_account.into()) - ); - }); + MockNet::reset(); + + let new_account = [5u8; 32]; + let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); + let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1, None, false, false); + let amount = 123u128; + + // register relay asset in parachain A + let relay_asset_id = + register_assets_on_parachain::(&source_location, &asset_metadata, Some(0u128), None); + + let dest: MultiLocation = AccountId32 { + network: Any, + id: new_account, + } + .into(); + + Relay::execute_with(|| { + assert_ok!(RelayChainPalletXcm::reserve_transfer_assets( + relay_chain::Origin::signed(ALICE), + Box::new(X1(Parachain(1)).into().into()), + Box::new(VersionedMultiLocation::V1(dest.clone())), + Box::new((Here, amount).into()), + 0, + )); + assert_eq!( + relay_chain::Balances::free_balance(¶_account_id(1)), + INITIAL_BALANCE + amount + ); + }); + + // parachain should not have received assets + ParaA::execute_with(|| { + assert_eq!( + parachain::Assets::balance(relay_asset_id, &new_account.into()), + 0 + ); + }); + + // Send native token to fresh_account + ParaA::execute_with(|| { + assert_ok!(parachain::Balances::transfer( + parachain::Origin::signed(ALICE), + new_account.into(), + 100 + )); + }); + + Relay::execute_with(|| { + assert_ok!(RelayChainPalletXcm::reserve_transfer_assets( + relay_chain::Origin::signed(ALICE), + Box::new(X1(Parachain(1)).into().into()), + Box::new(VersionedMultiLocation::V1(dest)), + Box::new((Here, amount).into()), + 0, + )); + assert_eq!( + relay_chain::Balances::free_balance(¶_account_id(1)), + INITIAL_BALANCE + amount + amount + ); + }); + + // parachain should not have received assets + ParaA::execute_with(|| { + println!( + "fresh account bal: {}", + parachain::Assets::balance(relay_asset_id, &new_account.into()) + ); + }); } #[test] fn receive_asset_with_is_sufficient_true() { - MockNet::reset(); - - let new_account = [5u8; 32]; - let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); - let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1, None, false, true); - let amount = 123u128; - - // register relay asset in parachain A - let relay_asset_id = - register_assets_on_parachain::(&source_location, &asset_metadata, Some(0u128), None); - - let dest: MultiLocation = AccountId32 { - network: Any, - id: new_account.into(), - } - .into(); - - Relay::execute_with(|| { - assert_ok!(RelayChainPalletXcm::reserve_transfer_assets( - relay_chain::Origin::signed(ALICE), - Box::new(X1(Parachain(1)).into().into()), - Box::new(VersionedMultiLocation::V1(dest.clone()).clone().into()), - Box::new((Here, amount).into()), - 0, - )); - assert_eq!( - relay_chain::Balances::free_balance(¶_account_id(1)), - INITIAL_BALANCE + amount - ); - }); - - // parachain should have received assets - ParaA::execute_with(|| { - assert_eq!( - parachain::Assets::balance(relay_asset_id, &new_account.into()), - amount - ); - }); + MockNet::reset(); + + let new_account = [5u8; 32]; + let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); + let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1, None, false, true); + let amount = 123u128; + + // register relay asset in parachain A + let relay_asset_id = + register_assets_on_parachain::(&source_location, &asset_metadata, Some(0u128), None); + + let dest: MultiLocation = AccountId32 { + network: Any, + id: new_account, + } + .into(); + + Relay::execute_with(|| { + assert_ok!(RelayChainPalletXcm::reserve_transfer_assets( + relay_chain::Origin::signed(ALICE), + Box::new(X1(Parachain(1)).into().into()), + Box::new(VersionedMultiLocation::V1(dest.clone())), + Box::new((Here, amount).into()), + 0, + )); + assert_eq!( + relay_chain::Balances::free_balance(¶_account_id(1)), + INITIAL_BALANCE + amount + ); + }); + + // parachain should have received assets + ParaA::execute_with(|| { + assert_eq!( + parachain::Assets::balance(relay_asset_id, &new_account.into()), + amount + ); + }); } /// Scenario: @@ -1443,34 +1428,34 @@ fn receive_asset_with_is_sufficient_true() { /// Asserts that the parachain accounts are updated as expected. #[test] fn withdraw_and_deposit() { - MockNet::reset(); - - let send_amount = 10; - - ParaA::execute_with(|| { - let message = Xcm(vec![ - WithdrawAsset((Here, send_amount).into()), - buy_execution((Here, send_amount)), - DepositAsset { - assets: All.into(), - max_assets: 1, - beneficiary: Parachain(2).into(), - }, - ]); - // Send withdraw and deposit - assert_ok!(ParachainPalletXcm::send_xcm(Here, Parent, message.clone())); - }); - - Relay::execute_with(|| { - assert_eq!( - relay_chain::Balances::free_balance(para_account_id(1)), - INITIAL_BALANCE - send_amount - ); - assert_eq!( - relay_chain::Balances::free_balance(para_account_id(2)), - send_amount - ); - }); + MockNet::reset(); + + let send_amount = 10; + + ParaA::execute_with(|| { + let message = Xcm(vec![ + WithdrawAsset((Here, send_amount).into()), + buy_execution((Here, send_amount)), + DepositAsset { + assets: All.into(), + max_assets: 1, + beneficiary: Parachain(2).into(), + }, + ]); + // Send withdraw and deposit + assert_ok!(ParachainPalletXcm::send_xcm(Here, Parent, message)); + }); + + Relay::execute_with(|| { + assert_eq!( + relay_chain::Balances::free_balance(para_account_id(1)), + INITIAL_BALANCE - send_amount + ); + assert_eq!( + relay_chain::Balances::free_balance(para_account_id(2)), + send_amount + ); + }); } /// Scenario: @@ -1480,697 +1465,694 @@ fn withdraw_and_deposit() { /// Asserts that the balances are updated correctly and the expected XCM is sent. #[test] fn query_holding() { - MockNet::reset(); - - let send_amount = 10; - let query_id_set = 1234; - - // Send a message which fully succeeds on the relay chain - ParaA::execute_with(|| { - let message = Xcm(vec![ - WithdrawAsset((Here, send_amount).into()), - buy_execution((Here, send_amount)), - DepositAsset { - assets: All.into(), - max_assets: 1, - beneficiary: Parachain(2).into(), - }, - QueryHolding { - query_id: query_id_set, - dest: Parachain(1).into(), - assets: All.into(), - max_response_weight: 1_000_000_000, - }, - ]); - // Send withdraw and deposit with query holding - assert_ok!(ParachainPalletXcm::send_xcm(Here, Parent, message.clone(),)); - }); - - // Check that transfer was executed - Relay::execute_with(|| { - // Withdraw executed - assert_eq!( - relay_chain::Balances::free_balance(para_account_id(1)), - INITIAL_BALANCE - send_amount - ); - // Deposit executed - assert_eq!( - relay_chain::Balances::free_balance(para_account_id(2)), - send_amount - ); - }); - - // Check that QueryResponse message was received - ParaA::execute_with(|| { - assert_eq!( - parachain::MsgQueue::received_dmp(), - vec![Xcm(vec![QueryResponse { - query_id: query_id_set, - response: Response::Assets(MultiAssets::new()), - max_weight: 1_000_000_000, - }])], - ); - }); + MockNet::reset(); + + let send_amount = 10; + let query_id_set = 1234; + + // Send a message which fully succeeds on the relay chain + ParaA::execute_with(|| { + let message = Xcm(vec![ + WithdrawAsset((Here, send_amount).into()), + buy_execution((Here, send_amount)), + DepositAsset { + assets: All.into(), + max_assets: 1, + beneficiary: Parachain(2).into(), + }, + QueryHolding { + query_id: query_id_set, + dest: Parachain(1).into(), + assets: All.into(), + max_response_weight: 1_000_000_000, + }, + ]); + // Send withdraw and deposit with query holding + assert_ok!(ParachainPalletXcm::send_xcm(Here, Parent, message,)); + }); + + // Check that transfer was executed + Relay::execute_with(|| { + // Withdraw executed + assert_eq!( + relay_chain::Balances::free_balance(para_account_id(1)), + INITIAL_BALANCE - send_amount + ); + // Deposit executed + assert_eq!( + relay_chain::Balances::free_balance(para_account_id(2)), + send_amount + ); + }); + + // Check that QueryResponse message was received + ParaA::execute_with(|| { + assert_eq!( + parachain::MsgQueue::received_dmp(), + vec![Xcm(vec![QueryResponse { + query_id: query_id_set, + response: Response::Assets(MultiAssets::new()), + max_weight: 1_000_000_000, + }])], + ); + }); } #[test] fn test_versioning_on_runtime_upgrade_with_relay() { - MockNet::reset(); - - let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); - let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1, None, false, true); - - // register relay asset in parachain A (XCM version 1) - ParaA::execute_with(|| { - // SelfReserve - parachain::set_current_xcm_version(1); - }); - let _ = - register_assets_on_parachain::(&source_location, &asset_metadata, Some(0u128), None); - - let response = Response::Version(2); - - // This is irrelevant, nothing will be done with this message, - // but we need to pass a message as an argument to trigger the storage change - let mock_message: Xcm<()> = Xcm(vec![QueryResponse { - query_id: 0, - response, - max_weight: 0, - }]); - - let dest: MultiLocation = AccountId32 { - network: Any, - id: ALICE.into(), - } - .into(); - - Relay::execute_with(|| { - // This sets the default version, for not known destinations - assert_ok!(RelayChainPalletXcm::force_default_xcm_version( - relay_chain::Origin::root(), - Some(2) - )); - - // Wrap version, which sets VersionedStorage - // This is necessary because the mock router does not use wrap_version, but - // this is not necessary in prod. - // more specifically, this will trigger `note_unknown_version` to put the - // version to `VersionDiscoveryQueue` on relay-chain's pallet-xcm - assert_ok!(::wrap_version( - &Parachain(1).into(), - mock_message - )); - - // Transfer assets. Since it is an unknown destination, it will query for version - assert_ok!(RelayChainPalletXcm::reserve_transfer_assets( - relay_chain::Origin::signed(ALICE), - Box::new(Parachain(1).into().into()), - Box::new(VersionedMultiLocation::V1(dest).clone().into()), - Box::new((Here, 123).into()), - 0, - )); - - // Let's advance the relay. This should trigger the subscription message - relay_chain::relay_roll_to(2); - - // queries should have been updated - assert!(RelayChainPalletXcm::query(0).is_some()); - }); - - let expected_supported_version: relay_chain::Event = - pallet_xcm::Event::SupportedVersionChanged( - MultiLocation { - parents: 0, - interior: X1(Parachain(1)), - }, - 1, - ) - .into(); - - Relay::execute_with(|| { - // Assert that the events vector contains the version change - assert!(relay_chain::relay_events().contains(&expected_supported_version)); - }); - - let expected_version_notified: parachain::Event = pallet_xcm::Event::VersionChangeNotified( - MultiLocation { - parents: 1, - interior: Here, - }, - 2, - ) - .into(); - - // ParaA changes version to 2, and calls on_runtime_upgrade. This should notify the targets - // of the new version change - ParaA::execute_with(|| { - // Set version - parachain::set_current_xcm_version(2); - // Do runtime upgrade - parachain::on_runtime_upgrade(); - // Initialize block, to call on_initialize and notify targets - parachain::para_roll_to(2); - // Expect the event in the parachain - assert!(parachain::para_events().contains(&expected_version_notified)); - }); - - // This event should have been seen in the relay - let expected_supported_version_2: relay_chain::Event = - pallet_xcm::Event::SupportedVersionChanged( - MultiLocation { - parents: 0, - interior: X1(Parachain(1)), - }, - 2, - ) - .into(); - - Relay::execute_with(|| { - // Assert that the events vector contains the new version change - assert!(relay_chain::relay_events().contains(&expected_supported_version_2)); - }); + MockNet::reset(); + + let source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); + let asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1, None, false, true); + + // register relay asset in parachain A (XCM version 1) + ParaA::execute_with(|| { + // SelfReserve + parachain::set_current_xcm_version(1); + }); + let _ = + register_assets_on_parachain::(&source_location, &asset_metadata, Some(0u128), None); + + let response = Response::Version(2); + + // This is irrelevant, nothing will be done with this message, + // but we need to pass a message as an argument to trigger the storage change + let mock_message: Xcm<()> = Xcm(vec![QueryResponse { + query_id: 0, + response, + max_weight: 0, + }]); + + let dest: MultiLocation = AccountId32 { + network: Any, + id: ALICE.into(), + } + .into(); + + Relay::execute_with(|| { + // This sets the default version, for not known destinations + assert_ok!(RelayChainPalletXcm::force_default_xcm_version( + relay_chain::Origin::root(), + Some(2) + )); + + // Wrap version, which sets VersionedStorage + // This is necessary because the mock router does not use wrap_version, but + // this is not necessary in prod. + // more specifically, this will trigger `note_unknown_version` to put the + // version to `VersionDiscoveryQueue` on relay-chain's pallet-xcm + assert_ok!(::wrap_version( + &Parachain(1).into(), + mock_message + )); + + // Transfer assets. Since it is an unknown destination, it will query for version + assert_ok!(RelayChainPalletXcm::reserve_transfer_assets( + relay_chain::Origin::signed(ALICE), + Box::new(Parachain(1).into().into()), + Box::new(VersionedMultiLocation::V1(dest)), + Box::new((Here, 123).into()), + 0, + )); + + // Let's advance the relay. This should trigger the subscription message + relay_chain::relay_roll_to(2); + + // queries should have been updated + assert!(RelayChainPalletXcm::query(0).is_some()); + }); + + let expected_supported_version: relay_chain::Event = + pallet_xcm::Event::SupportedVersionChanged( + MultiLocation { + parents: 0, + interior: X1(Parachain(1)), + }, + 1, + ) + .into(); + + Relay::execute_with(|| { + // Assert that the events vector contains the version change + assert!(relay_chain::relay_events().contains(&expected_supported_version)); + }); + + let expected_version_notified: parachain::Event = pallet_xcm::Event::VersionChangeNotified( + MultiLocation { + parents: 1, + interior: Here, + }, + 2, + ) + .into(); + + // ParaA changes version to 2, and calls on_runtime_upgrade. This should notify the targets + // of the new version change + ParaA::execute_with(|| { + // Set version + parachain::set_current_xcm_version(2); + // Do runtime upgrade + parachain::on_runtime_upgrade(); + // Initialize block, to call on_initialize and notify targets + parachain::para_roll_to(2); + // Expect the event in the parachain + assert!(parachain::para_events().contains(&expected_version_notified)); + }); + + // This event should have been seen in the relay + let expected_supported_version_2: relay_chain::Event = + pallet_xcm::Event::SupportedVersionChanged( + MultiLocation { + parents: 0, + interior: X1(Parachain(1)), + }, + 2, + ) + .into(); + + Relay::execute_with(|| { + // Assert that the events vector contains the new version change + assert!(relay_chain::relay_events().contains(&expected_supported_version_2)); + }); } #[test] fn test_automatic_versioning_on_runtime_upgrade_with_para_b() { - MockNet::reset(); - - // para a balance location - let para_a_id = 1; - let para_b_id = 2; - let para_a_source_location = create_asset_location(1, para_a_id); - let para_b_source_location = create_asset_location(1, para_b_id); - - let para_a_asset_metadata = - create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, true); - let para_b_asset_metadata = - create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, true); - let response = Response::Version(2); - - // This is irrelevant, nothing will be done with this message, - // but we need to pass a message as an argument to trigger the storage change - let mock_message: Xcm<()> = Xcm(vec![QueryResponse { - query_id: 0, - response, - max_weight: 0, - }]); - - ParaA::execute_with(|| { - // advertised version - parachain::set_current_xcm_version(2); - }); - - // Register ParaA native asset in ParaA - let a_currency_id = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(0u128), - None, - ); - - // register ParaB native asset on ParaA - let _ = register_assets_on_parachain::( - ¶_b_source_location, - ¶_b_asset_metadata, - Some(0u128), - None, - ); - - ParaB::execute_with(|| { - // advertised version - parachain::set_current_xcm_version(0); - }); - - // register ParaA native asset on ParaB - let _ = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(0u128), - None, - ); - - ParaA::execute_with(|| { - // This sets the default version, for not known destinations - assert_ok!(ParachainPalletXcm::force_default_xcm_version( - parachain::Origin::root(), - Some(2) - )); - // Wrap version, which sets VersionedStorage - assert_ok!(::wrap_version( - &MultiLocation::new(1, X1(Parachain(2))).into(), - mock_message - )); - - parachain::para_roll_to(2); - - // queries should have been updated - assert!(ParachainPalletXcm::query(0).is_some()); - }); - - let expected_supported_version: parachain::Event = pallet_xcm::Event::SupportedVersionChanged( - MultiLocation { - parents: 1, - interior: X1(Parachain(2)), - }, - 0, - ) - .into(); - - ParaA::execute_with(|| { - // Assert that the events vector contains the version change - assert!(parachain::para_events().contains(&expected_supported_version)); - }); - - // Let's ensure talking in v0 works - let dest = MultiLocation { - parents: 1, - interior: X2( - Parachain(2), - AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }, - ), - }; - - ParaA::execute_with(|| { - // free execution, full amount received - assert_ok!(parachain::XTokens::transfer( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(a_currency_id), - 100, - Box::new(VersionedMultiLocation::V1(dest)), - 80 - )); - // free execution, full amount received - assert_eq!( - parachain::Balances::free_balance(&ALICE.into()), - INITIAL_BALANCE - 100 - ); - }); - - ParaB::execute_with(|| { - // free execution, full amount received - assert_eq!( - parachain::Assets::balance(a_currency_id, &ALICE.into()), - 100 - ); - }); - - let expected_version_notified: parachain::Event = pallet_xcm::Event::VersionChangeNotified( - MultiLocation { - parents: 1, - interior: X1(Parachain(1)), - }, - 2, - ) - .into(); - - // ParaB changes version to 2, and calls on_runtime_upgrade. This should notify the targets - // of the new version change - ParaB::execute_with(|| { - // Set version - parachain::set_current_xcm_version(2); - // Do runtime upgrade - parachain::on_runtime_upgrade(); - // Initialize block, to call on_initialize and notify targets - parachain::para_roll_to(2); - // Expect the event in the parachain - assert!(parachain::para_events().contains(&expected_version_notified)); - }); - - // This event should have been seen in para A - let expected_supported_version_2: parachain::Event = - pallet_xcm::Event::SupportedVersionChanged( - MultiLocation { - parents: 1, - interior: X1(Parachain(2)), - }, - 2, - ) - .into(); - - // Para A should have received the version change - ParaA::execute_with(|| { - // Assert that the events vector contains the new version change - assert!(parachain::para_events().contains(&expected_supported_version_2)); - }); + MockNet::reset(); + + // para a balance location + let para_a_id = 1; + let para_b_id = 2; + let para_a_source_location = create_asset_location(1, para_a_id); + let para_b_source_location = create_asset_location(1, para_b_id); + + let para_a_asset_metadata = + create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, true); + let para_b_asset_metadata = + create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, true); + let response = Response::Version(2); + + // This is irrelevant, nothing will be done with this message, + // but we need to pass a message as an argument to trigger the storage change + let mock_message: Xcm<()> = Xcm(vec![QueryResponse { + query_id: 0, + response, + max_weight: 0, + }]); + + ParaA::execute_with(|| { + // advertised version + parachain::set_current_xcm_version(2); + }); + + // Register ParaA native asset in ParaA + let a_currency_id = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(0u128), + None, + ); + + // register ParaB native asset on ParaA + let _ = register_assets_on_parachain::( + ¶_b_source_location, + ¶_b_asset_metadata, + Some(0u128), + None, + ); + + ParaB::execute_with(|| { + // advertised version + parachain::set_current_xcm_version(0); + }); + + // register ParaA native asset on ParaB + let _ = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(0u128), + None, + ); + + ParaA::execute_with(|| { + // This sets the default version, for not known destinations + assert_ok!(ParachainPalletXcm::force_default_xcm_version( + parachain::Origin::root(), + Some(2) + )); + // Wrap version, which sets VersionedStorage + assert_ok!(::wrap_version( + &MultiLocation::new(1, X1(Parachain(2))), + mock_message + )); + + parachain::para_roll_to(2); + + // queries should have been updated + assert!(ParachainPalletXcm::query(0).is_some()); + }); + + let expected_supported_version: parachain::Event = pallet_xcm::Event::SupportedVersionChanged( + MultiLocation { + parents: 1, + interior: X1(Parachain(2)), + }, + 0, + ) + .into(); + + ParaA::execute_with(|| { + // Assert that the events vector contains the version change + assert!(parachain::para_events().contains(&expected_supported_version)); + }); + + // Let's ensure talking in v0 works + let dest = MultiLocation { + parents: 1, + interior: X2( + Parachain(2), + AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }, + ), + }; + + ParaA::execute_with(|| { + // free execution, full amount received + assert_ok!(parachain::XTokens::transfer( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(a_currency_id), + 100, + Box::new(VersionedMultiLocation::V1(dest)), + 80 + )); + // free execution, full amount received + assert_eq!( + parachain::Balances::free_balance(&ALICE), + INITIAL_BALANCE - 100 + ); + }); + + ParaB::execute_with(|| { + // free execution, full amount received + assert_eq!(parachain::Assets::balance(a_currency_id, &ALICE), 100); + }); + + let expected_version_notified: parachain::Event = pallet_xcm::Event::VersionChangeNotified( + MultiLocation { + parents: 1, + interior: X1(Parachain(1)), + }, + 2, + ) + .into(); + + // ParaB changes version to 2, and calls on_runtime_upgrade. This should notify the targets + // of the new version change + ParaB::execute_with(|| { + // Set version + parachain::set_current_xcm_version(2); + // Do runtime upgrade + parachain::on_runtime_upgrade(); + // Initialize block, to call on_initialize and notify targets + parachain::para_roll_to(2); + // Expect the event in the parachain + assert!(parachain::para_events().contains(&expected_version_notified)); + }); + + // This event should have been seen in para A + let expected_supported_version_2: parachain::Event = + pallet_xcm::Event::SupportedVersionChanged( + MultiLocation { + parents: 1, + interior: X1(Parachain(2)), + }, + 2, + ) + .into(); + + // Para A should have received the version change + ParaA::execute_with(|| { + // Assert that the events vector contains the new version change + assert!(parachain::para_events().contains(&expected_supported_version_2)); + }); } #[test] fn filtered_multilocation_should_not_work() { - let para_a_id = 1; - let para_b_id = 2; - let para_a_source_location = create_asset_location(1, para_a_id); - let para_b_source_location = create_asset_location(1, para_b_id); - let para_a_asset_metadata = - create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, true); - let para_b_asset_metadata = - create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, true); - - // Register ParaA native asset in ParaA - let a_currency_id = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(0u128), - None, - ); - // register ParaB native asset on ParaA - let _ = register_assets_on_parachain::( - ¶_b_source_location, - ¶_b_asset_metadata, - Some(0u128), - None, - ); - - // register ParaA native asset on ParaB - let _ = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(0u128), - None, - ); - - let dest = MultiLocation { - parents: 1, - interior: X2( - Parachain(4), // set para id as 4 - AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }, - ), - }; - - // Sending xcm to parachain 5 should not work - ParaA::execute_with(|| { - assert_noop!( - parachain::XTokens::transfer( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(a_currency_id), - 100, - Box::new(VersionedMultiLocation::V1(dest)), - 80 - ), - orml_xtokens::Error::::NotSupportedMultiLocation, - ); - }); - - let x3_dest = MultiLocation { - parents: 1, - interior: X3( - Parachain(2), - PalletInstance(PALLET_ASSET_INDEX), - AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }, - ), - }; - // We don't support X3 or more longer Junctions. - ParaA::execute_with(|| { - assert_noop!( - parachain::XTokens::transfer( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(a_currency_id), - 100, - Box::new(VersionedMultiLocation::V1(x3_dest)), - 80 - ), - orml_xtokens::Error::::NotSupportedMultiLocation, - ); - }); - - let parents_as_2_relay_dest = MultiLocation { - parents: 2, - interior: X1(AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }), - }; - // relaychain dest with wrong parents should not work. - ParaA::execute_with(|| { - assert_noop!( - parachain::XTokens::transfer( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(a_currency_id), - 100, - Box::new(VersionedMultiLocation::V1(parents_as_2_relay_dest)), - 80 - ), - orml_xtokens::Error::::NotSupportedMultiLocation, - ); - }); - - let parents_as_2_dest = MultiLocation { - parents: 2, - interior: X2( - Parachain(2), - AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }, - ), - }; - // Wrong parents should not work. - ParaA::execute_with(|| { - assert_noop!( - parachain::XTokens::transfer( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(a_currency_id), - 100, - Box::new(VersionedMultiLocation::V1(parents_as_2_dest)), - 80 - ), - orml_xtokens::Error::::NotSupportedMultiLocation, - ); - }); - - let here_dest = MultiLocation { - parents: 1, - interior: Here, - }; - // The destination with no receiver should not work. - ParaA::execute_with(|| { - assert_noop!( - parachain::XTokens::transfer( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(a_currency_id), - 100, - Box::new(VersionedMultiLocation::V1(here_dest)), - 80 - ), - orml_xtokens::Error::::NotSupportedMultiLocation, - ); - }); - - // Correct relaychain location should work, (1, Here) - let relay_dest = MultiLocation { - parents: 1, - interior: X1(AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }), - }; - ParaA::execute_with(|| { - assert_ok!(parachain::XTokens::transfer( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(a_currency_id), - 100, - Box::new(VersionedMultiLocation::V1(relay_dest)), - 80 - )); - }); - - // Correct sibling location should work - let sibling_chain_dest = MultiLocation { - parents: 1, - interior: X2( - Parachain(2), - AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }, - ), - }; - ParaA::execute_with(|| { - assert_ok!(parachain::XTokens::transfer( - parachain::Origin::signed(ALICE.into()), - parachain::CurrencyId::MantaCurrency(a_currency_id), - 100, - Box::new(VersionedMultiLocation::V1(sibling_chain_dest)), - 80 - )); - }); + let para_a_id = 1; + let para_b_id = 2; + let para_a_source_location = create_asset_location(1, para_a_id); + let para_b_source_location = create_asset_location(1, para_b_id); + let para_a_asset_metadata = + create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, true); + let para_b_asset_metadata = + create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, true); + + // Register ParaA native asset in ParaA + let a_currency_id = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(0u128), + None, + ); + // register ParaB native asset on ParaA + let _ = register_assets_on_parachain::( + ¶_b_source_location, + ¶_b_asset_metadata, + Some(0u128), + None, + ); + + // register ParaA native asset on ParaB + let _ = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(0u128), + None, + ); + + let dest = MultiLocation { + parents: 1, + interior: X2( + Parachain(4), // set para id as 4 + AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }, + ), + }; + + // Sending xcm to parachain 5 should not work + ParaA::execute_with(|| { + assert_noop!( + parachain::XTokens::transfer( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(a_currency_id), + 100, + Box::new(VersionedMultiLocation::V1(dest)), + 80 + ), + orml_xtokens::Error::::NotSupportedMultiLocation, + ); + }); + + let x3_dest = MultiLocation { + parents: 1, + interior: X3( + Parachain(2), + PalletInstance(PALLET_ASSET_INDEX), + AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }, + ), + }; + // We don't support X3 or more longer Junctions. + ParaA::execute_with(|| { + assert_noop!( + parachain::XTokens::transfer( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(a_currency_id), + 100, + Box::new(VersionedMultiLocation::V1(x3_dest)), + 80 + ), + orml_xtokens::Error::::NotSupportedMultiLocation, + ); + }); + + let parents_as_2_relay_dest = MultiLocation { + parents: 2, + interior: X1(AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }), + }; + // relaychain dest with wrong parents should not work. + ParaA::execute_with(|| { + assert_noop!( + parachain::XTokens::transfer( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(a_currency_id), + 100, + Box::new(VersionedMultiLocation::V1(parents_as_2_relay_dest)), + 80 + ), + orml_xtokens::Error::::NotSupportedMultiLocation, + ); + }); + + let parents_as_2_dest = MultiLocation { + parents: 2, + interior: X2( + Parachain(2), + AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }, + ), + }; + // Wrong parents should not work. + ParaA::execute_with(|| { + assert_noop!( + parachain::XTokens::transfer( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(a_currency_id), + 100, + Box::new(VersionedMultiLocation::V1(parents_as_2_dest)), + 80 + ), + orml_xtokens::Error::::NotSupportedMultiLocation, + ); + }); + + let here_dest = MultiLocation { + parents: 1, + interior: Here, + }; + // The destination with no receiver should not work. + ParaA::execute_with(|| { + assert_noop!( + parachain::XTokens::transfer( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(a_currency_id), + 100, + Box::new(VersionedMultiLocation::V1(here_dest)), + 80 + ), + orml_xtokens::Error::::NotSupportedMultiLocation, + ); + }); + + // Correct relaychain location should work, (1, Here) + let relay_dest = MultiLocation { + parents: 1, + interior: X1(AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }), + }; + ParaA::execute_with(|| { + assert_ok!(parachain::XTokens::transfer( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(a_currency_id), + 100, + Box::new(VersionedMultiLocation::V1(relay_dest)), + 80 + )); + }); + + // Correct sibling location should work + let sibling_chain_dest = MultiLocation { + parents: 1, + interior: X2( + Parachain(2), + AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }, + ), + }; + ParaA::execute_with(|| { + assert_ok!(parachain::XTokens::transfer( + parachain::Origin::signed(ALICE), + parachain::CurrencyId::MantaCurrency(a_currency_id), + 100, + Box::new(VersionedMultiLocation::V1(sibling_chain_dest)), + 80 + )); + }); } #[test] fn less_than_min_xcm_fee_should_not_work() { - MockNet::reset(); - - let para_a_id = 1; - let para_b_id = 2; - let para_a_source_location = create_asset_location(1, para_a_id); - let para_b_source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( - 1, - X2(Parachain(para_b_id), GeneralKey(b"ParaBToken".to_vec())), - ))); - let para_b_as_reserve_chain = create_asset_location(1, para_b_id); - - let para_a_asset_metadata = - create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, true); - let para_b_asset_metadata = - create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, true); - - let relay_source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); - let relay_asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1, None, false, true); - - // Register ParaA native asset in ParaA - let _a_currency_id_on_a = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(0u128), - None, - ); - // Register relaychain native asset in ParaA - let relay_asset_id_on_a = register_assets_on_parachain::( - &relay_source_location, - &relay_asset_metadata, - Some(0u128), - None, - ); - // register ParaB native asset on ParaA - let b_currency_id_on_a = register_assets_on_parachain::( - ¶_b_source_location, - ¶_b_asset_metadata, - Some(0u128), - None, - ); - - // register ParaA native asset on ParaB - let _ = register_assets_on_parachain::( - ¶_a_source_location, - ¶_a_asset_metadata, - Some(0u128), - None, - ); - // Register relaychain native asset in ParaA - let _relay_asset_id_on_b = register_assets_on_parachain::( - &relay_source_location, - &relay_asset_metadata, - Some(0u128), - None, - ); - - // Initlize some tokens for alice - assert_ok!(ParaA::execute_with(|| { - parachain::Assets::mint( - parachain::Origin::signed(parachain::AssetManager::account_id()), - b_currency_id_on_a, - ALICE.into(), - 1000, - ) - })); - assert_ok!(ParaA::execute_with(|| { - parachain::Assets::mint( - parachain::Origin::signed(parachain::AssetManager::account_id()), - relay_asset_id_on_a, - ALICE.into(), - 1000, - ) - })); - - let dest = MultiLocation { - parents: 1, - interior: X2( - Parachain(2), - AccountId32 { - network: NetworkId::Any, - id: ALICE.into(), - }, - ), - }; - - let amount = 450; - let fee_amount: u128 = 200; - // Minimum xcm execution fee paid on destination chain. - // Current only support `ToReserve` with relay-chain asset as fee. other case - // like `NonReserve` or `SelfReserve` with relay-chain fee is not support. - // And our `MaxAssetsForTransfer` for xtokens is 1, - // so `transfer_multicurrencies` is not supported on calamari. - // If min-xcm-fee is not set, no one can pay xcm fee(u129::MAX). - ParaA::execute_with(|| { - assert_noop!( - parachain::XTokens::transfer_multicurrencies( - Some(ALICE).into(), - vec![ - ( - parachain::CurrencyId::MantaCurrency(b_currency_id_on_a), - amount - ), - ( - parachain::CurrencyId::MantaCurrency(relay_asset_id_on_a), - fee_amount - ) - ], - 1, - Box::new(VersionedMultiLocation::V1(dest.clone())), - 40, - ), - orml_xtokens::Error::::FeeNotEnough - ); - }); - - // set min xcm fee on ParaA - let min_xcm_fee = 40; - ParaA::execute_with(|| { - assert_ok!(AssetManager::set_min_xcm_fee( - parachain::Origin::root(), - para_b_as_reserve_chain, - min_xcm_fee, - )); - }); - - // fee is bigger than min-xcm-fee should work(39 < 40). - ParaA::execute_with(|| { - assert_noop!( - parachain::XTokens::transfer_multicurrencies( - Some(ALICE).into(), - vec![ - ( - parachain::CurrencyId::MantaCurrency(b_currency_id_on_a), - amount - ), - ( - parachain::CurrencyId::MantaCurrency(relay_asset_id_on_a), - 39 - ) - ], - 1, - Box::new(VersionedMultiLocation::V1(dest.clone())), - 40, - ), - orml_xtokens::Error::::FeeNotEnough - ); - }); - - // fee is bigger than min-xcm-fee should work - ParaA::execute_with(|| { - assert_ok!(parachain::XTokens::transfer_multicurrencies( - Some(ALICE).into(), - vec![ - ( - parachain::CurrencyId::MantaCurrency(b_currency_id_on_a), - amount - ), - ( - parachain::CurrencyId::MantaCurrency(relay_asset_id_on_a), - fee_amount - ) - ], - 1, - Box::new(VersionedMultiLocation::V1(dest.clone())), - 40, - )); - }); + MockNet::reset(); + + let para_a_id = 1; + let para_b_id = 2; + let para_a_source_location = create_asset_location(1, para_a_id); + let para_b_source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::new( + 1, + X2(Parachain(para_b_id), GeneralKey(b"ParaBToken".to_vec())), + ))); + let para_b_as_reserve_chain = create_asset_location(1, para_b_id); + + let para_a_asset_metadata = + create_asset_metadata("ParaAToken", "ParaA", 18, 1, None, false, true); + let para_b_asset_metadata = + create_asset_metadata("ParaBToken", "ParaB", 18, 1, None, false, true); + + let relay_source_location = AssetLocation(VersionedMultiLocation::V1(MultiLocation::parent())); + let relay_asset_metadata = create_asset_metadata("Kusama", "KSM", 12, 1, None, false, true); + + // Register ParaA native asset in ParaA + let _a_currency_id_on_a = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(0u128), + None, + ); + // Register relaychain native asset in ParaA + let relay_asset_id_on_a = register_assets_on_parachain::( + &relay_source_location, + &relay_asset_metadata, + Some(0u128), + None, + ); + // register ParaB native asset on ParaA + let b_currency_id_on_a = register_assets_on_parachain::( + ¶_b_source_location, + ¶_b_asset_metadata, + Some(0u128), + None, + ); + + // register ParaA native asset on ParaB + let _ = register_assets_on_parachain::( + ¶_a_source_location, + ¶_a_asset_metadata, + Some(0u128), + None, + ); + // Register relaychain native asset in ParaA + let _relay_asset_id_on_b = register_assets_on_parachain::( + &relay_source_location, + &relay_asset_metadata, + Some(0u128), + None, + ); + + // Initlize some tokens for alice + assert_ok!(ParaA::execute_with(|| { + parachain::Assets::mint( + parachain::Origin::signed(parachain::AssetManager::account_id()), + b_currency_id_on_a, + ALICE, + 1000, + ) + })); + assert_ok!(ParaA::execute_with(|| { + parachain::Assets::mint( + parachain::Origin::signed(parachain::AssetManager::account_id()), + relay_asset_id_on_a, + ALICE, + 1000, + ) + })); + + let dest = MultiLocation { + parents: 1, + interior: X2( + Parachain(2), + AccountId32 { + network: NetworkId::Any, + id: ALICE.into(), + }, + ), + }; + + let amount = 450; + let fee_amount: u128 = 200; + // Minimum xcm execution fee paid on destination chain. + // Current only support `ToReserve` with relay-chain asset as fee. other case + // like `NonReserve` or `SelfReserve` with relay-chain fee is not support. + // And our `MaxAssetsForTransfer` for xtokens is 1, + // so `transfer_multicurrencies` is not supported on calamari. + // If min-xcm-fee is not set, no one can pay xcm fee(u129::MAX). + ParaA::execute_with(|| { + assert_noop!( + parachain::XTokens::transfer_multicurrencies( + Some(ALICE).into(), + vec![ + ( + parachain::CurrencyId::MantaCurrency(b_currency_id_on_a), + amount + ), + ( + parachain::CurrencyId::MantaCurrency(relay_asset_id_on_a), + fee_amount + ) + ], + 1, + Box::new(VersionedMultiLocation::V1(dest.clone())), + 40, + ), + orml_xtokens::Error::::FeeNotEnough + ); + }); + + // set min xcm fee on ParaA + let min_xcm_fee = 40; + ParaA::execute_with(|| { + assert_ok!(AssetManager::set_min_xcm_fee( + parachain::Origin::root(), + para_b_as_reserve_chain, + min_xcm_fee, + )); + }); + + // fee is bigger than min-xcm-fee should work(39 < 40). + ParaA::execute_with(|| { + assert_noop!( + parachain::XTokens::transfer_multicurrencies( + Some(ALICE).into(), + vec![ + ( + parachain::CurrencyId::MantaCurrency(b_currency_id_on_a), + amount + ), + ( + parachain::CurrencyId::MantaCurrency(relay_asset_id_on_a), + 39 + ) + ], + 1, + Box::new(VersionedMultiLocation::V1(dest.clone())), + 40, + ), + orml_xtokens::Error::::FeeNotEnough + ); + }); + + // fee is bigger than min-xcm-fee should work + ParaA::execute_with(|| { + assert_ok!(parachain::XTokens::transfer_multicurrencies( + Some(ALICE).into(), + vec![ + ( + parachain::CurrencyId::MantaCurrency(b_currency_id_on_a), + amount + ), + ( + parachain::CurrencyId::MantaCurrency(relay_asset_id_on_a), + fee_amount + ) + ], + 1, + Box::new(VersionedMultiLocation::V1(dest.clone())), + 40, + )); + }); } diff --git a/runtime/dolphin/Cargo.toml b/runtime/dolphin/Cargo.toml index d7dbecefb..9400e83f7 100644 --- a/runtime/dolphin/Cargo.toml +++ b/runtime/dolphin/Cargo.toml @@ -9,8 +9,8 @@ version = '3.2.0' [dependencies] codec = { package = "parity-scale-codec", version = '3.0.0', default-features = false, features = ["derive", "max-encoded-len"] } -log = { version = "0.4.16", default-features = false } hex-literal = { version = '0.3.4', optional = true } +log = { version = "0.4.16", default-features = false } scale-info = { version = "2.0.0", default-features = false, features = ["derive"] } serde = { version = '1.0.137', features = ['derive'], optional = true } smallvec = "1.8.0" @@ -32,10 +32,10 @@ sp-version = { git = 'https://github.com/paritytech/substrate.git', default-feat # Substrate frames frame-benchmarking = { git = 'https://github.com/paritytech/substrate.git', default-features = false, optional = true, branch = "polkadot-v0.9.18" } -frame-system-benchmarking = { git = 'https://github.com/paritytech/substrate.git', default-features = false, optional = true, branch = "polkadot-v0.9.18" } frame-executive = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } frame-support = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } frame-system = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } +frame-system-benchmarking = { git = 'https://github.com/paritytech/substrate.git', default-features = false, optional = true, branch = "polkadot-v0.9.18" } frame-system-rpc-runtime-api = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } frame-try-runtime = { git = "https://github.com/paritytech/substrate.git", default-features = false, optional = true, branch = "polkadot-v0.9.18" } @@ -44,53 +44,53 @@ pallet-assets = { git = 'https://github.com/paritytech/substrate.git', default-f pallet-aura = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } pallet-authorship = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } pallet-balances = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } +pallet-collective = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } +pallet-democracy = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } +pallet-membership = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } pallet-multisig = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } +pallet-preimage = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } +pallet-scheduler = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } pallet-session = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } pallet-sudo = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } pallet-timestamp = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } pallet-transaction-payment = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } pallet-transaction-payment-rpc-runtime-api = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } -pallet-utility = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } -pallet-collective = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } -pallet-democracy = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } -pallet-preimage = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } -pallet-scheduler = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } -pallet-membership = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } pallet-treasury = { git = "https://github.com/paritytech/substrate.git", default-features = false, branch = "polkadot-v0.9.18" } +pallet-utility = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } # Cumulus dependencies cumulus-pallet-aura-ext = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } +cumulus-pallet-dmp-queue = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } cumulus-pallet-parachain-system = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } +cumulus-pallet-session-benchmarking = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, optional = true, branch = "polkadot-v0.9.18" } +cumulus-pallet-xcm = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } +cumulus-pallet-xcmp-queue = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } cumulus-primitives-core = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } cumulus-primitives-timestamp = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } cumulus-primitives-utility = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } -cumulus-pallet-dmp-queue = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } -cumulus-pallet-session-benchmarking = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, optional = true, branch = "polkadot-v0.9.18" } -cumulus-pallet-xcmp-queue = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } -cumulus-pallet-xcm = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } parachain-info = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } # Polkadot dependencies -polkadot-primitives = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } +pallet-xcm = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } polkadot-core-primitives = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } -polkadot-runtime-common = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } polkadot-parachain = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } +polkadot-primitives = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } +polkadot-runtime-common = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } xcm = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } xcm-builder = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } xcm-executor = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } -pallet-xcm = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } # Self dependencies -manta-primitives = { path = '../../primitives', default-features = false } manta-collator-selection = { path = '../../pallets/collator-selection', default-features = false } -pallet-tx-pause = { path = '../../pallets/tx-pause', default-features = false } +manta-primitives = { path = '../../primitives', default-features = false } pallet-asset-manager = { path = '../../pallets/asset-manager', default-features = false } -pallet-manta-pay = { path='../../pallets/manta-pay', default-features = false, features = ["runtime"] } +pallet-manta-pay = { path = '../../pallets/manta-pay', default-features = false, features = ["runtime"] } +pallet-tx-pause = { path = '../../pallets/tx-pause', default-features = false } runtime-common = { path = '../common', default-features = false } # Third party (vendored) dependencies -orml-traits = { git = "https://github.com/manta-network/open-runtime-module-library.git", default-features = false, rev="7e2f985" } -orml-xtokens = { git = "https://github.com/manta-network/open-runtime-module-library.git", default-features = false, rev="7e2f985" } +orml-traits = { git = "https://github.com/manta-network/open-runtime-module-library.git", default-features = false, rev = "7e2f985" } +orml-xtokens = { git = "https://github.com/manta-network/open-runtime-module-library.git", default-features = false, rev = "7e2f985" } [package.metadata.docs.rs] targets = ['x86_64-unknown-linux-gnu'] @@ -100,116 +100,116 @@ substrate-wasm-builder = { git = 'https://github.com/paritytech/substrate.git', [features] default = ['std'] -try-runtime = [ - 'frame-executive/try-runtime', - 'frame-try-runtime', - 'frame-system/try-runtime', - 'pallet-aura/try-runtime', - 'pallet-authorship/try-runtime', - 'pallet-balances/try-runtime', - 'pallet-preimage/try-runtime', - 'pallet-multisig/try-runtime', - 'pallet-session/try-runtime', - 'pallet-timestamp/try-runtime', - 'pallet-transaction-payment/try-runtime', - 'pallet-utility/try-runtime', - 'pallet-collective/try-runtime', - 'pallet-democracy/try-runtime', - 'pallet-scheduler/try-runtime', - 'pallet-membership/try-runtime', - 'pallet-treasury/try-runtime', - 'pallet-assets/try-runtime', - 'pallet-tx-pause/try-runtime', - 'pallet-asset-manager/try-runtime', -] runtime-benchmarks = [ - 'cumulus-pallet-session-benchmarking/runtime-benchmarks', - 'hex-literal', - 'sp-runtime/runtime-benchmarks', - 'xcm-builder/runtime-benchmarks', - 'frame-benchmarking', - 'frame-system-benchmarking', - 'frame-support/runtime-benchmarks', - 'frame-system/runtime-benchmarks', - 'pallet-balances/runtime-benchmarks', - 'pallet-multisig/runtime-benchmarks', - 'pallet-utility/runtime-benchmarks', - 'pallet-timestamp/runtime-benchmarks', - 'pallet-xcm/runtime-benchmarks', - 'manta-collator-selection/runtime-benchmarks', - 'pallet-collective/runtime-benchmarks', - 'pallet-democracy/runtime-benchmarks', - 'pallet-preimage/runtime-benchmarks', - 'pallet-scheduler/runtime-benchmarks', - 'pallet-membership/runtime-benchmarks', - 'pallet-tx-pause/runtime-benchmarks', - 'pallet-treasury/runtime-benchmarks', - 'pallet-assets/runtime-benchmarks', - 'pallet-manta-pay/runtime-benchmarks', - 'pallet-asset-manager/runtime-benchmarks', - 'cumulus-pallet-xcmp-queue/runtime-benchmarks', + 'cumulus-pallet-session-benchmarking/runtime-benchmarks', + 'hex-literal', + 'sp-runtime/runtime-benchmarks', + 'xcm-builder/runtime-benchmarks', + 'frame-benchmarking', + 'frame-system-benchmarking', + 'frame-support/runtime-benchmarks', + 'frame-system/runtime-benchmarks', + 'pallet-balances/runtime-benchmarks', + 'pallet-multisig/runtime-benchmarks', + 'pallet-utility/runtime-benchmarks', + 'pallet-timestamp/runtime-benchmarks', + 'pallet-xcm/runtime-benchmarks', + 'manta-collator-selection/runtime-benchmarks', + 'pallet-collective/runtime-benchmarks', + 'pallet-democracy/runtime-benchmarks', + 'pallet-preimage/runtime-benchmarks', + 'pallet-scheduler/runtime-benchmarks', + 'pallet-membership/runtime-benchmarks', + 'pallet-tx-pause/runtime-benchmarks', + 'pallet-treasury/runtime-benchmarks', + 'pallet-assets/runtime-benchmarks', + 'pallet-manta-pay/runtime-benchmarks', + 'pallet-asset-manager/runtime-benchmarks', + 'cumulus-pallet-xcmp-queue/runtime-benchmarks', +] +try-runtime = [ + 'frame-executive/try-runtime', + 'frame-try-runtime', + 'frame-system/try-runtime', + 'pallet-aura/try-runtime', + 'pallet-authorship/try-runtime', + 'pallet-balances/try-runtime', + 'pallet-preimage/try-runtime', + 'pallet-multisig/try-runtime', + 'pallet-session/try-runtime', + 'pallet-timestamp/try-runtime', + 'pallet-transaction-payment/try-runtime', + 'pallet-utility/try-runtime', + 'pallet-collective/try-runtime', + 'pallet-democracy/try-runtime', + 'pallet-scheduler/try-runtime', + 'pallet-membership/try-runtime', + 'pallet-treasury/try-runtime', + 'pallet-assets/try-runtime', + 'pallet-tx-pause/try-runtime', + 'pallet-asset-manager/try-runtime', ] # Set timing constants (e.g. session period) to faster versions to speed up testing. fast-runtime = [] std = [ - 'codec/std', - 'serde', - 'sp-consensus-aura/std', - 'pallet-aura/std', - 'sp-api/std', - 'sp-std/std', - 'sp-io/std', - 'sp-core/std', - 'sp-runtime/std', - 'sp-version/std', - 'sp-offchain/std', - 'sp-session/std', - 'sp-block-builder/std', - 'sp-transaction-pool/std', - 'sp-inherents/std', - 'frame-support/std', - 'frame-executive/std', - 'frame-system/std', - 'frame-system-rpc-runtime-api/std', - 'frame-try-runtime/std', - 'pallet-authorship/std', - 'pallet-balances/std', - 'pallet-multisig/std', - 'pallet-utility/std', - 'pallet-transaction-payment-rpc-runtime-api/std', - 'pallet-timestamp/std', - 'pallet-session/std', - 'pallet-sudo/std', - 'pallet-xcm/std', - 'pallet-transaction-payment/std', - 'pallet-collective/std', - 'pallet-democracy/std', - 'pallet-preimage/std', - 'pallet-scheduler/std', - 'pallet-membership/std', - 'manta-primitives/std', - 'runtime-common/std', - 'parachain-info/std', - "cumulus-pallet-aura-ext/std", - 'cumulus-pallet-parachain-system/std', - 'cumulus-pallet-dmp-queue/std', - "cumulus-pallet-xcmp-queue/std", - "cumulus-pallet-xcm/std", - "cumulus-primitives-core/std", - "cumulus-primitives-timestamp/std", - "cumulus-primitives-utility/std", - 'xcm/std', - 'xcm-builder/std', - 'xcm-executor/std', - 'polkadot-runtime-common/std', - 'polkadot-primitives/std', - 'orml-traits/std', - 'orml-xtokens/std', - 'pallet-asset-manager/std', - 'manta-collator-selection/std', - 'pallet-tx-pause/std', - 'pallet-treasury/std', - 'pallet-assets/std', - 'pallet-manta-pay/std', - 'pallet-asset-manager/std', + 'codec/std', + 'serde', + 'sp-consensus-aura/std', + 'pallet-aura/std', + 'sp-api/std', + 'sp-std/std', + 'sp-io/std', + 'sp-core/std', + 'sp-runtime/std', + 'sp-version/std', + 'sp-offchain/std', + 'sp-session/std', + 'sp-block-builder/std', + 'sp-transaction-pool/std', + 'sp-inherents/std', + 'frame-support/std', + 'frame-executive/std', + 'frame-system/std', + 'frame-system-rpc-runtime-api/std', + 'frame-try-runtime/std', + 'pallet-authorship/std', + 'pallet-balances/std', + 'pallet-multisig/std', + 'pallet-utility/std', + 'pallet-transaction-payment-rpc-runtime-api/std', + 'pallet-timestamp/std', + 'pallet-session/std', + 'pallet-sudo/std', + 'pallet-xcm/std', + 'pallet-transaction-payment/std', + 'pallet-collective/std', + 'pallet-democracy/std', + 'pallet-preimage/std', + 'pallet-scheduler/std', + 'pallet-membership/std', + 'manta-primitives/std', + 'runtime-common/std', + 'parachain-info/std', + "cumulus-pallet-aura-ext/std", + 'cumulus-pallet-parachain-system/std', + 'cumulus-pallet-dmp-queue/std', + "cumulus-pallet-xcmp-queue/std", + "cumulus-pallet-xcm/std", + "cumulus-primitives-core/std", + "cumulus-primitives-timestamp/std", + "cumulus-primitives-utility/std", + 'xcm/std', + 'xcm-builder/std', + 'xcm-executor/std', + 'polkadot-runtime-common/std', + 'polkadot-primitives/std', + 'orml-traits/std', + 'orml-xtokens/std', + 'pallet-asset-manager/std', + 'manta-collator-selection/std', + 'pallet-tx-pause/std', + 'pallet-treasury/std', + 'pallet-assets/std', + 'pallet-manta-pay/std', + 'pallet-asset-manager/std', ] diff --git a/runtime/dolphin/build.rs b/runtime/dolphin/build.rs index 46ffd8513..ebc6ed273 100644 --- a/runtime/dolphin/build.rs +++ b/runtime/dolphin/build.rs @@ -17,9 +17,9 @@ use substrate_wasm_builder::WasmBuilder; fn main() { - WasmBuilder::new() - .with_current_project() - .export_heap_base() - .import_memory() - .build() + WasmBuilder::new() + .with_current_project() + .export_heap_base() + .import_memory() + .build() } diff --git a/runtime/dolphin/src/assets_config.rs b/runtime/dolphin/src/assets_config.rs index 7b829745d..c81603836 100644 --- a/runtime/dolphin/src/assets_config.rs +++ b/runtime/dolphin/src/assets_config.rs @@ -15,17 +15,17 @@ // along with Manta. If not, see . use super::{ - weights, xcm_config::SelfReserve, AssetManager, Assets, Balances, Event, - NativeTokenExistentialDeposit, Origin, Runtime, + weights, xcm_config::SelfReserve, AssetManager, Assets, Balances, Event, + NativeTokenExistentialDeposit, Origin, Runtime, }; use manta_primitives::{ - assets::{ - AssetConfig, AssetLocation, AssetRegistrar, AssetRegistrarMetadata, AssetStorageMetadata, - ConcreteFungibleLedger, - }, - constants::{ASSET_MANAGER_PALLET_ID, DOLPHIN_DECIMAL, MANTA_PAY_PALLET_ID}, - types::{AccountId, AssetId, Balance}, + assets::{ + AssetConfig, AssetLocation, AssetRegistrar, AssetRegistrarMetadata, AssetStorageMetadata, + ConcreteFungibleLedger, + }, + constants::{ASSET_MANAGER_PALLET_ID, DOLPHIN_DECIMAL, MANTA_PAY_PALLET_ID}, + types::{AccountId, AssetId, Balance}, }; use frame_support::{pallet_prelude::DispatchResult, parameter_types, PalletId}; @@ -33,133 +33,133 @@ use frame_system::EnsureRoot; use xcm::VersionedMultiLocation; parameter_types! { - pub const AssetDeposit: Balance = 0; // Does not really matter as this will be only called by root - pub const AssetAccountDeposit: Balance = 0; - pub const ApprovalDeposit: Balance = 0; - pub const AssetsStringLimit: u32 = 50; - pub const MetadataDepositBase: Balance = 0; - pub const MetadataDepositPerByte: Balance = 0; + pub const AssetDeposit: Balance = 0; // Does not really matter as this will be only called by root + pub const AssetAccountDeposit: Balance = 0; + pub const ApprovalDeposit: Balance = 0; + pub const AssetsStringLimit: u32 = 50; + pub const MetadataDepositBase: Balance = 0; + pub const MetadataDepositPerByte: Balance = 0; } impl pallet_assets::Config for Runtime { - type Event = Event; - type Balance = Balance; - type AssetId = AssetId; - type Currency = Balances; - type ForceOrigin = EnsureRoot; - type AssetDeposit = AssetDeposit; - type AssetAccountDeposit = AssetAccountDeposit; - type MetadataDepositBase = MetadataDepositBase; - type MetadataDepositPerByte = MetadataDepositPerByte; - type ApprovalDeposit = ApprovalDeposit; - type StringLimit = AssetsStringLimit; - type Freezer = (); - type Extra = (); - type WeightInfo = weights::pallet_assets::SubstrateWeight; + type Event = Event; + type Balance = Balance; + type AssetId = AssetId; + type Currency = Balances; + type ForceOrigin = EnsureRoot; + type AssetDeposit = AssetDeposit; + type AssetAccountDeposit = AssetAccountDeposit; + type MetadataDepositBase = MetadataDepositBase; + type MetadataDepositPerByte = MetadataDepositPerByte; + type ApprovalDeposit = ApprovalDeposit; + type StringLimit = AssetsStringLimit; + type Freezer = (); + type Extra = (); + type WeightInfo = weights::pallet_assets::SubstrateWeight; } pub struct MantaAssetRegistrar; impl AssetRegistrar for MantaAssetRegistrar { - fn create_asset( - asset_id: AssetId, - min_balance: Balance, - metadata: AssetStorageMetadata, - is_sufficient: bool, - ) -> DispatchResult { - Assets::force_create( - Origin::root(), - asset_id, - sp_runtime::MultiAddress::Id(AssetManager::account_id()), - is_sufficient, - min_balance, - )?; - - Assets::force_set_metadata( - Origin::root(), - asset_id, - metadata.name, - metadata.symbol, - metadata.decimals, - metadata.is_frozen, - )?; - - Assets::force_asset_status( - Origin::root(), - asset_id, - AssetManager::account_id().into(), - AssetManager::account_id().into(), - AssetManager::account_id().into(), - AssetManager::account_id().into(), - min_balance, - is_sufficient, - metadata.is_frozen, - ) - } - - fn update_asset_metadata(asset_id: AssetId, metadata: AssetStorageMetadata) -> DispatchResult { - Assets::force_set_metadata( - Origin::root(), - asset_id, - metadata.name, - metadata.symbol, - metadata.decimals, - metadata.is_frozen, - ) - } + fn create_asset( + asset_id: AssetId, + min_balance: Balance, + metadata: AssetStorageMetadata, + is_sufficient: bool, + ) -> DispatchResult { + Assets::force_create( + Origin::root(), + asset_id, + sp_runtime::MultiAddress::Id(AssetManager::account_id()), + is_sufficient, + min_balance, + )?; + + Assets::force_set_metadata( + Origin::root(), + asset_id, + metadata.name, + metadata.symbol, + metadata.decimals, + metadata.is_frozen, + )?; + + Assets::force_asset_status( + Origin::root(), + asset_id, + AssetManager::account_id().into(), + AssetManager::account_id().into(), + AssetManager::account_id().into(), + AssetManager::account_id().into(), + min_balance, + is_sufficient, + metadata.is_frozen, + ) + } + + fn update_asset_metadata(asset_id: AssetId, metadata: AssetStorageMetadata) -> DispatchResult { + Assets::force_set_metadata( + Origin::root(), + asset_id, + metadata.name, + metadata.symbol, + metadata.decimals, + metadata.is_frozen, + ) + } } parameter_types! { - pub const DummyAssetId: AssetId = 0; - pub const NativeAssetId: AssetId = 1; - pub const StartNonNativeAssetId: AssetId = 8; - pub NativeAssetLocation: AssetLocation = AssetLocation( - VersionedMultiLocation::V1(SelfReserve::get())); - pub NativeAssetMetadata: AssetRegistrarMetadata = AssetRegistrarMetadata { - name: b"Dolphin".to_vec(), - symbol: b"DOL".to_vec(), - decimals: DOLPHIN_DECIMAL, - min_balance: NativeTokenExistentialDeposit::get(), - evm_address: None, - is_frozen: false, - is_sufficient: true, - }; - pub const AssetManagerPalletId: PalletId = ASSET_MANAGER_PALLET_ID; + pub const DummyAssetId: AssetId = 0; + pub const NativeAssetId: AssetId = 1; + pub const StartNonNativeAssetId: AssetId = 8; + pub NativeAssetLocation: AssetLocation = AssetLocation( + VersionedMultiLocation::V1(SelfReserve::get())); + pub NativeAssetMetadata: AssetRegistrarMetadata = AssetRegistrarMetadata { + name: b"Dolphin".to_vec(), + symbol: b"DOL".to_vec(), + decimals: DOLPHIN_DECIMAL, + min_balance: NativeTokenExistentialDeposit::get(), + evm_address: None, + is_frozen: false, + is_sufficient: true, + }; + pub const AssetManagerPalletId: PalletId = ASSET_MANAGER_PALLET_ID; } pub type DolphinConcreteFungibleLedger = - ConcreteFungibleLedger; + ConcreteFungibleLedger; #[derive(Clone, Eq, PartialEq)] pub struct DolphinAssetConfig; impl AssetConfig for DolphinAssetConfig { - type DummyAssetId = DummyAssetId; - type NativeAssetId = NativeAssetId; - type StartNonNativeAssetId = StartNonNativeAssetId; - type AssetRegistrarMetadata = AssetRegistrarMetadata; - type NativeAssetLocation = NativeAssetLocation; - type NativeAssetMetadata = NativeAssetMetadata; - type StorageMetadata = AssetStorageMetadata; - type AssetLocation = AssetLocation; - type AssetRegistrar = MantaAssetRegistrar; - type FungibleLedger = DolphinConcreteFungibleLedger; + type DummyAssetId = DummyAssetId; + type NativeAssetId = NativeAssetId; + type StartNonNativeAssetId = StartNonNativeAssetId; + type AssetRegistrarMetadata = AssetRegistrarMetadata; + type NativeAssetLocation = NativeAssetLocation; + type NativeAssetMetadata = NativeAssetMetadata; + type StorageMetadata = AssetStorageMetadata; + type AssetLocation = AssetLocation; + type AssetRegistrar = MantaAssetRegistrar; + type FungibleLedger = DolphinConcreteFungibleLedger; } impl pallet_asset_manager::Config for Runtime { - type Event = Event; - type AssetConfig = DolphinAssetConfig; - type ModifierOrigin = EnsureRoot; - type PalletId = AssetManagerPalletId; - type WeightInfo = weights::pallet_asset_manager::SubstrateWeight; + type Event = Event; + type AssetConfig = DolphinAssetConfig; + type ModifierOrigin = EnsureRoot; + type PalletId = AssetManagerPalletId; + type WeightInfo = weights::pallet_asset_manager::SubstrateWeight; } parameter_types! { - pub const MantaPayPalletId: PalletId = MANTA_PAY_PALLET_ID; + pub const MantaPayPalletId: PalletId = MANTA_PAY_PALLET_ID; } impl pallet_manta_pay::Config for Runtime { - type Event = Event; - type WeightInfo = weights::pallet_manta_pay::SubstrateWeight; - type AssetConfig = DolphinAssetConfig; - type PalletId = MantaPayPalletId; + type Event = Event; + type WeightInfo = weights::pallet_manta_pay::SubstrateWeight; + type AssetConfig = DolphinAssetConfig; + type PalletId = MantaPayPalletId; } diff --git a/runtime/dolphin/src/currency.rs b/runtime/dolphin/src/currency.rs index a7c666720..3fc5e5d86 100644 --- a/runtime/dolphin/src/currency.rs +++ b/runtime/dolphin/src/currency.rs @@ -23,5 +23,5 @@ pub const mDOL: Balance = DOL / 1_000; //15 decimal, milli-DOL pub const uDOL: Balance = DOL / 1_000_000; // 12 decimal, micro-DOL pub const fn deposit(items: u32, bytes: u32) -> Balance { - items as Balance * 15 * mDOL + (bytes as Balance) * 6 * mDOL // TODO: revisit the storage cost here + items as Balance * 15 * mDOL + (bytes as Balance) * 6 * mDOL // TODO: revisit the storage cost here } diff --git a/runtime/dolphin/src/fee.rs b/runtime/dolphin/src/fee.rs index d0556ca13..88e03329e 100644 --- a/runtime/dolphin/src/fee.rs +++ b/runtime/dolphin/src/fee.rs @@ -15,7 +15,7 @@ // along with Manta. If not, see . use frame_support::weights::{ - WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial, + WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial, }; use manta_primitives::types::Balance; use smallvec::smallvec; @@ -36,14 +36,14 @@ pub const TARGET_BLOCK_FULLNESS: Perbill = Perbill::from_percent(25); /// - Setting it to `1` will cause the literal `#[weight = x]` values to be charged. pub struct WeightToFee; impl WeightToFeePolynomial for WeightToFee { - type Balance = Balance; - fn polynomial() -> WeightToFeeCoefficients { - // Refer to Calamari's congested_chain_simulation() test for how to come up with the coefficient. - smallvec![WeightToFeeCoefficient { - coeff_integer: 5000u32.into(), - coeff_frac: Perbill::zero(), - negative: false, - degree: 1, - }] - } + type Balance = Balance; + fn polynomial() -> WeightToFeeCoefficients { + // Refer to Calamari's congested_chain_simulation() test for how to come up with the coefficient. + smallvec![WeightToFeeCoefficient { + coeff_integer: 5000u32.into(), + coeff_frac: Perbill::zero(), + negative: false, + degree: 1, + }] + } } diff --git a/runtime/dolphin/src/impls.rs b/runtime/dolphin/src/impls.rs index ad278d837..988dd748c 100644 --- a/runtime/dolphin/src/impls.rs +++ b/runtime/dolphin/src/impls.rs @@ -19,24 +19,24 @@ use frame_support::traits::{Currency, Imbalance, OnUnbalanced}; pub struct Author; impl OnUnbalanced for Author { - fn on_nonzero_unbalanced(amount: NegativeImbalance) { - if let Some(author) = Authorship::author() { - Balances::resolve_creating(&author, amount); - } - } + fn on_nonzero_unbalanced(amount: NegativeImbalance) { + if let Some(author) = Authorship::author() { + Balances::resolve_creating(&author, amount); + } + } } pub struct DealWithFees; impl OnUnbalanced for DealWithFees { - fn on_unbalanceds(mut fees_then_tips: impl Iterator) { - if let Some(fees) = fees_then_tips.next() { - let mut split = fees.ration(80, 20); - if let Some(tips) = fees_then_tips.next() { - // for tips, if any, 0% to treasury, 100% to block author (though this can be anything) - tips.ration_merge_into(0, 100, &mut split); - } - Treasury::on_unbalanced(split.0); - Author::on_unbalanced(split.1); - } - } + fn on_unbalanceds(mut fees_then_tips: impl Iterator) { + if let Some(fees) = fees_then_tips.next() { + let mut split = fees.ration(80, 20); + if let Some(tips) = fees_then_tips.next() { + // for tips, if any, 0% to treasury, 100% to block author (though this can be anything) + tips.ration_merge_into(0, 100, &mut split); + } + Treasury::on_unbalanced(split.0); + Author::on_unbalanced(split.1); + } + } } diff --git a/runtime/dolphin/src/lib.rs b/runtime/dolphin/src/lib.rs index 7e59be176..65e6704f4 100644 --- a/runtime/dolphin/src/lib.rs +++ b/runtime/dolphin/src/lib.rs @@ -16,6 +16,7 @@ //! Dolphin Parachain runtime. +#![allow(clippy::identity_op)] // keep e.g. 1 * DAYS for legibility #![cfg_attr(not(feature = "std"), no_std)] #![recursion_limit = "256"] @@ -26,10 +27,10 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, - traits::{AccountIdLookup, BlakeTwo256, Block as BlockT}, - transaction_validity::{TransactionSource, TransactionValidity}, - ApplyExtrinsicResult, Perbill, Permill, + create_runtime_str, generic, impl_opaque_keys, + traits::{AccountIdLookup, BlakeTwo256, Block as BlockT}, + transaction_validity::{TransactionSource, TransactionValidity}, + ApplyExtrinsicResult, Perbill, Permill, }; use sp_std::{cmp::Ordering, prelude::*}; use sp_version::RuntimeVersion; @@ -38,21 +39,21 @@ use sp_version::RuntimeVersion; use sp_version::NativeVersion; use frame_support::{ - construct_runtime, parameter_types, - traits::{ConstU16, ConstU32, ConstU8, Contains, Currency, EnsureOneOf, PrivilegeCmp}, - weights::{ - constants::{BlockExecutionWeight, ExtrinsicBaseWeight, WEIGHT_PER_SECOND}, - DispatchClass, Weight, - }, - PalletId, + construct_runtime, parameter_types, + traits::{ConstU16, ConstU32, ConstU8, Contains, Currency, EnsureOneOf, PrivilegeCmp}, + weights::{ + constants::{BlockExecutionWeight, ExtrinsicBaseWeight, WEIGHT_PER_SECOND}, + DispatchClass, Weight, + }, + PalletId, }; use frame_system::{ - limits::{BlockLength, BlockWeights}, - EnsureRoot, + limits::{BlockLength, BlockWeights}, + EnsureRoot, }; use manta_primitives::{ - constants::{time::*, STAKING_PALLET_ID, TREASURY_PALLET_ID}, - types::{AccountId, AuraId, Balance, BlockNumber, Hash, Header, Index, Signature}, + constants::{time::*, STAKING_PALLET_ID, TREASURY_PALLET_ID}, + types::{AccountId, AuraId, Balance, BlockNumber, Hash, Header, Index, Signature}, }; use runtime_common::prod_or_fast; @@ -80,19 +81,19 @@ pub type NegativeImbalance = >::NegativeImbalanc /// of data like extrinsics, allowing for them to continue syncing the network through upgrades /// to even the core data structures. pub mod opaque { - use super::*; - pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic; - /// Opaque block header type. - pub type Header = generic::Header; - /// Opaque block type. - pub type Block = generic::Block; - /// Opaque block identifier type. - pub type BlockId = generic::BlockId; - impl_opaque_keys! { - pub struct SessionKeys { - pub aura: Aura, - } - } + use super::*; + pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic; + /// Opaque block header type. + pub type Header = generic::Header; + /// Opaque block type. + pub type Block = generic::Block; + /// Opaque block identifier type. + pub type BlockId = generic::BlockId; + impl_opaque_keys! { + pub struct SessionKeys { + pub aura: Aura, + } + } } // Weights used in the runtime. @@ -100,23 +101,23 @@ mod weights; #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("dolphin"), - impl_name: create_runtime_str!("dolphin"), - authoring_version: 1, - spec_version: 3200, - impl_version: 1, - apis: RUNTIME_API_VERSIONS, - transaction_version: 2, - state_version: 0, + spec_name: create_runtime_str!("dolphin"), + impl_name: create_runtime_str!("dolphin"), + authoring_version: 1, + spec_version: 3200, + impl_version: 1, + apis: RUNTIME_API_VERSIONS, + transaction_version: 2, + state_version: 0, }; /// The version information used to identify this runtime when compiled natively. #[cfg(feature = "std")] pub fn native_version() -> NativeVersion { - NativeVersion { - runtime_version: VERSION, - can_author_with: Default::default(), - } + NativeVersion { + runtime_version: VERSION, + can_author_with: Default::default(), + } } /// We assume that ~10% of the block weight is consumed by `on_initialize` handlers. This is @@ -130,574 +131,584 @@ pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(70); pub const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2; parameter_types! { - pub const Version: RuntimeVersion = VERSION; - pub RuntimeBlockLength: BlockLength = - BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); - pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder() - .base_block(BlockExecutionWeight::get()) - .for_class(DispatchClass::all(), |weights| { - weights.base_extrinsic = ExtrinsicBaseWeight::get(); - }) - .for_class(DispatchClass::Normal, |weights| { - weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); - }) - .for_class(DispatchClass::Operational, |weights| { - weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT); - // Operational transactions have some extra reserved space, so that they - // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`. - weights.reserved = Some( - MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT - ); - }) - .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) - .build_or_panic(); - pub const SS58Prefix: u8 = manta_primitives::constants::CALAMARI_SS58PREFIX; + pub const Version: RuntimeVersion = VERSION; + pub RuntimeBlockLength: BlockLength = + BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); + pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder() + .base_block(BlockExecutionWeight::get()) + .for_class(DispatchClass::all(), |weights| { + weights.base_extrinsic = ExtrinsicBaseWeight::get(); + }) + .for_class(DispatchClass::Normal, |weights| { + weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); + }) + .for_class(DispatchClass::Operational, |weights| { + weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT); + // Operational transactions have some extra reserved space, so that they + // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`. + weights.reserved = Some( + MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT + ); + }) + .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) + .build_or_panic(); + pub const SS58Prefix: u8 = manta_primitives::constants::CALAMARI_SS58PREFIX; } impl pallet_tx_pause::Config for Runtime { - type Event = Event; - type UpdateOrigin = EnsureRoot; - type WeightInfo = weights::pallet_tx_pause::SubstrateWeight; + type Event = Event; + type UpdateOrigin = EnsureRoot; + type WeightInfo = weights::pallet_tx_pause::SubstrateWeight; } // Don't allow permission-less asset creation. pub struct BaseFilter; impl Contains for BaseFilter { - fn contains(call: &Call) -> bool { - if matches!( - call, - Call::Timestamp(_) | Call::ParachainSystem(_) | Call::System(_) - ) { - // always allow core call - // pallet-timestamp and parachainSystem could not be filtered because - // they are used in communication between relaychain and parachain. - return true; - } - - if pallet_tx_pause::PausedTransactionFilter::::contains(call) { - // no paused call - return false; - } - - match call { - | Call::Authorship(_) - // Sudo also cannot be filtered because it is used in runtime upgrade. - | Call::Sudo(_) - | Call::Multisig(_) - // For now disallow public proposal workflows, treasury workflows, - // as well as external_propose and external_propose_majority. - // The following are filtered out: - // pallet_democracy::Call::propose(_) - // pallet_democracy::Call::second(_, _) - // pallet_democracy::Call::cancel_proposal(_) - // pallet_democracy::Call::clear_public_proposals() - // pallet_democracy::Call::external_propose(_) - // pallet_democracy::Call::external_propose_majority(_) - | Call::Democracy(pallet_democracy::Call::vote {..} - | pallet_democracy::Call::emergency_cancel {..} - | pallet_democracy::Call::external_propose_default {..} - | pallet_democracy::Call::fast_track {..} - | pallet_democracy::Call::veto_external {..} - | pallet_democracy::Call::cancel_referendum {..} - | pallet_democracy::Call::cancel_queued {..} - | pallet_democracy::Call::delegate {..} - | pallet_democracy::Call::undelegate {..} - | pallet_democracy::Call::note_preimage {..} - | pallet_democracy::Call::note_preimage_operational {..} - | pallet_democracy::Call::note_imminent_preimage {..} - | pallet_democracy::Call::note_imminent_preimage_operational {..} - | pallet_democracy::Call::reap_preimage {..} - | pallet_democracy::Call::unlock {..} - | pallet_democracy::Call::remove_vote {..} - | pallet_democracy::Call::remove_other_vote {..} - | pallet_democracy::Call::enact_proposal {..} - | pallet_democracy::Call::blacklist {..}) - | Call::Council(_) - | Call::TechnicalCommittee(_) - | Call::CouncilMembership(_) - | Call::TechnicalMembership(_) - // Treasury calls are filtered while it is accumulating funds. - //| Call::Treasury(_) - | Call::Scheduler(_) - | Call::Session(_) // User must be able to set their session key when applying for a collator - | Call::CollatorSelection( - manta_collator_selection::Call::set_invulnerables{..} - | manta_collator_selection::Call::set_desired_candidates{..} - | manta_collator_selection::Call::set_candidacy_bond{..} - | manta_collator_selection::Call::set_eviction_baseline{..} - | manta_collator_selection::Call::set_eviction_tolerance{..} - | manta_collator_selection::Call::register_candidate{..} - // Currently, we filter `register_as_candidate` as this call is not yet ready for community. - | manta_collator_selection::Call::remove_collator{..} - | manta_collator_selection::Call::leave_intent{..}) - | Call::Balances(_) - // Everything except transfer() is filtered out until it is practically needed: - // orml_xtokens::Call::transfer_with_fee {..} - // orml_xtokens::Call::transfer_multiasset {..} - // orml_xtokens::Call::transfer_multiasset_with_fee {..} - // orml_xtokens::Call::transfer_multicurrencies {..} - // orml_xtokens::Call::transfer_multiassets {..} - | Call::XTokens(orml_xtokens::Call::transfer {..}) - | Call::MantaPay(_) - | Call::Preimage(_) - | Call::Utility(_) => true, - // Filter XCM pallets, we only allow transfer with XTokens. - // Filter Assets. Assets should only be accessed by AssetManager. - // AssetManager is also filtered because all of its extrinsics are callable only by Root, - // and Root calls skip this whole filter. - _ => false, - } - } + fn contains(call: &Call) -> bool { + if matches!( + call, + Call::Timestamp(_) | Call::ParachainSystem(_) | Call::System(_) + ) { + // always allow core call + // pallet-timestamp and parachainSystem could not be filtered because + // they are used in communication between relaychain and parachain. + return true; + } + + if pallet_tx_pause::PausedTransactionFilter::::contains(call) { + // no paused call + return false; + } + + #[allow(clippy::match_like_matches_macro)] + // keep CallFilter with explicit true/false for documentation + match call { + // Explicitly DISALLOWED calls + | Call::Assets(_) // Filter Assets. Assets should only be accessed by AssetManager. + | Call::AssetManager(_) // AssetManager is also filtered because all of its extrinsics + // are callable only by Root, and Root calls skip this whole filter. + // Currently, we filter `register_as_candidate` as this call is not yet ready for community. + | Call::CollatorSelection( manta_collator_selection::Call::register_as_candidate{..}) + // For now disallow public proposal workflows, treasury workflows, + // as well as external_propose and external_propose_majority. + // The following are filtered out: + | Call::Democracy( + pallet_democracy::Call::propose {..} + | pallet_democracy::Call::second {..} + | pallet_democracy::Call::cancel_proposal {..} + | pallet_democracy::Call::clear_public_proposals {..} + | pallet_democracy::Call::external_propose {..} + | pallet_democracy::Call::external_propose_majority {..}) + | Call::Treasury(_) // Treasury calls are filtered while it is accumulating funds. + // Everything except transfer() is filtered out until it is practically needed: + | Call::XTokens( + orml_xtokens::Call::transfer_with_fee {..} + | orml_xtokens::Call::transfer_multiasset {..} + | orml_xtokens::Call::transfer_multiasset_with_fee {..} + | orml_xtokens::Call::transfer_multicurrencies {..} + | orml_xtokens::Call::transfer_multiassets {..}) + // Everything except transfer() is filtered out until it is practically needed: + | Call::XcmpQueue(_) | Call::PolkadotXcm(_) | Call::DmpQueue(_) => false, + + // Explicitly ALLOWED calls + | Call::Authorship(_) + // Sudo also cannot be filtered because it is used in runtime upgrade. + | Call::Sudo(_) + | Call::Multisig(_) + | Call::Democracy(pallet_democracy::Call::vote {..} + | pallet_democracy::Call::emergency_cancel {..} + | pallet_democracy::Call::external_propose_default {..} + | pallet_democracy::Call::fast_track {..} + | pallet_democracy::Call::veto_external {..} + | pallet_democracy::Call::cancel_referendum {..} + | pallet_democracy::Call::cancel_queued {..} + | pallet_democracy::Call::delegate {..} + | pallet_democracy::Call::undelegate {..} + | pallet_democracy::Call::note_preimage {..} + | pallet_democracy::Call::note_preimage_operational {..} + | pallet_democracy::Call::note_imminent_preimage {..} + | pallet_democracy::Call::note_imminent_preimage_operational {..} + | pallet_democracy::Call::reap_preimage {..} + | pallet_democracy::Call::unlock {..} + | pallet_democracy::Call::remove_vote {..} + | pallet_democracy::Call::remove_other_vote {..} + | pallet_democracy::Call::enact_proposal {..} + | pallet_democracy::Call::blacklist {..}) + | Call::Council(_) + | Call::TechnicalCommittee(_) + | Call::CouncilMembership(_) + | Call::TechnicalMembership(_) + | Call::Scheduler(_) + | Call::Session(_) // User must be able to set their session key when applying for a collator + | Call::CollatorSelection( + manta_collator_selection::Call::set_invulnerables{..} + | manta_collator_selection::Call::set_desired_candidates{..} + | manta_collator_selection::Call::set_candidacy_bond{..} + | manta_collator_selection::Call::set_eviction_baseline{..} + | manta_collator_selection::Call::set_eviction_tolerance{..} + | manta_collator_selection::Call::register_candidate{..} + | manta_collator_selection::Call::remove_collator{..} + | manta_collator_selection::Call::leave_intent{..}) + | Call::Balances(_) + | Call::XTokens(orml_xtokens::Call::transfer {..}) + | Call::MantaPay(_) + | Call::Preimage(_) + | Call::Utility(_) => true, + + // DISALLOW anything else + _ => false, + } + } } // Configure FRAME pallets to include in runtime. impl frame_system::Config for Runtime { - type BaseCallFilter = BaseFilter; // Let filter activate. - type BlockWeights = RuntimeBlockWeights; - type BlockLength = RuntimeBlockLength; - type AccountId = AccountId; - type Call = Call; - type Lookup = AccountIdLookup; - type Index = Index; - type BlockNumber = BlockNumber; - type Hash = Hash; - type Hashing = BlakeTwo256; - type Header = Header; - type Event = Event; - type Origin = Origin; - type BlockHashCount = BlockHashCount; - type DbWeight = RocksDbWeight; - type Version = Version; - type PalletInfo = PalletInfo; - type OnNewAccount = (); - type OnKilledAccount = (); - type AccountData = pallet_balances::AccountData; - type SystemWeightInfo = weights::frame_system::SubstrateWeight; - type SS58Prefix = SS58Prefix; - type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; - type MaxConsumers = ConstU32<16>; + type BaseCallFilter = BaseFilter; // Let filter activate. + type BlockWeights = RuntimeBlockWeights; + type BlockLength = RuntimeBlockLength; + type AccountId = AccountId; + type Call = Call; + type Lookup = AccountIdLookup; + type Index = Index; + type BlockNumber = BlockNumber; + type Hash = Hash; + type Hashing = BlakeTwo256; + type Header = Header; + type Event = Event; + type Origin = Origin; + type BlockHashCount = BlockHashCount; + type DbWeight = RocksDbWeight; + type Version = Version; + type PalletInfo = PalletInfo; + type OnNewAccount = (); + type OnKilledAccount = (); + type AccountData = pallet_balances::AccountData; + type SystemWeightInfo = weights::frame_system::SubstrateWeight; + type SS58Prefix = SS58Prefix; + type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; + type MaxConsumers = ConstU32<16>; } parameter_types! { - pub const MinimumPeriod: u64 = SLOT_DURATION / 2; + pub const MinimumPeriod: u64 = SLOT_DURATION / 2; } impl pallet_timestamp::Config for Runtime { - /// A timestamp: milliseconds since the unix epoch. - type Moment = u64; - type OnTimestampSet = (); - type MinimumPeriod = MinimumPeriod; - type WeightInfo = weights::pallet_timestamp::SubstrateWeight; + /// A timestamp: milliseconds since the unix epoch. + type Moment = u64; + type OnTimestampSet = (); + type MinimumPeriod = MinimumPeriod; + type WeightInfo = weights::pallet_timestamp::SubstrateWeight; } impl pallet_authorship::Config for Runtime { - type FindAuthor = pallet_session::FindAccountFromAuthorIndex; - type UncleGenerations = ConstU32<0>; - type FilterUncle = (); - type EventHandler = (CollatorSelection,); + type FindAuthor = pallet_session::FindAccountFromAuthorIndex; + type UncleGenerations = ConstU32<0>; + type FilterUncle = (); + type EventHandler = (CollatorSelection,); } parameter_types! { - pub const NativeTokenExistentialDeposit: u128 = 10 * cDOL; // 0.1 DOL + pub const NativeTokenExistentialDeposit: u128 = 10 * cDOL; // 0.1 DOL } impl pallet_balances::Config for Runtime { - type MaxLocks = ConstU32<50>; - type MaxReserves = ConstU32<50>; - type ReserveIdentifier = [u8; 8]; - type Balance = Balance; - type DustRemoval = (); - type Event = Event; - type ExistentialDeposit = NativeTokenExistentialDeposit; - type AccountStore = frame_system::Pallet; - type WeightInfo = weights::pallet_balances::SubstrateWeight; + type MaxLocks = ConstU32<50>; + type MaxReserves = ConstU32<50>; + type ReserveIdentifier = [u8; 8]; + type Balance = Balance; + type DustRemoval = (); + type Event = Event; + type ExistentialDeposit = NativeTokenExistentialDeposit; + type AccountStore = frame_system::Pallet; + type WeightInfo = weights::pallet_balances::SubstrateWeight; } parameter_types! { - /// Relay Chain `TransactionByteFee` / 10 - pub const TransactionByteFee: Balance = mDOL / 100; + /// Relay Chain `TransactionByteFee` / 10 + pub const TransactionByteFee: Balance = mDOL / 100; } impl pallet_transaction_payment::Config for Runtime { - type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter; - type TransactionByteFee = TransactionByteFee; - type WeightToFee = WeightToFee; - type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; - type OperationalFeeMultiplier = ConstU8<5>; + type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter; + type TransactionByteFee = TransactionByteFee; + type WeightToFee = WeightToFee; + type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; + type OperationalFeeMultiplier = ConstU8<5>; } parameter_types! { - // One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes. - pub const DepositBase: Balance = deposit(1, 88); - // Additional storage item size of 32 bytes. - pub const DepositFactor: Balance = deposit(0, 32); + // One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes. + pub const DepositBase: Balance = deposit(1, 88); + // Additional storage item size of 32 bytes. + pub const DepositFactor: Balance = deposit(0, 32); } impl pallet_multisig::Config for Runtime { - type Event = Event; - type Call = Call; - type Currency = Balances; - type DepositBase = DepositBase; - type DepositFactor = DepositFactor; - type MaxSignatories = ConstU16<100>; - type WeightInfo = weights::pallet_multisig::SubstrateWeight; + type Event = Event; + type Call = Call; + type Currency = Balances; + type DepositBase = DepositBase; + type DepositFactor = DepositFactor; + type MaxSignatories = ConstU16<100>; + type WeightInfo = weights::pallet_multisig::SubstrateWeight; } impl pallet_utility::Config for Runtime { - type Event = Event; - type Call = Call; - type PalletsOrigin = OriginCaller; - type WeightInfo = weights::pallet_utility::SubstrateWeight; + type Event = Event; + type Call = Call; + type PalletsOrigin = OriginCaller; + type WeightInfo = weights::pallet_utility::SubstrateWeight; } impl pallet_sudo::Config for Runtime { - type Event = Event; - type Call = Call; + type Event = Event; + type Call = Call; } parameter_types! { - pub LaunchPeriod: BlockNumber = prod_or_fast!(5 * MINUTES, 1 * MINUTES, "DOLPHIN_LAUNCHPERIOD"); - pub VotingPeriod: BlockNumber = prod_or_fast!(5 * MINUTES, 1 * MINUTES, "DOLPHIN_VOTINGPERIOD"); - pub FastTrackVotingPeriod: BlockNumber = prod_or_fast!(5 * MINUTES, 1 * MINUTES, "DOLPHIN_FASTTRACKVOTINGPERIOD"); - pub const InstantAllowed: bool = true; - pub const MinimumDeposit: Balance = 20 * DOL; - pub EnactmentPeriod: BlockNumber = prod_or_fast!(5 * MINUTES, 1 * MINUTES, "DOLPHIN_ENACTMENTPERIOD"); - pub CooloffPeriod: BlockNumber = prod_or_fast!(5 * MINUTES, 1 * MINUTES, "DOLPHIN_COOLOFFPERIOD"); - pub const PreimageByteDeposit: Balance = deposit(0, 1); + pub LaunchPeriod: BlockNumber = prod_or_fast!(5 * MINUTES, 1 * MINUTES, "DOLPHIN_LAUNCHPERIOD"); + pub VotingPeriod: BlockNumber = prod_or_fast!(5 * MINUTES, 1 * MINUTES, "DOLPHIN_VOTINGPERIOD"); + pub FastTrackVotingPeriod: BlockNumber = prod_or_fast!(5 * MINUTES, 1 * MINUTES, "DOLPHIN_FASTTRACKVOTINGPERIOD"); + pub const InstantAllowed: bool = true; + pub const MinimumDeposit: Balance = 20 * DOL; + pub EnactmentPeriod: BlockNumber = prod_or_fast!(5 * MINUTES, 1 * MINUTES, "DOLPHIN_ENACTMENTPERIOD"); + pub CooloffPeriod: BlockNumber = prod_or_fast!(5 * MINUTES, 1 * MINUTES, "DOLPHIN_COOLOFFPERIOD"); + pub const PreimageByteDeposit: Balance = deposit(0, 1); } impl pallet_democracy::Config for Runtime { - type Proposal = Call; - type Event = Event; - type Currency = Balances; - type EnactmentPeriod = EnactmentPeriod; - type VoteLockingPeriod = EnactmentPeriod; - type LaunchPeriod = LaunchPeriod; - type VotingPeriod = VotingPeriod; - type MinimumDeposit = MinimumDeposit; - /// A straight majority of the council can decide what their next motion is. - type ExternalOrigin = - pallet_collective::EnsureProportionAtLeast; - /// A super-majority can have the next scheduled referendum be a straight majority-carries vote. - type ExternalMajorityOrigin = - pallet_collective::EnsureProportionAtLeast; - /// A unanimous council can have the next scheduled referendum be a straight default-carries - /// (NTB) vote. - type ExternalDefaultOrigin = - pallet_collective::EnsureProportionAtLeast; - /// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote - /// be tabled immediately and with a shorter voting/enactment period. - type FastTrackOrigin = - pallet_collective::EnsureProportionAtLeast; - type InstantOrigin = - pallet_collective::EnsureProportionAtLeast; - type InstantAllowed = InstantAllowed; - type FastTrackVotingPeriod = FastTrackVotingPeriod; - // To cancel a proposal which has been passed, 2/3 of the council must agree to it. - type CancellationOrigin = - pallet_collective::EnsureProportionAtLeast; - // To cancel a proposal before it has been passed, the technical committee must be unanimous or - // Root must agree. - type CancelProposalOrigin = EnsureOneOf< - EnsureRoot, - pallet_collective::EnsureProportionAtLeast, - >; - type BlacklistOrigin = EnsureRoot; - // Any single technical committee member may veto a coming council proposal, however they can - // only do it once and it lasts only for the cool-off period. - type VetoOrigin = pallet_collective::EnsureMember; - type CooloffPeriod = CooloffPeriod; - type PreimageByteDeposit = PreimageByteDeposit; - type OperationalPreimageOrigin = pallet_collective::EnsureMember; - type Slash = (); - type Scheduler = Scheduler; - type PalletsOrigin = OriginCaller; - type MaxVotes = ConstU32<100>; - type WeightInfo = weights::pallet_democracy::SubstrateWeight; - type MaxProposals = ConstU32<100>; + type Proposal = Call; + type Event = Event; + type Currency = Balances; + type EnactmentPeriod = EnactmentPeriod; + type VoteLockingPeriod = EnactmentPeriod; + type LaunchPeriod = LaunchPeriod; + type VotingPeriod = VotingPeriod; + type MinimumDeposit = MinimumDeposit; + /// A straight majority of the council can decide what their next motion is. + type ExternalOrigin = + pallet_collective::EnsureProportionAtLeast; + /// A super-majority can have the next scheduled referendum be a straight majority-carries vote. + type ExternalMajorityOrigin = + pallet_collective::EnsureProportionAtLeast; + /// A unanimous council can have the next scheduled referendum be a straight default-carries + /// (NTB) vote. + type ExternalDefaultOrigin = + pallet_collective::EnsureProportionAtLeast; + /// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote + /// be tabled immediately and with a shorter voting/enactment period. + type FastTrackOrigin = + pallet_collective::EnsureProportionAtLeast; + type InstantOrigin = + pallet_collective::EnsureProportionAtLeast; + type InstantAllowed = InstantAllowed; + type FastTrackVotingPeriod = FastTrackVotingPeriod; + // To cancel a proposal which has been passed, 2/3 of the council must agree to it. + type CancellationOrigin = + pallet_collective::EnsureProportionAtLeast; + // To cancel a proposal before it has been passed, the technical committee must be unanimous or + // Root must agree. + type CancelProposalOrigin = EnsureOneOf< + EnsureRoot, + pallet_collective::EnsureProportionAtLeast, + >; + type BlacklistOrigin = EnsureRoot; + // Any single technical committee member may veto a coming council proposal, however they can + // only do it once and it lasts only for the cool-off period. + type VetoOrigin = pallet_collective::EnsureMember; + type CooloffPeriod = CooloffPeriod; + type PreimageByteDeposit = PreimageByteDeposit; + type OperationalPreimageOrigin = pallet_collective::EnsureMember; + type Slash = (); + type Scheduler = Scheduler; + type PalletsOrigin = OriginCaller; + type MaxVotes = ConstU32<100>; + type WeightInfo = weights::pallet_democracy::SubstrateWeight; + type MaxProposals = ConstU32<100>; } parameter_types! { - /// The maximum amount of time (in blocks) for council members to vote on motions. - /// Motions may end in fewer blocks if enough votes are cast to determine the result. - pub const CouncilMotionDuration: BlockNumber = 3 * DAYS; + /// The maximum amount of time (in blocks) for council members to vote on motions. + /// Motions may end in fewer blocks if enough votes are cast to determine the result. + pub const CouncilMotionDuration: BlockNumber = 3 * DAYS; } type CouncilCollective = pallet_collective::Instance1; impl pallet_collective::Config for Runtime { - type Origin = Origin; - type Proposal = Call; - type Event = Event; - type MotionDuration = CouncilMotionDuration; - type MaxProposals = ConstU32<100>; - type MaxMembers = ConstU32<100>; - type DefaultVote = pallet_collective::PrimeDefaultVote; - type WeightInfo = weights::pallet_collective::SubstrateWeight; + type Origin = Origin; + type Proposal = Call; + type Event = Event; + type MotionDuration = CouncilMotionDuration; + type MaxProposals = ConstU32<100>; + type MaxMembers = ConstU32<100>; + type DefaultVote = pallet_collective::PrimeDefaultVote; + type WeightInfo = weights::pallet_collective::SubstrateWeight; } pub type EnsureRootOrThreeFourthsCouncil = EnsureOneOf< - EnsureRoot, - pallet_collective::EnsureProportionAtLeast, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast, >; type CouncilMembershipInstance = pallet_membership::Instance1; impl pallet_membership::Config for Runtime { - type Event = Event; - type AddOrigin = EnsureRootOrThreeFourthsCouncil; - type RemoveOrigin = EnsureRootOrThreeFourthsCouncil; - type SwapOrigin = EnsureRootOrThreeFourthsCouncil; - type ResetOrigin = EnsureRootOrThreeFourthsCouncil; - type PrimeOrigin = EnsureRootOrThreeFourthsCouncil; - type MembershipInitialized = Council; - type MembershipChanged = Council; - type MaxMembers = ConstU32<100>; - type WeightInfo = weights::pallet_membership::SubstrateWeight; + type Event = Event; + type AddOrigin = EnsureRootOrThreeFourthsCouncil; + type RemoveOrigin = EnsureRootOrThreeFourthsCouncil; + type SwapOrigin = EnsureRootOrThreeFourthsCouncil; + type ResetOrigin = EnsureRootOrThreeFourthsCouncil; + type PrimeOrigin = EnsureRootOrThreeFourthsCouncil; + type MembershipInitialized = Council; + type MembershipChanged = Council; + type MaxMembers = ConstU32<100>; + type WeightInfo = weights::pallet_membership::SubstrateWeight; } parameter_types! { - pub const TechnicalMotionDuration: BlockNumber = 3 * DAYS; + pub const TechnicalMotionDuration: BlockNumber = 3 * DAYS; } type TechnicalCollective = pallet_collective::Instance2; impl pallet_collective::Config for Runtime { - type Origin = Origin; - type Proposal = Call; - type Event = Event; - type MotionDuration = TechnicalMotionDuration; - type MaxProposals = ConstU32<100>; - type MaxMembers = ConstU32<100>; - type DefaultVote = pallet_collective::PrimeDefaultVote; - type WeightInfo = weights::pallet_collective::SubstrateWeight; + type Origin = Origin; + type Proposal = Call; + type Event = Event; + type MotionDuration = TechnicalMotionDuration; + type MaxProposals = ConstU32<100>; + type MaxMembers = ConstU32<100>; + type DefaultVote = pallet_collective::PrimeDefaultVote; + type WeightInfo = weights::pallet_collective::SubstrateWeight; } type TechnicalMembershipInstance = pallet_membership::Instance2; impl pallet_membership::Config for Runtime { - type Event = Event; - type AddOrigin = EnsureRootOrThreeFourthsCouncil; - type RemoveOrigin = EnsureRootOrThreeFourthsCouncil; - type SwapOrigin = EnsureRootOrThreeFourthsCouncil; - type ResetOrigin = EnsureRootOrThreeFourthsCouncil; - type PrimeOrigin = EnsureRootOrThreeFourthsCouncil; - type MembershipInitialized = TechnicalCommittee; - type MembershipChanged = TechnicalCommittee; - type MaxMembers = ConstU32<100>; - type WeightInfo = weights::pallet_membership::SubstrateWeight; + type Event = Event; + type AddOrigin = EnsureRootOrThreeFourthsCouncil; + type RemoveOrigin = EnsureRootOrThreeFourthsCouncil; + type SwapOrigin = EnsureRootOrThreeFourthsCouncil; + type ResetOrigin = EnsureRootOrThreeFourthsCouncil; + type PrimeOrigin = EnsureRootOrThreeFourthsCouncil; + type MembershipInitialized = TechnicalCommittee; + type MembershipChanged = TechnicalCommittee; + type MaxMembers = ConstU32<100>; + type WeightInfo = weights::pallet_membership::SubstrateWeight; } parameter_types! { - pub const ProposalBond: Permill = Permill::from_percent(1); - pub const ProposalBondMinimum: Balance = 500 * DOL; - pub const ProposalBondMaximum: Balance = 10_000 * DOL; - pub SpendPeriod: BlockNumber = prod_or_fast!(10 * MINUTES, 2 * MINUTES, "DOLPHIN_SPENDPERIOD"); - pub const Burn: Permill = Permill::from_percent(0); - pub const TreasuryPalletId: PalletId = TREASURY_PALLET_ID; + pub const ProposalBond: Permill = Permill::from_percent(1); + pub const ProposalBondMinimum: Balance = 500 * DOL; + pub const ProposalBondMaximum: Balance = 10_000 * DOL; + pub SpendPeriod: BlockNumber = prod_or_fast!(10 * MINUTES, 2 * MINUTES, "DOLPHIN_SPENDPERIOD"); + pub const Burn: Permill = Permill::from_percent(0); + pub const TreasuryPalletId: PalletId = TREASURY_PALLET_ID; } type EnsureRootOrThreeFifthsCouncil = EnsureOneOf< - EnsureRoot, - pallet_collective::EnsureProportionAtLeast, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast, >; type EnsureRootOrMoreThanHalfCouncil = EnsureOneOf< - EnsureRoot, - pallet_collective::EnsureProportionMoreThan, + EnsureRoot, + pallet_collective::EnsureProportionMoreThan, >; impl pallet_treasury::Config for Runtime { - type PalletId = TreasuryPalletId; - type Currency = Balances; - type ApproveOrigin = EnsureRootOrThreeFifthsCouncil; - type RejectOrigin = EnsureRootOrMoreThanHalfCouncil; - type Event = Event; - type OnSlash = Treasury; - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ProposalBondMinimum; - type ProposalBondMaximum = ProposalBondMaximum; - type SpendPeriod = SpendPeriod; - type Burn = Burn; - type BurnDestination = (); - type MaxApprovals = ConstU32<100>; - type WeightInfo = weights::pallet_treasury::SubstrateWeight; - type SpendFunds = (); + type PalletId = TreasuryPalletId; + type Currency = Balances; + type ApproveOrigin = EnsureRootOrThreeFifthsCouncil; + type RejectOrigin = EnsureRootOrMoreThanHalfCouncil; + type Event = Event; + type OnSlash = Treasury; + type ProposalBond = ProposalBond; + type ProposalBondMinimum = ProposalBondMinimum; + type ProposalBondMaximum = ProposalBondMaximum; + type SpendPeriod = SpendPeriod; + type Burn = Burn; + type BurnDestination = (); + type MaxApprovals = ConstU32<100>; + type WeightInfo = weights::pallet_treasury::SubstrateWeight; + type SpendFunds = (); } parameter_types! { - pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * - RuntimeBlockWeights::get().max_block; - pub const NoPreimagePostponement: Option = Some(10); + pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * + RuntimeBlockWeights::get().max_block; + pub const NoPreimagePostponement: Option = Some(10); } type ScheduleOrigin = EnsureRoot; /// Used the compare the privilege of an origin inside the scheduler. pub struct OriginPrivilegeCmp; impl PrivilegeCmp for OriginPrivilegeCmp { - fn cmp_privilege(left: &OriginCaller, right: &OriginCaller) -> Option { - if left == right { - return Some(Ordering::Equal); - } - - match (left, right) { - // Root is greater than anything. - (OriginCaller::system(frame_system::RawOrigin::Root), _) => Some(Ordering::Greater), - // Check which one has more yes votes. - ( - OriginCaller::Council(pallet_collective::RawOrigin::Members(l_yes_votes, l_count)), - OriginCaller::Council(pallet_collective::RawOrigin::Members(r_yes_votes, r_count)), - ) => Some((l_yes_votes * r_count).cmp(&(r_yes_votes * l_count))), - // For every other origin we don't care, as they are not used for `ScheduleOrigin`. - _ => None, - } - } + fn cmp_privilege(left: &OriginCaller, right: &OriginCaller) -> Option { + if left == right { + return Some(Ordering::Equal); + } + + match (left, right) { + // Root is greater than anything. + (OriginCaller::system(frame_system::RawOrigin::Root), _) => Some(Ordering::Greater), + // Check which one has more yes votes. + ( + OriginCaller::Council(pallet_collective::RawOrigin::Members(l_yes_votes, l_count)), + OriginCaller::Council(pallet_collective::RawOrigin::Members(r_yes_votes, r_count)), + ) => Some((l_yes_votes * r_count).cmp(&(r_yes_votes * l_count))), + // For every other origin we don't care, as they are not used for `ScheduleOrigin`. + _ => None, + } + } } impl pallet_scheduler::Config for Runtime { - type Event = Event; - type Origin = Origin; - type PalletsOrigin = OriginCaller; - type Call = Call; - type MaximumWeight = MaximumSchedulerWeight; - type ScheduleOrigin = ScheduleOrigin; - type MaxScheduledPerBlock = ConstU32<50>; // 50 scheduled calls at most in the queue for a single block. - type WeightInfo = weights::pallet_scheduler::SubstrateWeight; - type OriginPrivilegeCmp = OriginPrivilegeCmp; - type PreimageProvider = Preimage; - type NoPreimagePostponement = NoPreimagePostponement; + type Event = Event; + type Origin = Origin; + type PalletsOrigin = OriginCaller; + type Call = Call; + type MaximumWeight = MaximumSchedulerWeight; + type ScheduleOrigin = ScheduleOrigin; + type MaxScheduledPerBlock = ConstU32<50>; // 50 scheduled calls at most in the queue for a single block. + type WeightInfo = weights::pallet_scheduler::SubstrateWeight; + type OriginPrivilegeCmp = OriginPrivilegeCmp; + type PreimageProvider = Preimage; + type NoPreimagePostponement = NoPreimagePostponement; } parameter_types! { - // Our NORMAL_DISPATCH_RATIO is 70% of the 5MB limit - // So anything more than 3.5MB doesn't make sense here - pub const PreimageMaxSize: u32 = 3584 * 1024; - pub const PreimageBaseDeposit: Balance = 1 * DOL; + // Our NORMAL_DISPATCH_RATIO is 70% of the 5MB limit + // So anything more than 3.5MB doesn't make sense here + pub const PreimageMaxSize: u32 = 3584 * 1024; + pub const PreimageBaseDeposit: Balance = 1 * DOL; } impl pallet_preimage::Config for Runtime { - type WeightInfo = weights::pallet_preimage::SubstrateWeight; - type Event = Event; - type Currency = Balances; - type ManagerOrigin = EnsureRoot; - type MaxSize = PreimageMaxSize; - // The sum of the below 2 amounts will get reserved every time someone submits a preimage. - // Their sum will be unreserved when the preimage is requested, i.e. when it is going to be used. - type BaseDeposit = PreimageBaseDeposit; - type ByteDeposit = PreimageByteDeposit; + type WeightInfo = weights::pallet_preimage::SubstrateWeight; + type Event = Event; + type Currency = Balances; + type ManagerOrigin = EnsureRoot; + type MaxSize = PreimageMaxSize; + // The sum of the below 2 amounts will get reserved every time someone submits a preimage. + // Their sum will be unreserved when the preimage is requested, i.e. when it is going to be used. + type BaseDeposit = PreimageBaseDeposit; + type ByteDeposit = PreimageByteDeposit; } parameter_types! { - // Rotate collator's spot each 6 hours. - pub Period: u32 = prod_or_fast!(6 * HOURS, 2 * MINUTES, "DOLPHIN_PERIOD"); - pub const Offset: u32 = 0; + // Rotate collator's spot each 6 hours. + pub Period: u32 = prod_or_fast!(6 * HOURS, 2 * MINUTES, "DOLPHIN_PERIOD"); + pub const Offset: u32 = 0; } impl pallet_session::Config for Runtime { - type Event = Event; - type ValidatorId = ::AccountId; - // we don't have stash and controller, thus we don't need the convert as well. - type ValidatorIdOf = manta_collator_selection::IdentityCollator; - type ShouldEndSession = pallet_session::PeriodicSessions; - type NextSessionRotation = pallet_session::PeriodicSessions; - type SessionManager = CollatorSelection; - // Essentially just Aura, but lets be pedantic. - type SessionHandler = - ::KeyTypeIdProviders; - type Keys = opaque::SessionKeys; - type WeightInfo = weights::pallet_session::SubstrateWeight; + type Event = Event; + type ValidatorId = ::AccountId; + // we don't have stash and controller, thus we don't need the convert as well. + type ValidatorIdOf = manta_collator_selection::IdentityCollator; + type ShouldEndSession = pallet_session::PeriodicSessions; + type NextSessionRotation = pallet_session::PeriodicSessions; + type SessionManager = CollatorSelection; + // Essentially just Aura, but lets be pedantic. + type SessionHandler = + ::KeyTypeIdProviders; + type Keys = opaque::SessionKeys; + type WeightInfo = weights::pallet_session::SubstrateWeight; } impl pallet_aura::Config for Runtime { - type AuthorityId = AuraId; - type DisabledValidators = (); - type MaxAuthorities = ConstU32<100_000>; + type AuthorityId = AuraId; + type DisabledValidators = (); + type MaxAuthorities = ConstU32<100_000>; } parameter_types! { - // Pallet account for record rewards and give rewards to collator. - pub const PotId: PalletId = STAKING_PALLET_ID; + // Pallet account for record rewards and give rewards to collator. + pub const PotId: PalletId = STAKING_PALLET_ID; } parameter_types! { - pub const ExecutiveBody: BodyId = BodyId::Executive; + pub const ExecutiveBody: BodyId = BodyId::Executive; } /// We allow root and the Relay Chain council to execute privileged collator selection operations. pub type CollatorSelectionUpdateOrigin = EnsureOneOf< - EnsureRoot, - pallet_collective::EnsureProportionAtLeast, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast, >; impl manta_collator_selection::Config for Runtime { - type Event = Event; - type Currency = Balances; - type UpdateOrigin = CollatorSelectionUpdateOrigin; - type PotId = PotId; - type MaxCandidates = ConstU32<50>; // 50 candidates at most - type MaxInvulnerables = ConstU32<5>; // 5 invulnerables at most - type ValidatorId = ::AccountId; - type ValidatorIdOf = manta_collator_selection::IdentityCollator; - type AccountIdOf = manta_collator_selection::IdentityCollator; - type ValidatorRegistration = Session; - type WeightInfo = weights::manta_collator_selection::SubstrateWeight; + type Event = Event; + type Currency = Balances; + type UpdateOrigin = CollatorSelectionUpdateOrigin; + type PotId = PotId; + type MaxCandidates = ConstU32<50>; // 50 candidates at most + type MaxInvulnerables = ConstU32<5>; // 5 invulnerables at most + type ValidatorId = ::AccountId; + type ValidatorIdOf = manta_collator_selection::IdentityCollator; + type AccountIdOf = manta_collator_selection::IdentityCollator; + type ValidatorRegistration = Session; + type WeightInfo = weights::manta_collator_selection::SubstrateWeight; } // Create the runtime by composing the FRAME pallets that were previously configured. construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = opaque::Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - // System support stuff. - System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, - ParachainSystem: cumulus_pallet_parachain_system::{ - Pallet, Call, Config, Storage, Inherent, Event, ValidateUnsigned, - } = 1, - Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 2, - ParachainInfo: parachain_info::{Pallet, Storage, Config} = 3, - TransactionPause: pallet_tx_pause::{Pallet, Call, Storage, Event} = 9, - - // Monetary stuff. - Balances: pallet_balances::{Pallet, Call, Storage, Config, Event} = 10, - TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 11, - - // Governance stuff. - Democracy: pallet_democracy::{Pallet, Call, Storage, Config, Event} = 14, - Council: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 15, - CouncilMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 16, - TechnicalCommittee: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 17, - TechnicalMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 18, - - // Collator support. the order of these 5 are important and shall not change. - Authorship: pallet_authorship::{Pallet, Call, Storage} = 20, - CollatorSelection: manta_collator_selection::{Pallet, Call, Storage, Event, Config} = 21, - Session: pallet_session::{Pallet, Call, Storage, Event, Config} = 22, - Aura: pallet_aura::{Pallet, Storage, Config} = 23, - AuraExt: cumulus_pallet_aura_ext::{Pallet, Storage, Config} = 24, - - // Treasury - Treasury: pallet_treasury::{Pallet, Call, Storage, Event} = 26, - - // Preimage registrar. - Preimage: pallet_preimage::{Pallet, Call, Storage, Event} = 28, - // System scheduler. - Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event} = 29, - - // XCM helpers. - XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event} = 30, - PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event, Origin, Config} = 31, - CumulusXcm: cumulus_pallet_xcm::{Pallet, Event, Origin} = 32, - DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event} = 33, - XTokens: orml_xtokens::{Pallet, Call, Event, Storage} = 34, - - // Handy utilities. - Utility: pallet_utility::{Pallet, Call, Event} = 40, - Multisig: pallet_multisig::{Pallet, Call, Storage, Event} = 41, - Sudo: pallet_sudo::{Pallet, Call, Config, Storage, Event} = 42, - - // Asset and Private Payment - Assets: pallet_assets::{Pallet, Call, Storage, Event} = 45, - AssetManager: pallet_asset_manager::{Pallet, Call, Storage, Config, Event} = 46, - MantaPay: pallet_manta_pay::{Pallet, Call, Storage, Event} = 47, - } + pub enum Runtime where + Block = Block, + NodeBlock = opaque::Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + // System support stuff. + System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, + ParachainSystem: cumulus_pallet_parachain_system::{ + Pallet, Call, Config, Storage, Inherent, Event, ValidateUnsigned, + } = 1, + Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 2, + ParachainInfo: parachain_info::{Pallet, Storage, Config} = 3, + TransactionPause: pallet_tx_pause::{Pallet, Call, Storage, Event} = 9, + + // Monetary stuff. + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event} = 10, + TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 11, + + // Governance stuff. + Democracy: pallet_democracy::{Pallet, Call, Storage, Config, Event} = 14, + Council: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 15, + CouncilMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 16, + TechnicalCommittee: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 17, + TechnicalMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 18, + + // Collator support. the order of these 5 are important and shall not change. + Authorship: pallet_authorship::{Pallet, Call, Storage} = 20, + CollatorSelection: manta_collator_selection::{Pallet, Call, Storage, Event, Config} = 21, + Session: pallet_session::{Pallet, Call, Storage, Event, Config} = 22, + Aura: pallet_aura::{Pallet, Storage, Config} = 23, + AuraExt: cumulus_pallet_aura_ext::{Pallet, Storage, Config} = 24, + + // Treasury + Treasury: pallet_treasury::{Pallet, Call, Storage, Event} = 26, + + // Preimage registrar. + Preimage: pallet_preimage::{Pallet, Call, Storage, Event} = 28, + // System scheduler. + Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event} = 29, + + // XCM helpers. + XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event} = 30, + PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event, Origin, Config} = 31, + CumulusXcm: cumulus_pallet_xcm::{Pallet, Event, Origin} = 32, + DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event} = 33, + XTokens: orml_xtokens::{Pallet, Call, Event, Storage} = 34, + + // Handy utilities. + Utility: pallet_utility::{Pallet, Call, Event} = 40, + Multisig: pallet_multisig::{Pallet, Call, Storage, Event} = 41, + Sudo: pallet_sudo::{Pallet, Call, Config, Storage, Event} = 42, + + // Asset and Private Payment + Assets: pallet_assets::{Pallet, Call, Storage, Event} = 45, + AssetManager: pallet_asset_manager::{Pallet, Call, Storage, Config, Event} = 46, + MantaPay: pallet_manta_pay::{Pallet, Call, Storage, Event} = 47, + } ); /// The address format for describing accounts. @@ -710,13 +721,13 @@ pub type SignedBlock = generic::SignedBlock; pub type BlockId = generic::BlockId; /// The SignedExtension to the basic transaction logic. pub type SignedExtra = ( - frame_system::CheckSpecVersion, - frame_system::CheckTxVersion, - frame_system::CheckGenesis, - frame_system::CheckEra, - frame_system::CheckNonce, - frame_system::CheckWeight, - pallet_transaction_payment::ChargeTransactionPayment, + frame_system::CheckSpecVersion, + frame_system::CheckTxVersion, + frame_system::CheckGenesis, + frame_system::CheckEra, + frame_system::CheckNonce, + frame_system::CheckWeight, + pallet_transaction_payment::ChargeTransactionPayment, ); /// Unchecked extrinsic type as expected by this runtime. pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; @@ -724,11 +735,11 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; /// Executive: handles dispatch to the various modules. pub type Executive = frame_executive::Executive< - Runtime, - Block, - frame_system::ChainContext, - Runtime, - AllPalletsReversedWithSystemFirst, + Runtime, + Block, + frame_system::ChainContext, + Runtime, + AllPalletsReversedWithSystemFirst, >; #[cfg(feature = "runtime-benchmarks")] @@ -737,236 +748,236 @@ extern crate frame_benchmarking; #[cfg(feature = "runtime-benchmarks")] mod benches { - frame_benchmarking::define_benchmarks!( - // Substrate pallets - [pallet_balances, Balances] - [pallet_multisig, Multisig] - [frame_system, SystemBench::] - [pallet_timestamp, Timestamp] - [pallet_utility, Utility] - [pallet_democracy, Democracy] - [pallet_collective, Council] - [pallet_membership, CouncilMembership] - [pallet_treasury, Treasury] - [pallet_preimage, Preimage] - [pallet_scheduler, Scheduler] - [pallet_session, SessionBench::] - [pallet_assets, Assets] - // XCM - [cumulus_pallet_xcmp_queue, XcmpQueue] - // Manta pallets - [pallet_tx_pause, TransactionPause] - [manta_collator_selection, CollatorSelection] - [pallet_manta_pay, MantaPay] - [pallet_asset_manager, AssetManager] - ); + frame_benchmarking::define_benchmarks!( + // Substrate pallets + [pallet_balances, Balances] + [pallet_multisig, Multisig] + [frame_system, SystemBench::] + [pallet_timestamp, Timestamp] + [pallet_utility, Utility] + [pallet_democracy, Democracy] + [pallet_collective, Council] + [pallet_membership, CouncilMembership] + [pallet_treasury, Treasury] + [pallet_preimage, Preimage] + [pallet_scheduler, Scheduler] + [pallet_session, SessionBench::] + [pallet_assets, Assets] + // XCM + [cumulus_pallet_xcmp_queue, XcmpQueue] + // Manta pallets + [pallet_tx_pause, TransactionPause] + [manta_collator_selection, CollatorSelection] + [pallet_manta_pay, MantaPay] + [pallet_asset_manager, AssetManager] + ); } impl_runtime_apis! { - impl sp_consensus_aura::AuraApi for Runtime { - fn slot_duration() -> sp_consensus_aura::SlotDuration { - sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) - } - - fn authorities() -> Vec { - Aura::authorities().into_inner() - } - } - - impl sp_api::Core for Runtime { - fn version() -> RuntimeVersion { - VERSION - } - - fn execute_block(block: Block) { - Executive::execute_block(block) - } - - fn initialize_block(header: &::Header) { - Executive::initialize_block(header) - } - } - - impl sp_api::Metadata for Runtime { - fn metadata() -> OpaqueMetadata { - OpaqueMetadata::new(Runtime::metadata().into()) - } - } - - impl sp_block_builder::BlockBuilder for Runtime { - fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { - Executive::apply_extrinsic(extrinsic) - } - - fn finalize_block() -> ::Header { - Executive::finalize_block() - } - - fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { - data.create_extrinsics() - } - - fn check_inherents( - block: Block, - data: sp_inherents::InherentData, - ) -> sp_inherents::CheckInherentsResult { - data.check_extrinsics(&block) - } - } - - impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { - fn validate_transaction( - source: TransactionSource, - tx: ::Extrinsic, - block_hash: ::Hash, - ) -> TransactionValidity { - Executive::validate_transaction(source, tx, block_hash) - } - } - - impl sp_offchain::OffchainWorkerApi for Runtime { - fn offchain_worker(header: &::Header) { - Executive::offchain_worker(header) - } - } - - impl sp_session::SessionKeys for Runtime { - fn generate_session_keys(seed: Option>) -> Vec { - opaque::SessionKeys::generate(seed) - } - - fn decode_session_keys( - encoded: Vec, - ) -> Option, KeyTypeId)>> { - opaque::SessionKeys::decode_into_raw_public_keys(&encoded) - } - } - - impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { - fn account_nonce(account: AccountId) -> Index { - System::account_nonce(account) - } - } - - impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { - fn query_info( - uxt: ::Extrinsic, - len: u32, - ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { - TransactionPayment::query_info(uxt, len) - } - fn query_fee_details( - uxt: ::Extrinsic, - len: u32, - ) -> pallet_transaction_payment::FeeDetails { - TransactionPayment::query_fee_details(uxt, len) - } - } - - impl cumulus_primitives_core::CollectCollationInfo for Runtime { - fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { - ParachainSystem::collect_collation_info(header) - } - } - - impl pallet_manta_pay::runtime::PullLedgerDiffApi for Runtime { - fn pull_ledger_diff(checkpoint: pallet_manta_pay::RawCheckpoint) -> pallet_manta_pay::PullResponse { - MantaPay::pull_ledger_diff(checkpoint.into()) - } - } - - #[cfg(feature = "try-runtime")] - impl frame_try_runtime::TryRuntime for Runtime { - fn on_runtime_upgrade() -> (Weight, Weight) { - let weight = Executive::try_runtime_upgrade().unwrap(); - (weight, RuntimeBlockWeights::get().max_block) - } - - fn execute_block_no_check(block: Block) -> Weight { - Executive::execute_block_no_check(block) - } - } - - #[cfg(feature = "runtime-benchmarks")] - impl frame_benchmarking::Benchmark for Runtime { - fn benchmark_metadata(extra: bool) -> ( - Vec, - Vec, - ) { - use frame_benchmarking::{Benchmarking, BenchmarkList}; - use frame_support::traits::StorageInfoTrait; - use frame_system_benchmarking::Pallet as SystemBench; - use cumulus_pallet_session_benchmarking::Pallet as SessionBench; - - let mut list = Vec::::new(); - list_benchmarks!(list, extra); - - let storage_info = AllPalletsReversedWithSystemFirst::storage_info(); - - return (list, storage_info) - } - - fn dispatch_benchmark( - config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { - use frame_benchmarking::{Benchmarking, BenchmarkBatch, TrackedStorageKey}; - - use frame_system_benchmarking::Pallet as SystemBench; - impl frame_system_benchmarking::Config for Runtime {} - - use cumulus_pallet_session_benchmarking::Pallet as SessionBench; - impl cumulus_pallet_session_benchmarking::Config for Runtime {} - - let whitelist: Vec = vec![ - // Block Number - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(), - // Total Issuance - hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(), - // Execution Phase - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(), - // Event Count - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(), - // System Events - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(), - // Treasury Account - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da95ecffd7b6c0f78751baa9d281e0bfa3a6d6f646c70792f74727372790000000000000000000000000000000000000000").to_vec().into(), - ]; - - let mut batches = Vec::::new(); - let params = (&config, &whitelist); - - add_benchmarks!(params, batches); - - if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } - Ok(batches) - } - } + impl sp_consensus_aura::AuraApi for Runtime { + fn slot_duration() -> sp_consensus_aura::SlotDuration { + sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) + } + + fn authorities() -> Vec { + Aura::authorities().into_inner() + } + } + + impl sp_api::Core for Runtime { + fn version() -> RuntimeVersion { + VERSION + } + + fn execute_block(block: Block) { + Executive::execute_block(block) + } + + fn initialize_block(header: &::Header) { + Executive::initialize_block(header) + } + } + + impl sp_api::Metadata for Runtime { + fn metadata() -> OpaqueMetadata { + OpaqueMetadata::new(Runtime::metadata().into()) + } + } + + impl sp_block_builder::BlockBuilder for Runtime { + fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { + Executive::apply_extrinsic(extrinsic) + } + + fn finalize_block() -> ::Header { + Executive::finalize_block() + } + + fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { + data.create_extrinsics() + } + + fn check_inherents( + block: Block, + data: sp_inherents::InherentData, + ) -> sp_inherents::CheckInherentsResult { + data.check_extrinsics(&block) + } + } + + impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { + fn validate_transaction( + source: TransactionSource, + tx: ::Extrinsic, + block_hash: ::Hash, + ) -> TransactionValidity { + Executive::validate_transaction(source, tx, block_hash) + } + } + + impl sp_offchain::OffchainWorkerApi for Runtime { + fn offchain_worker(header: &::Header) { + Executive::offchain_worker(header) + } + } + + impl sp_session::SessionKeys for Runtime { + fn generate_session_keys(seed: Option>) -> Vec { + opaque::SessionKeys::generate(seed) + } + + fn decode_session_keys( + encoded: Vec, + ) -> Option, KeyTypeId)>> { + opaque::SessionKeys::decode_into_raw_public_keys(&encoded) + } + } + + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Index { + System::account_nonce(account) + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { + fn query_info( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { + TransactionPayment::query_info(uxt, len) + } + fn query_fee_details( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_fee_details(uxt, len) + } + } + + impl cumulus_primitives_core::CollectCollationInfo for Runtime { + fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { + ParachainSystem::collect_collation_info(header) + } + } + + impl pallet_manta_pay::runtime::PullLedgerDiffApi for Runtime { + fn pull_ledger_diff(checkpoint: pallet_manta_pay::RawCheckpoint) -> pallet_manta_pay::PullResponse { + MantaPay::pull_ledger_diff(checkpoint.into()) + } + } + + #[cfg(feature = "try-runtime")] + impl frame_try_runtime::TryRuntime for Runtime { + fn on_runtime_upgrade() -> (Weight, Weight) { + let weight = Executive::try_runtime_upgrade().unwrap(); + (weight, RuntimeBlockWeights::get().max_block) + } + + fn execute_block_no_check(block: Block) -> Weight { + Executive::execute_block_no_check(block) + } + } + + #[cfg(feature = "runtime-benchmarks")] + impl frame_benchmarking::Benchmark for Runtime { + fn benchmark_metadata(extra: bool) -> ( + Vec, + Vec, + ) { + use frame_benchmarking::{Benchmarking, BenchmarkList}; + use frame_support::traits::StorageInfoTrait; + use frame_system_benchmarking::Pallet as SystemBench; + use cumulus_pallet_session_benchmarking::Pallet as SessionBench; + + let mut list = Vec::::new(); + list_benchmarks!(list, extra); + + let storage_info = AllPalletsReversedWithSystemFirst::storage_info(); + + (list, storage_info) + } + + fn dispatch_benchmark( + config: frame_benchmarking::BenchmarkConfig + ) -> Result, sp_runtime::RuntimeString> { + use frame_benchmarking::{Benchmarking, BenchmarkBatch, TrackedStorageKey}; + + use frame_system_benchmarking::Pallet as SystemBench; + impl frame_system_benchmarking::Config for Runtime {} + + use cumulus_pallet_session_benchmarking::Pallet as SessionBench; + impl cumulus_pallet_session_benchmarking::Config for Runtime {} + + let whitelist: Vec = vec![ + // Block Number + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(), + // Total Issuance + hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(), + // Execution Phase + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(), + // Event Count + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(), + // System Events + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(), + // Treasury Account + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da95ecffd7b6c0f78751baa9d281e0bfa3a6d6f646c70792f74727372790000000000000000000000000000000000000000").to_vec().into(), + ]; + + let mut batches = Vec::::new(); + let params = (&config, &whitelist); + + add_benchmarks!(params, batches); + + if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } + Ok(batches) + } + } } struct CheckInherents; impl cumulus_pallet_parachain_system::CheckInherents for CheckInherents { - fn check_inherents( - block: &Block, - relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof, - ) -> sp_inherents::CheckInherentsResult { - let relay_chain_slot = relay_state_proof - .read_slot() - .expect("Could not read the relay chain slot from the proof"); - - let inherent_data = - cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration( - relay_chain_slot, - sp_std::time::Duration::from_secs(6), - ) - .create_inherent_data() - .expect("Could not create the timestamp inherent data"); - - inherent_data.check_extrinsics(block) - } + fn check_inherents( + block: &Block, + relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof, + ) -> sp_inherents::CheckInherentsResult { + let relay_chain_slot = relay_state_proof + .read_slot() + .expect("Could not read the relay chain slot from the proof"); + + let inherent_data = + cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration( + relay_chain_slot, + sp_std::time::Duration::from_secs(6), + ) + .create_inherent_data() + .expect("Could not create the timestamp inherent data"); + + inherent_data.check_extrinsics(block) + } } cumulus_pallet_parachain_system::register_validate_block! { - Runtime = Runtime, - BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::, - CheckInherents = CheckInherents, + Runtime = Runtime, + BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::, + CheckInherents = CheckInherents, } diff --git a/runtime/dolphin/src/weights/cumulus_pallet_xcmp_queue.rs b/runtime/dolphin/src/weights/cumulus_pallet_xcmp_queue.rs index c30ea089c..f5948e2ee 100644 --- a/runtime/dolphin/src/weights/cumulus_pallet_xcmp_queue.rs +++ b/runtime/dolphin/src/weights/cumulus_pallet_xcmp_queue.rs @@ -43,39 +43,39 @@ use sp_std::marker::PhantomData; /// Weight functions needed for cumulus_pallet_xcmp_queue. pub trait WeightInfo { - fn set_config_with_u32() -> Weight; - fn set_config_with_weight() -> Weight; + fn set_config_with_u32() -> Weight; + fn set_config_with_weight() -> Weight; } /// Weights for cumulus_pallet_xcmp_queue using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl cumulus_pallet_xcmp_queue::WeightInfo for SubstrateWeight { - // Storage: XcmpQueue QueueConfig (r:1 w:1) - fn set_config_with_u32() -> Weight { - (3_155_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: XcmpQueue QueueConfig (r:1 w:1) - fn set_config_with_weight() -> Weight { - (3_231_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } + // Storage: XcmpQueue QueueConfig (r:1 w:1) + fn set_config_with_u32() -> Weight { + (3_155_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: XcmpQueue QueueConfig (r:1 w:1) + fn set_config_with_weight() -> Weight { + (3_231_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: XcmpQueue QueueConfig (r:1 w:1) - fn set_config_with_u32() -> Weight { - (3_155_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: XcmpQueue QueueConfig (r:1 w:1) - fn set_config_with_weight() -> Weight { - (3_231_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } -} \ No newline at end of file + // Storage: XcmpQueue QueueConfig (r:1 w:1) + fn set_config_with_u32() -> Weight { + (3_155_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: XcmpQueue QueueConfig (r:1 w:1) + fn set_config_with_weight() -> Weight { + (3_231_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } +} diff --git a/runtime/dolphin/src/weights/frame_system.rs b/runtime/dolphin/src/weights/frame_system.rs index 6c2c5e37e..a62f1612f 100644 --- a/runtime/dolphin/src/weights/frame_system.rs +++ b/runtime/dolphin/src/weights/frame_system.rs @@ -43,91 +43,91 @@ use sp_std::marker::PhantomData; /// Weight functions needed for frame_system. pub trait WeightInfo { - fn remark(b: u32, ) -> Weight; - fn remark_with_event(b: u32, ) -> Weight; - fn set_heap_pages() -> Weight; - fn set_storage(i: u32, ) -> Weight; - fn kill_storage(i: u32, ) -> Weight; - fn kill_prefix(p: u32, ) -> Weight; + fn remark(b: u32, ) -> Weight; + fn remark_with_event(b: u32, ) -> Weight; + fn set_heap_pages() -> Weight; + fn set_storage(i: u32, ) -> Weight; + fn kill_storage(i: u32, ) -> Weight; + fn kill_prefix(p: u32, ) -> Weight; } /// Weights for frame_system using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl frame_system::WeightInfo for SubstrateWeight { - fn remark(_b: u32, ) -> Weight { - (1_672_000 as Weight) - } - fn remark_with_event(b: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - } - // Storage: System Digest (r:1 w:1) - // Storage: unknown [0x3a686561707061676573] (r:0 w:1) - fn set_heap_pages() -> Weight { - (2_834_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Skipped Metadata (r:0 w:0) - fn set_storage(i: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((493_000 as Weight).saturating_mul(i as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) - } - // Storage: Skipped Metadata (r:0 w:0) - fn kill_storage(i: u32, ) -> Weight { - (1_098_000 as Weight) - // Standard Error: 0 - .saturating_add((351_000 as Weight).saturating_mul(i as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) - } - // Storage: Skipped Metadata (r:0 w:0) - fn kill_prefix(p: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 1_000 - .saturating_add((822_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) - } + fn remark(_b: u32, ) -> Weight { + (1_672_000 as Weight) + } + fn remark_with_event(b: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + } + // Storage: System Digest (r:1 w:1) + // Storage: unknown [0x3a686561707061676573] (r:0 w:1) + fn set_heap_pages() -> Weight { + (2_834_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Skipped Metadata (r:0 w:0) + fn set_storage(i: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((493_000 as Weight).saturating_mul(i as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) + } + // Storage: Skipped Metadata (r:0 w:0) + fn kill_storage(i: u32, ) -> Weight { + (1_098_000 as Weight) + // Standard Error: 0 + .saturating_add((351_000 as Weight).saturating_mul(i as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) + } + // Storage: Skipped Metadata (r:0 w:0) + fn kill_prefix(p: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 1_000 + .saturating_add((822_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) + } } // For backwards compatibility and tests impl WeightInfo for () { - fn remark(_b: u32, ) -> Weight { - (1_672_000 as Weight) - } - fn remark_with_event(b: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - } - // Storage: System Digest (r:1 w:1) - // Storage: unknown [0x3a686561707061676573] (r:0 w:1) - fn set_heap_pages() -> Weight { - (2_834_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Skipped Metadata (r:0 w:0) - fn set_storage(i: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((493_000 as Weight).saturating_mul(i as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) - } - // Storage: Skipped Metadata (r:0 w:0) - fn kill_storage(i: u32, ) -> Weight { - (1_098_000 as Weight) - // Standard Error: 0 - .saturating_add((351_000 as Weight).saturating_mul(i as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) - } - // Storage: Skipped Metadata (r:0 w:0) - fn kill_prefix(p: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 1_000 - .saturating_add((822_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) - } -} \ No newline at end of file + fn remark(_b: u32, ) -> Weight { + (1_672_000 as Weight) + } + fn remark_with_event(b: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + } + // Storage: System Digest (r:1 w:1) + // Storage: unknown [0x3a686561707061676573] (r:0 w:1) + fn set_heap_pages() -> Weight { + (2_834_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Skipped Metadata (r:0 w:0) + fn set_storage(i: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((493_000 as Weight).saturating_mul(i as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) + } + // Storage: Skipped Metadata (r:0 w:0) + fn kill_storage(i: u32, ) -> Weight { + (1_098_000 as Weight) + // Standard Error: 0 + .saturating_add((351_000 as Weight).saturating_mul(i as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) + } + // Storage: Skipped Metadata (r:0 w:0) + fn kill_prefix(p: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 1_000 + .saturating_add((822_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) + } +} diff --git a/runtime/dolphin/src/weights/manta_collator_selection.rs b/runtime/dolphin/src/weights/manta_collator_selection.rs index cd843bfb0..8952c7a72 100644 --- a/runtime/dolphin/src/weights/manta_collator_selection.rs +++ b/runtime/dolphin/src/weights/manta_collator_selection.rs @@ -43,210 +43,210 @@ use sp_std::marker::PhantomData; /// Weight functions needed for manta_collator_selection. pub trait WeightInfo { - fn set_invulnerables(b: u32, ) -> Weight; - fn set_desired_candidates() -> Weight; - fn set_candidacy_bond() -> Weight; - fn set_eviction_baseline() -> Weight; - fn set_eviction_tolerance() -> Weight; - fn register_as_candidate(c: u32, ) -> Weight; - fn leave_intent(c: u32, ) -> Weight; - fn remove_collator(c: u32, ) -> Weight; - fn register_candidate(c: u32, ) -> Weight; - fn note_author() -> Weight; - fn new_session(c: u32, ) -> Weight; + fn set_invulnerables(b: u32, ) -> Weight; + fn set_desired_candidates() -> Weight; + fn set_candidacy_bond() -> Weight; + fn set_eviction_baseline() -> Weight; + fn set_eviction_tolerance() -> Weight; + fn register_as_candidate(c: u32, ) -> Weight; + fn leave_intent(c: u32, ) -> Weight; + fn remove_collator(c: u32, ) -> Weight; + fn register_candidate(c: u32, ) -> Weight; + fn note_author() -> Weight; + fn new_session(c: u32, ) -> Weight; } /// Weights for manta_collator_selection using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl manta_collator_selection::WeightInfo for SubstrateWeight { - // Storage: CollatorSelection Invulnerables (r:0 w:1) - fn set_invulnerables(b: u32, ) -> Weight { - (9_677_000 as Weight) - // Standard Error: 16_000 - .saturating_add((99_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection DesiredCandidates (r:0 w:1) - fn set_desired_candidates() -> Weight { - (10_756_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection CandidacyBond (r:0 w:1) - fn set_candidacy_bond() -> Weight { - (9_204_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection EvictionBaseline (r:0 w:1) - fn set_eviction_baseline() -> Weight { - (8_762_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection EvictionTolerance (r:0 w:1) - fn set_eviction_tolerance() -> Weight { - (8_900_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:1) - // Storage: CollatorSelection DesiredCandidates (r:1 w:0) - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: Session NextKeys (r:1 w:0) - // Storage: CollatorSelection CandidacyBond (r:1 w:0) - fn register_as_candidate(c: u32, ) -> Weight { - (38_497_000 as Weight) - // Standard Error: 5_000 - .saturating_add((298_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:1) - fn leave_intent(c: u32, ) -> Weight { - (25_779_000 as Weight) - // Standard Error: 4_000 - .saturating_add((270_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: CollatorSelection Candidates (r:1 w:1) - fn remove_collator(c: u32, ) -> Weight { - (28_838_000 as Weight) - // Standard Error: 4_000 - .saturating_add((253_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:1) - // Storage: CollatorSelection DesiredCandidates (r:1 w:0) - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: Session NextKeys (r:1 w:0) - // Storage: CollatorSelection CandidacyBond (r:1 w:0) - fn register_candidate(c: u32, ) -> Weight { - (38_419_000 as Weight) - // Standard Error: 6_000 - .saturating_add((271_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:2 w:2) - // Storage: CollatorSelection BlocksPerCollatorThisSession (r:1 w:1) - // Storage: System BlockWeight (r:1 w:1) - fn note_author() -> Weight { - (37_567_000 as Weight) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:0) - // Storage: CollatorSelection EvictionBaseline (r:1 w:0) - // Storage: CollatorSelection EvictionTolerance (r:1 w:0) - // Storage: CollatorSelection BlocksPerCollatorThisSession (r:2 w:2) - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: System BlockWeight (r:1 w:1) - // Storage: Session Validators (r:1 w:0) - // Storage: System Account (r:1 w:1) - fn new_session(c: u32, ) -> Weight { - (3_898_000 as Weight) - // Standard Error: 78_000 - .saturating_add((25_284_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads(6 as Weight)) - .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) - } + // Storage: CollatorSelection Invulnerables (r:0 w:1) + fn set_invulnerables(b: u32, ) -> Weight { + (9_677_000 as Weight) + // Standard Error: 16_000 + .saturating_add((99_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection DesiredCandidates (r:0 w:1) + fn set_desired_candidates() -> Weight { + (10_756_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection CandidacyBond (r:0 w:1) + fn set_candidacy_bond() -> Weight { + (9_204_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection EvictionBaseline (r:0 w:1) + fn set_eviction_baseline() -> Weight { + (8_762_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection EvictionTolerance (r:0 w:1) + fn set_eviction_tolerance() -> Weight { + (8_900_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:1) + // Storage: CollatorSelection DesiredCandidates (r:1 w:0) + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: Session NextKeys (r:1 w:0) + // Storage: CollatorSelection CandidacyBond (r:1 w:0) + fn register_as_candidate(c: u32, ) -> Weight { + (38_497_000 as Weight) + // Standard Error: 5_000 + .saturating_add((298_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:1) + fn leave_intent(c: u32, ) -> Weight { + (25_779_000 as Weight) + // Standard Error: 4_000 + .saturating_add((270_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: CollatorSelection Candidates (r:1 w:1) + fn remove_collator(c: u32, ) -> Weight { + (28_838_000 as Weight) + // Standard Error: 4_000 + .saturating_add((253_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:1) + // Storage: CollatorSelection DesiredCandidates (r:1 w:0) + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: Session NextKeys (r:1 w:0) + // Storage: CollatorSelection CandidacyBond (r:1 w:0) + fn register_candidate(c: u32, ) -> Weight { + (38_419_000 as Weight) + // Standard Error: 6_000 + .saturating_add((271_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:2 w:2) + // Storage: CollatorSelection BlocksPerCollatorThisSession (r:1 w:1) + // Storage: System BlockWeight (r:1 w:1) + fn note_author() -> Weight { + (37_567_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:0) + // Storage: CollatorSelection EvictionBaseline (r:1 w:0) + // Storage: CollatorSelection EvictionTolerance (r:1 w:0) + // Storage: CollatorSelection BlocksPerCollatorThisSession (r:2 w:2) + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: System BlockWeight (r:1 w:1) + // Storage: Session Validators (r:1 w:0) + // Storage: System Account (r:1 w:1) + fn new_session(c: u32, ) -> Weight { + (3_898_000 as Weight) + // Standard Error: 78_000 + .saturating_add((25_284_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(T::DbWeight::get().reads(6 as Weight)) + .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: CollatorSelection Invulnerables (r:0 w:1) - fn set_invulnerables(b: u32, ) -> Weight { - (9_677_000 as Weight) - // Standard Error: 16_000 - .saturating_add((99_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection DesiredCandidates (r:0 w:1) - fn set_desired_candidates() -> Weight { - (10_756_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection CandidacyBond (r:0 w:1) - fn set_candidacy_bond() -> Weight { - (9_204_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection EvictionBaseline (r:0 w:1) - fn set_eviction_baseline() -> Weight { - (8_762_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection EvictionTolerance (r:0 w:1) - fn set_eviction_tolerance() -> Weight { - (8_900_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:1) - // Storage: CollatorSelection DesiredCandidates (r:1 w:0) - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: Session NextKeys (r:1 w:0) - // Storage: CollatorSelection CandidacyBond (r:1 w:0) - fn register_as_candidate(c: u32, ) -> Weight { - (38_497_000 as Weight) - // Standard Error: 5_000 - .saturating_add((298_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:1) - fn leave_intent(c: u32, ) -> Weight { - (25_779_000 as Weight) - // Standard Error: 4_000 - .saturating_add((270_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: CollatorSelection Candidates (r:1 w:1) - fn remove_collator(c: u32, ) -> Weight { - (28_838_000 as Weight) - // Standard Error: 4_000 - .saturating_add((253_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:1) - // Storage: CollatorSelection DesiredCandidates (r:1 w:0) - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: Session NextKeys (r:1 w:0) - // Storage: CollatorSelection CandidacyBond (r:1 w:0) - fn register_candidate(c: u32, ) -> Weight { - (38_419_000 as Weight) - // Standard Error: 6_000 - .saturating_add((271_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:2 w:2) - // Storage: CollatorSelection BlocksPerCollatorThisSession (r:1 w:1) - // Storage: System BlockWeight (r:1 w:1) - fn note_author() -> Weight { - (37_567_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - } - // Storage: CollatorSelection Candidates (r:1 w:0) - // Storage: CollatorSelection EvictionBaseline (r:1 w:0) - // Storage: CollatorSelection EvictionTolerance (r:1 w:0) - // Storage: CollatorSelection BlocksPerCollatorThisSession (r:2 w:2) - // Storage: CollatorSelection Invulnerables (r:1 w:0) - // Storage: System BlockWeight (r:1 w:1) - // Storage: Session Validators (r:1 w:0) - // Storage: System Account (r:1 w:1) - fn new_session(c: u32, ) -> Weight { - (3_898_000 as Weight) - // Standard Error: 78_000 - .saturating_add((25_284_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(RocksDbWeight::get().reads(6 as Weight)) - .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) - } -} \ No newline at end of file + // Storage: CollatorSelection Invulnerables (r:0 w:1) + fn set_invulnerables(b: u32, ) -> Weight { + (9_677_000 as Weight) + // Standard Error: 16_000 + .saturating_add((99_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection DesiredCandidates (r:0 w:1) + fn set_desired_candidates() -> Weight { + (10_756_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection CandidacyBond (r:0 w:1) + fn set_candidacy_bond() -> Weight { + (9_204_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection EvictionBaseline (r:0 w:1) + fn set_eviction_baseline() -> Weight { + (8_762_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection EvictionTolerance (r:0 w:1) + fn set_eviction_tolerance() -> Weight { + (8_900_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:1) + // Storage: CollatorSelection DesiredCandidates (r:1 w:0) + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: Session NextKeys (r:1 w:0) + // Storage: CollatorSelection CandidacyBond (r:1 w:0) + fn register_as_candidate(c: u32, ) -> Weight { + (38_497_000 as Weight) + // Standard Error: 5_000 + .saturating_add((298_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:1) + fn leave_intent(c: u32, ) -> Weight { + (25_779_000 as Weight) + // Standard Error: 4_000 + .saturating_add((270_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: CollatorSelection Candidates (r:1 w:1) + fn remove_collator(c: u32, ) -> Weight { + (28_838_000 as Weight) + // Standard Error: 4_000 + .saturating_add((253_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:1) + // Storage: CollatorSelection DesiredCandidates (r:1 w:0) + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: Session NextKeys (r:1 w:0) + // Storage: CollatorSelection CandidacyBond (r:1 w:0) + fn register_candidate(c: u32, ) -> Weight { + (38_419_000 as Weight) + // Standard Error: 6_000 + .saturating_add((271_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:2 w:2) + // Storage: CollatorSelection BlocksPerCollatorThisSession (r:1 w:1) + // Storage: System BlockWeight (r:1 w:1) + fn note_author() -> Weight { + (37_567_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + // Storage: CollatorSelection Candidates (r:1 w:0) + // Storage: CollatorSelection EvictionBaseline (r:1 w:0) + // Storage: CollatorSelection EvictionTolerance (r:1 w:0) + // Storage: CollatorSelection BlocksPerCollatorThisSession (r:2 w:2) + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: System BlockWeight (r:1 w:1) + // Storage: Session Validators (r:1 w:0) + // Storage: System Account (r:1 w:1) + fn new_session(c: u32, ) -> Weight { + (3_898_000 as Weight) + // Standard Error: 78_000 + .saturating_add((25_284_000 as Weight).saturating_mul(c as Weight)) + .saturating_add(RocksDbWeight::get().reads(6 as Weight)) + .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) + } +} diff --git a/runtime/dolphin/src/weights/pallet_asset_manager.rs b/runtime/dolphin/src/weights/pallet_asset_manager.rs index ff5640d11..ec84db7ac 100644 --- a/runtime/dolphin/src/weights/pallet_asset_manager.rs +++ b/runtime/dolphin/src/weights/pallet_asset_manager.rs @@ -43,115 +43,115 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_asset_manager. pub trait WeightInfo { - fn register_asset() -> Weight; - fn set_units_per_second() -> Weight; - fn update_asset_location() -> Weight; - fn update_asset_metadata() -> Weight; - fn mint_asset() -> Weight; - fn set_min_xcm_fee() -> Weight; + fn register_asset() -> Weight; + fn set_units_per_second() -> Weight; + fn update_asset_location() -> Weight; + fn update_asset_metadata() -> Weight; + fn mint_asset() -> Weight; + fn set_min_xcm_fee() -> Weight; } /// Weights for pallet_asset_manager using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_asset_manager::WeightInfo for SubstrateWeight { - // Storage: AssetManager LocationAssetId (r:1 w:1) - // Storage: AssetManager NextAssetId (r:1 w:1) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Metadata (r:1 w:1) - // Storage: AssetManager AssetIdMetadata (r:0 w:1) - // Storage: AssetManager AssetIdLocation (r:0 w:1) - fn register_asset() -> Weight { - (85_983_000 as Weight) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(6 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: AssetManager UnitsPerSecond (r:0 w:1) - fn set_units_per_second() -> Weight { - (48_301_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:1) - // Storage: AssetManager LocationAssetId (r:1 w:2) - // Storage: AssetManager AllowedDestParaIds (r:1 w:1) - fn update_asset_location() -> Weight { - (61_726_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - // Storage: AssetManager AssetIdMetadata (r:0 w:1) - fn update_asset_metadata() -> Weight { - (62_874_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:1 w:1) - fn mint_asset() -> Weight { - (73_795_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: AssetManager MinXcmFee (r:0 w:1) - fn set_min_xcm_fee() -> Weight { - (42_941_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } + // Storage: AssetManager LocationAssetId (r:1 w:1) + // Storage: AssetManager NextAssetId (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + // Storage: AssetManager AssetIdLocation (r:0 w:1) + fn register_asset() -> Weight { + (85_983_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(6 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: AssetManager UnitsPerSecond (r:0 w:1) + fn set_units_per_second() -> Weight { + (48_301_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:1) + // Storage: AssetManager LocationAssetId (r:1 w:2) + // Storage: AssetManager AllowedDestParaIds (r:1 w:1) + fn update_asset_location() -> Weight { + (61_726_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + fn update_asset_metadata() -> Weight { + (62_874_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + fn mint_asset() -> Weight { + (73_795_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: AssetManager MinXcmFee (r:0 w:1) + fn set_min_xcm_fee() -> Weight { + (42_941_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: AssetManager LocationAssetId (r:1 w:1) - // Storage: AssetManager NextAssetId (r:1 w:1) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Metadata (r:1 w:1) - // Storage: AssetManager AssetIdMetadata (r:0 w:1) - // Storage: AssetManager AssetIdLocation (r:0 w:1) - fn register_asset() -> Weight { - (85_983_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(6 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: AssetManager UnitsPerSecond (r:0 w:1) - fn set_units_per_second() -> Weight { - (48_301_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:1) - // Storage: AssetManager LocationAssetId (r:1 w:2) - // Storage: AssetManager AllowedDestParaIds (r:1 w:1) - fn update_asset_location() -> Weight { - (61_726_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - // Storage: AssetManager AssetIdMetadata (r:0 w:1) - fn update_asset_metadata() -> Weight { - (62_874_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:1 w:1) - fn mint_asset() -> Weight { - (73_795_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: AssetManager MinXcmFee (r:0 w:1) - fn set_min_xcm_fee() -> Weight { - (42_941_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } -} \ No newline at end of file + // Storage: AssetManager LocationAssetId (r:1 w:1) + // Storage: AssetManager NextAssetId (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + // Storage: AssetManager AssetIdLocation (r:0 w:1) + fn register_asset() -> Weight { + (85_983_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(6 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: AssetManager UnitsPerSecond (r:0 w:1) + fn set_units_per_second() -> Weight { + (48_301_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:1) + // Storage: AssetManager LocationAssetId (r:1 w:2) + // Storage: AssetManager AllowedDestParaIds (r:1 w:1) + fn update_asset_location() -> Weight { + (61_726_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + fn update_asset_metadata() -> Weight { + (62_874_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + fn mint_asset() -> Weight { + (73_795_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: AssetManager MinXcmFee (r:0 w:1) + fn set_min_xcm_fee() -> Weight { + (42_941_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } +} diff --git a/runtime/dolphin/src/weights/pallet_assets.rs b/runtime/dolphin/src/weights/pallet_assets.rs index 48c441bdc..f692023d2 100644 --- a/runtime/dolphin/src/weights/pallet_assets.rs +++ b/runtime/dolphin/src/weights/pallet_assets.rs @@ -43,398 +43,398 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_assets. pub trait WeightInfo { - fn create() -> Weight; - fn force_create() -> Weight; - fn destroy(c: u32, s: u32, a: u32, ) -> Weight; - fn mint() -> Weight; - fn burn() -> Weight; - fn transfer() -> Weight; - fn transfer_keep_alive() -> Weight; - fn force_transfer() -> Weight; - fn freeze() -> Weight; - fn thaw() -> Weight; - fn freeze_asset() -> Weight; - fn thaw_asset() -> Weight; - fn transfer_ownership() -> Weight; - fn set_team() -> Weight; - fn set_metadata(n: u32, s: u32, ) -> Weight; - fn clear_metadata() -> Weight; - fn force_set_metadata(n: u32, s: u32, ) -> Weight; - fn force_clear_metadata() -> Weight; - fn force_asset_status() -> Weight; - fn approve_transfer() -> Weight; - fn transfer_approved() -> Weight; - fn cancel_approval() -> Weight; - fn force_cancel_approval() -> Weight; + fn create() -> Weight; + fn force_create() -> Weight; + fn destroy(c: u32, s: u32, a: u32, ) -> Weight; + fn mint() -> Weight; + fn burn() -> Weight; + fn transfer() -> Weight; + fn transfer_keep_alive() -> Weight; + fn force_transfer() -> Weight; + fn freeze() -> Weight; + fn thaw() -> Weight; + fn freeze_asset() -> Weight; + fn thaw_asset() -> Weight; + fn transfer_ownership() -> Weight; + fn set_team() -> Weight; + fn set_metadata(n: u32, s: u32, ) -> Weight; + fn clear_metadata() -> Weight; + fn force_set_metadata(n: u32, s: u32, ) -> Weight; + fn force_clear_metadata() -> Weight; + fn force_asset_status() -> Weight; + fn approve_transfer() -> Weight; + fn transfer_approved() -> Weight; + fn cancel_approval() -> Weight; + fn force_cancel_approval() -> Weight; } /// Weights for pallet_assets using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_assets::WeightInfo for SubstrateWeight { - // Storage: Assets Asset (r:1 w:1) - fn create() -> Weight { - (20_622_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - fn force_create() -> Weight { - (12_978_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:5002 w:5001) - // Storage: System Account (r:5000 w:5000) - // Storage: Assets Metadata (r:1 w:0) - // Storage: Assets Approvals (r:501 w:500) - fn destroy(c: u32, s: u32, a: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 40_000 - .saturating_add((16_237_000 as Weight).saturating_mul(c as Weight)) - // Standard Error: 40_000 - .saturating_add((18_786_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 405_000 - .saturating_add((10_320_000 as Weight).saturating_mul(a as Weight)) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) - .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(a as Weight))) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) - .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(a as Weight))) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:1 w:1) - fn mint() -> Weight { - (26_320_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:1 w:1) - fn burn() -> Weight { - (30_435_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - // Storage: System Account (r:1 w:1) - fn transfer() -> Weight { - (44_405_000 as Weight) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - // Storage: System Account (r:1 w:1) - fn transfer_keep_alive() -> Weight { - (40_122_000 as Weight) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - // Storage: System Account (r:1 w:1) - fn force_transfer() -> Weight { - (47_515_000 as Weight) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Account (r:1 w:1) - fn freeze() -> Weight { - (18_143_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Account (r:1 w:1) - fn thaw() -> Weight { - (17_324_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - fn freeze_asset() -> Weight { - (14_662_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - fn thaw_asset() -> Weight { - (14_213_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Metadata (r:1 w:0) - fn transfer_ownership() -> Weight { - (16_008_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - fn set_team() -> Weight { - (14_389_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - fn set_metadata(n: u32, s: u32, ) -> Weight { - (17_348_000 as Weight) - // Standard Error: 1_000 - .saturating_add((5_000 as Weight).saturating_mul(n as Weight)) - // Standard Error: 1_000 - .saturating_add((3_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - fn clear_metadata() -> Weight { - (17_727_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - fn force_set_metadata(_n: u32, s: u32, ) -> Weight { - (15_571_000 as Weight) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - fn force_clear_metadata() -> Weight { - (17_634_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - fn force_asset_status() -> Weight { - (13_550_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Approvals (r:1 w:1) - fn approve_transfer() -> Weight { - (19_960_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Assets Approvals (r:1 w:1) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - // Storage: System Account (r:1 w:1) - fn transfer_approved() -> Weight { - (54_158_000 as Weight) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().writes(5 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Approvals (r:1 w:1) - fn cancel_approval() -> Weight { - (20_416_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Approvals (r:1 w:1) - fn force_cancel_approval() -> Weight { - (21_390_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } + // Storage: Assets Asset (r:1 w:1) + fn create() -> Weight { + (20_622_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + fn force_create() -> Weight { + (12_978_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:5002 w:5001) + // Storage: System Account (r:5000 w:5000) + // Storage: Assets Metadata (r:1 w:0) + // Storage: Assets Approvals (r:501 w:500) + fn destroy(c: u32, s: u32, a: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 40_000 + .saturating_add((16_237_000 as Weight).saturating_mul(c as Weight)) + // Standard Error: 40_000 + .saturating_add((18_786_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 405_000 + .saturating_add((10_320_000 as Weight).saturating_mul(a as Weight)) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) + .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(a as Weight))) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) + .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(a as Weight))) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + fn mint() -> Weight { + (26_320_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + fn burn() -> Weight { + (30_435_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + // Storage: System Account (r:1 w:1) + fn transfer() -> Weight { + (44_405_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + // Storage: System Account (r:1 w:1) + fn transfer_keep_alive() -> Weight { + (40_122_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + // Storage: System Account (r:1 w:1) + fn force_transfer() -> Weight { + (47_515_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Account (r:1 w:1) + fn freeze() -> Weight { + (18_143_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Account (r:1 w:1) + fn thaw() -> Weight { + (17_324_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + fn freeze_asset() -> Weight { + (14_662_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + fn thaw_asset() -> Weight { + (14_213_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:0) + fn transfer_ownership() -> Weight { + (16_008_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + fn set_team() -> Weight { + (14_389_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + fn set_metadata(n: u32, s: u32, ) -> Weight { + (17_348_000 as Weight) + // Standard Error: 1_000 + .saturating_add((5_000 as Weight).saturating_mul(n as Weight)) + // Standard Error: 1_000 + .saturating_add((3_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + fn clear_metadata() -> Weight { + (17_727_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + fn force_set_metadata(_n: u32, s: u32, ) -> Weight { + (15_571_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + fn force_clear_metadata() -> Weight { + (17_634_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + fn force_asset_status() -> Weight { + (13_550_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Approvals (r:1 w:1) + fn approve_transfer() -> Weight { + (19_960_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Assets Approvals (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + // Storage: System Account (r:1 w:1) + fn transfer_approved() -> Weight { + (54_158_000 as Weight) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(5 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Approvals (r:1 w:1) + fn cancel_approval() -> Weight { + (20_416_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Approvals (r:1 w:1) + fn force_cancel_approval() -> Weight { + (21_390_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Assets Asset (r:1 w:1) - fn create() -> Weight { - (20_622_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - fn force_create() -> Weight { - (12_978_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:5002 w:5001) - // Storage: System Account (r:5000 w:5000) - // Storage: Assets Metadata (r:1 w:0) - // Storage: Assets Approvals (r:501 w:500) - fn destroy(c: u32, s: u32, a: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 40_000 - .saturating_add((16_237_000 as Weight).saturating_mul(c as Weight)) - // Standard Error: 40_000 - .saturating_add((18_786_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 405_000 - .saturating_add((10_320_000 as Weight).saturating_mul(a as Weight)) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) - .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(a as Weight))) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) - .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(a as Weight))) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:1 w:1) - fn mint() -> Weight { - (26_320_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:1 w:1) - fn burn() -> Weight { - (30_435_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - // Storage: System Account (r:1 w:1) - fn transfer() -> Weight { - (44_405_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - // Storage: System Account (r:1 w:1) - fn transfer_keep_alive() -> Weight { - (40_122_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - // Storage: System Account (r:1 w:1) - fn force_transfer() -> Weight { - (47_515_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Account (r:1 w:1) - fn freeze() -> Weight { - (18_143_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Account (r:1 w:1) - fn thaw() -> Weight { - (17_324_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - fn freeze_asset() -> Weight { - (14_662_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - fn thaw_asset() -> Weight { - (14_213_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Metadata (r:1 w:0) - fn transfer_ownership() -> Weight { - (16_008_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - fn set_team() -> Weight { - (14_389_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - fn set_metadata(n: u32, s: u32, ) -> Weight { - (17_348_000 as Weight) - // Standard Error: 1_000 - .saturating_add((5_000 as Weight).saturating_mul(n as Weight)) - // Standard Error: 1_000 - .saturating_add((3_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - fn clear_metadata() -> Weight { - (17_727_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - fn force_set_metadata(_n: u32, s: u32, ) -> Weight { - (15_571_000 as Weight) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - fn force_clear_metadata() -> Weight { - (17_634_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - fn force_asset_status() -> Weight { - (13_550_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Approvals (r:1 w:1) - fn approve_transfer() -> Weight { - (19_960_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Assets Approvals (r:1 w:1) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - // Storage: System Account (r:1 w:1) - fn transfer_approved() -> Weight { - (54_158_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(5 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Approvals (r:1 w:1) - fn cancel_approval() -> Weight { - (20_416_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Approvals (r:1 w:1) - fn force_cancel_approval() -> Weight { - (21_390_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } -} \ No newline at end of file + // Storage: Assets Asset (r:1 w:1) + fn create() -> Weight { + (20_622_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + fn force_create() -> Weight { + (12_978_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:5002 w:5001) + // Storage: System Account (r:5000 w:5000) + // Storage: Assets Metadata (r:1 w:0) + // Storage: Assets Approvals (r:501 w:500) + fn destroy(c: u32, s: u32, a: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 40_000 + .saturating_add((16_237_000 as Weight).saturating_mul(c as Weight)) + // Standard Error: 40_000 + .saturating_add((18_786_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 405_000 + .saturating_add((10_320_000 as Weight).saturating_mul(a as Weight)) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) + .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(a as Weight))) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) + .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(a as Weight))) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + fn mint() -> Weight { + (26_320_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + fn burn() -> Weight { + (30_435_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + // Storage: System Account (r:1 w:1) + fn transfer() -> Weight { + (44_405_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + // Storage: System Account (r:1 w:1) + fn transfer_keep_alive() -> Weight { + (40_122_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + // Storage: System Account (r:1 w:1) + fn force_transfer() -> Weight { + (47_515_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Account (r:1 w:1) + fn freeze() -> Weight { + (18_143_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Account (r:1 w:1) + fn thaw() -> Weight { + (17_324_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + fn freeze_asset() -> Weight { + (14_662_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + fn thaw_asset() -> Weight { + (14_213_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:0) + fn transfer_ownership() -> Weight { + (16_008_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + fn set_team() -> Weight { + (14_389_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + fn set_metadata(n: u32, s: u32, ) -> Weight { + (17_348_000 as Weight) + // Standard Error: 1_000 + .saturating_add((5_000 as Weight).saturating_mul(n as Weight)) + // Standard Error: 1_000 + .saturating_add((3_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + fn clear_metadata() -> Weight { + (17_727_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + fn force_set_metadata(_n: u32, s: u32, ) -> Weight { + (15_571_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + fn force_clear_metadata() -> Weight { + (17_634_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + fn force_asset_status() -> Weight { + (13_550_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Approvals (r:1 w:1) + fn approve_transfer() -> Weight { + (19_960_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Assets Approvals (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + // Storage: System Account (r:1 w:1) + fn transfer_approved() -> Weight { + (54_158_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().writes(5 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Approvals (r:1 w:1) + fn cancel_approval() -> Weight { + (20_416_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Approvals (r:1 w:1) + fn force_cancel_approval() -> Weight { + (21_390_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } +} diff --git a/runtime/dolphin/src/weights/pallet_balances.rs b/runtime/dolphin/src/weights/pallet_balances.rs index f5e7c6840..adcd0d2f5 100644 --- a/runtime/dolphin/src/weights/pallet_balances.rs +++ b/runtime/dolphin/src/weights/pallet_balances.rs @@ -43,104 +43,104 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_balances. pub trait WeightInfo { - fn transfer() -> Weight; - fn transfer_keep_alive() -> Weight; - fn set_balance_creating() -> Weight; - fn set_balance_killing() -> Weight; - fn force_transfer() -> Weight; - fn transfer_all() -> Weight; - fn force_unreserve() -> Weight; + fn transfer() -> Weight; + fn transfer_keep_alive() -> Weight; + fn set_balance_creating() -> Weight; + fn set_balance_killing() -> Weight; + fn force_transfer() -> Weight; + fn transfer_all() -> Weight; + fn force_unreserve() -> Weight; } /// Weights for pallet_balances using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_balances::WeightInfo for SubstrateWeight { - // Storage: System Account (r:1 w:1) - fn transfer() -> Weight { - (40_750_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn transfer_keep_alive() -> Weight { - (30_317_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn set_balance_creating() -> Weight { - (18_034_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn set_balance_killing() -> Weight { - (20_328_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:2 w:2) - fn force_transfer() -> Weight { - (36_871_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn transfer_all() -> Weight { - (36_221_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn force_unreserve() -> Weight { - (16_325_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } + // Storage: System Account (r:1 w:1) + fn transfer() -> Weight { + (40_750_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn transfer_keep_alive() -> Weight { + (30_317_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn set_balance_creating() -> Weight { + (18_034_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn set_balance_killing() -> Weight { + (20_328_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:2 w:2) + fn force_transfer() -> Weight { + (36_871_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn transfer_all() -> Weight { + (36_221_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn force_unreserve() -> Weight { + (16_325_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: System Account (r:1 w:1) - fn transfer() -> Weight { - (40_750_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn transfer_keep_alive() -> Weight { - (30_317_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn set_balance_creating() -> Weight { - (18_034_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn set_balance_killing() -> Weight { - (20_328_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:2 w:2) - fn force_transfer() -> Weight { - (36_871_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn transfer_all() -> Weight { - (36_221_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn force_unreserve() -> Weight { - (16_325_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } -} \ No newline at end of file + // Storage: System Account (r:1 w:1) + fn transfer() -> Weight { + (40_750_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn transfer_keep_alive() -> Weight { + (30_317_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn set_balance_creating() -> Weight { + (18_034_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn set_balance_killing() -> Weight { + (20_328_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:2 w:2) + fn force_transfer() -> Weight { + (36_871_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn transfer_all() -> Weight { + (36_221_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn force_unreserve() -> Weight { + (16_325_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } +} diff --git a/runtime/dolphin/src/weights/pallet_collective.rs b/runtime/dolphin/src/weights/pallet_collective.rs index 37b885854..c726e1852 100644 --- a/runtime/dolphin/src/weights/pallet_collective.rs +++ b/runtime/dolphin/src/weights/pallet_collective.rs @@ -43,281 +43,281 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_collective. pub trait WeightInfo { - fn set_members(m: u32, n: u32, p: u32, ) -> Weight; - fn execute(b: u32, m: u32, ) -> Weight; - fn propose_execute(b: u32, m: u32, ) -> Weight; - fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight; - fn vote(m: u32, ) -> Weight; - fn close_early_disapproved(m: u32, p: u32, ) -> Weight; - fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight; - fn close_disapproved(m: u32, p: u32, ) -> Weight; - fn close_approved(b: u32, m: u32, p: u32, ) -> Weight; - fn disapprove_proposal(p: u32, ) -> Weight; + fn set_members(m: u32, n: u32, p: u32, ) -> Weight; + fn execute(b: u32, m: u32, ) -> Weight; + fn propose_execute(b: u32, m: u32, ) -> Weight; + fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight; + fn vote(m: u32, ) -> Weight; + fn close_early_disapproved(m: u32, p: u32, ) -> Weight; + fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight; + fn close_disapproved(m: u32, p: u32, ) -> Weight; + fn close_approved(b: u32, m: u32, p: u32, ) -> Weight; + fn disapprove_proposal(p: u32, ) -> Weight; } /// Weights for pallet_collective using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_collective::WeightInfo for SubstrateWeight { - // Storage: Council Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: Council Voting (r:100 w:100) - // Storage: Council Prime (r:0 w:1) - fn set_members(m: u32, n: u32, p: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 7_000 - .saturating_add((12_678_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 7_000 - .saturating_add((29_000 as Weight).saturating_mul(n as Weight)) - // Standard Error: 7_000 - .saturating_add((15_898_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(p as Weight))) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) - } - // Storage: Council Members (r:1 w:0) - fn execute(b: u32, m: u32, ) -> Weight { - (13_783_000 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 0 - .saturating_add((34_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - } - // Storage: Council Members (r:1 w:0) - // Storage: Council ProposalOf (r:1 w:0) - fn propose_execute(b: u32, m: u32, ) -> Weight { - (16_622_000 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 0 - .saturating_add((59_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - } - // Storage: Council Members (r:1 w:0) - // Storage: Council ProposalOf (r:1 w:1) - // Storage: Council Proposals (r:1 w:1) - // Storage: Council ProposalCount (r:1 w:1) - // Storage: Council Voting (r:0 w:1) - fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight { - (20_416_000 as Weight) - // Standard Error: 0 - .saturating_add((9_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 1_000 - .saturating_add((42_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((197_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - } - // Storage: Council Members (r:1 w:0) - // Storage: Council Voting (r:1 w:1) - fn vote(m: u32, ) -> Weight { - (30_555_000 as Weight) - // Standard Error: 2_000 - .saturating_add((86_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Council Voting (r:1 w:1) - // Storage: Council Members (r:1 w:0) - // Storage: Council Proposals (r:1 w:1) - // Storage: Council ProposalOf (r:0 w:1) - fn close_early_disapproved(m: u32, p: u32, ) -> Weight { - (28_022_000 as Weight) - // Standard Error: 2_000 - .saturating_add((62_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((148_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Council Voting (r:1 w:1) - // Storage: Council Members (r:1 w:0) - // Storage: Council ProposalOf (r:1 w:1) - // Storage: Council Proposals (r:1 w:1) - fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight { - (28_668_000 as Weight) - // Standard Error: 0 - .saturating_add((8_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 1_000 - .saturating_add((88_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((201_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Council Voting (r:1 w:1) - // Storage: Council Members (r:1 w:0) - // Storage: Council Prime (r:1 w:0) - // Storage: Council Proposals (r:1 w:1) - // Storage: Council ProposalOf (r:0 w:1) - fn close_disapproved(m: u32, p: u32, ) -> Weight { - (30_880_000 as Weight) - // Standard Error: 2_000 - .saturating_add((70_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((149_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Council Voting (r:1 w:1) - // Storage: Council Members (r:1 w:0) - // Storage: Council Prime (r:1 w:0) - // Storage: Council ProposalOf (r:1 w:1) - // Storage: Council Proposals (r:1 w:1) - fn close_approved(b: u32, m: u32, p: u32, ) -> Weight { - (35_158_000 as Weight) - // Standard Error: 0 - .saturating_add((6_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 1_000 - .saturating_add((72_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((193_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Council Proposals (r:1 w:1) - // Storage: Council Voting (r:0 w:1) - // Storage: Council ProposalOf (r:0 w:1) - fn disapprove_proposal(p: u32, ) -> Weight { - (16_370_000 as Weight) - // Standard Error: 1_000 - .saturating_add((192_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } + // Storage: Council Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: Council Voting (r:100 w:100) + // Storage: Council Prime (r:0 w:1) + fn set_members(m: u32, n: u32, p: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 7_000 + .saturating_add((12_678_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 7_000 + .saturating_add((29_000 as Weight).saturating_mul(n as Weight)) + // Standard Error: 7_000 + .saturating_add((15_898_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(p as Weight))) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) + } + // Storage: Council Members (r:1 w:0) + fn execute(b: u32, m: u32, ) -> Weight { + (13_783_000 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 0 + .saturating_add((34_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + } + // Storage: Council Members (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:0) + fn propose_execute(b: u32, m: u32, ) -> Weight { + (16_622_000 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 0 + .saturating_add((59_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + } + // Storage: Council Members (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:1) + // Storage: Council Proposals (r:1 w:1) + // Storage: Council ProposalCount (r:1 w:1) + // Storage: Council Voting (r:0 w:1) + fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight { + (20_416_000 as Weight) + // Standard Error: 0 + .saturating_add((9_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 1_000 + .saturating_add((42_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 1_000 + .saturating_add((197_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + // Storage: Council Members (r:1 w:0) + // Storage: Council Voting (r:1 w:1) + fn vote(m: u32, ) -> Weight { + (30_555_000 as Weight) + // Standard Error: 2_000 + .saturating_add((86_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council Proposals (r:1 w:1) + // Storage: Council ProposalOf (r:0 w:1) + fn close_early_disapproved(m: u32, p: u32, ) -> Weight { + (28_022_000 as Weight) + // Standard Error: 2_000 + .saturating_add((62_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 1_000 + .saturating_add((148_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:1) + // Storage: Council Proposals (r:1 w:1) + fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight { + (28_668_000 as Weight) + // Standard Error: 0 + .saturating_add((8_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 1_000 + .saturating_add((88_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 1_000 + .saturating_add((201_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council Prime (r:1 w:0) + // Storage: Council Proposals (r:1 w:1) + // Storage: Council ProposalOf (r:0 w:1) + fn close_disapproved(m: u32, p: u32, ) -> Weight { + (30_880_000 as Weight) + // Standard Error: 2_000 + .saturating_add((70_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 1_000 + .saturating_add((149_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council Prime (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:1) + // Storage: Council Proposals (r:1 w:1) + fn close_approved(b: u32, m: u32, p: u32, ) -> Weight { + (35_158_000 as Weight) + // Standard Error: 0 + .saturating_add((6_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 1_000 + .saturating_add((72_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 1_000 + .saturating_add((193_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Council Proposals (r:1 w:1) + // Storage: Council Voting (r:0 w:1) + // Storage: Council ProposalOf (r:0 w:1) + fn disapprove_proposal(p: u32, ) -> Weight { + (16_370_000 as Weight) + // Standard Error: 1_000 + .saturating_add((192_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Council Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: Council Voting (r:100 w:100) - // Storage: Council Prime (r:0 w:1) - fn set_members(m: u32, n: u32, p: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 7_000 - .saturating_add((12_678_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 7_000 - .saturating_add((29_000 as Weight).saturating_mul(n as Weight)) - // Standard Error: 7_000 - .saturating_add((15_898_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(p as Weight))) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) - } - // Storage: Council Members (r:1 w:0) - fn execute(b: u32, m: u32, ) -> Weight { - (13_783_000 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 0 - .saturating_add((34_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - } - // Storage: Council Members (r:1 w:0) - // Storage: Council ProposalOf (r:1 w:0) - fn propose_execute(b: u32, m: u32, ) -> Weight { - (16_622_000 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 0 - .saturating_add((59_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - } - // Storage: Council Members (r:1 w:0) - // Storage: Council ProposalOf (r:1 w:1) - // Storage: Council Proposals (r:1 w:1) - // Storage: Council ProposalCount (r:1 w:1) - // Storage: Council Voting (r:0 w:1) - fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight { - (20_416_000 as Weight) - // Standard Error: 0 - .saturating_add((9_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 1_000 - .saturating_add((42_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((197_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - } - // Storage: Council Members (r:1 w:0) - // Storage: Council Voting (r:1 w:1) - fn vote(m: u32, ) -> Weight { - (30_555_000 as Weight) - // Standard Error: 2_000 - .saturating_add((86_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Council Voting (r:1 w:1) - // Storage: Council Members (r:1 w:0) - // Storage: Council Proposals (r:1 w:1) - // Storage: Council ProposalOf (r:0 w:1) - fn close_early_disapproved(m: u32, p: u32, ) -> Weight { - (28_022_000 as Weight) - // Standard Error: 2_000 - .saturating_add((62_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((148_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Council Voting (r:1 w:1) - // Storage: Council Members (r:1 w:0) - // Storage: Council ProposalOf (r:1 w:1) - // Storage: Council Proposals (r:1 w:1) - fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight { - (28_668_000 as Weight) - // Standard Error: 0 - .saturating_add((8_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 1_000 - .saturating_add((88_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((201_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Council Voting (r:1 w:1) - // Storage: Council Members (r:1 w:0) - // Storage: Council Prime (r:1 w:0) - // Storage: Council Proposals (r:1 w:1) - // Storage: Council ProposalOf (r:0 w:1) - fn close_disapproved(m: u32, p: u32, ) -> Weight { - (30_880_000 as Weight) - // Standard Error: 2_000 - .saturating_add((70_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((149_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Council Voting (r:1 w:1) - // Storage: Council Members (r:1 w:0) - // Storage: Council Prime (r:1 w:0) - // Storage: Council ProposalOf (r:1 w:1) - // Storage: Council Proposals (r:1 w:1) - fn close_approved(b: u32, m: u32, p: u32, ) -> Weight { - (35_158_000 as Weight) - // Standard Error: 0 - .saturating_add((6_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 1_000 - .saturating_add((72_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((193_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Council Proposals (r:1 w:1) - // Storage: Council Voting (r:0 w:1) - // Storage: Council ProposalOf (r:0 w:1) - fn disapprove_proposal(p: u32, ) -> Weight { - (16_370_000 as Weight) - // Standard Error: 1_000 - .saturating_add((192_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } -} \ No newline at end of file + // Storage: Council Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: Council Voting (r:100 w:100) + // Storage: Council Prime (r:0 w:1) + fn set_members(m: u32, n: u32, p: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 7_000 + .saturating_add((12_678_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 7_000 + .saturating_add((29_000 as Weight).saturating_mul(n as Weight)) + // Standard Error: 7_000 + .saturating_add((15_898_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(p as Weight))) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) + } + // Storage: Council Members (r:1 w:0) + fn execute(b: u32, m: u32, ) -> Weight { + (13_783_000 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 0 + .saturating_add((34_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + } + // Storage: Council Members (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:0) + fn propose_execute(b: u32, m: u32, ) -> Weight { + (16_622_000 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 0 + .saturating_add((59_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + } + // Storage: Council Members (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:1) + // Storage: Council Proposals (r:1 w:1) + // Storage: Council ProposalCount (r:1 w:1) + // Storage: Council Voting (r:0 w:1) + fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight { + (20_416_000 as Weight) + // Standard Error: 0 + .saturating_add((9_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 1_000 + .saturating_add((42_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 1_000 + .saturating_add((197_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + // Storage: Council Members (r:1 w:0) + // Storage: Council Voting (r:1 w:1) + fn vote(m: u32, ) -> Weight { + (30_555_000 as Weight) + // Standard Error: 2_000 + .saturating_add((86_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council Proposals (r:1 w:1) + // Storage: Council ProposalOf (r:0 w:1) + fn close_early_disapproved(m: u32, p: u32, ) -> Weight { + (28_022_000 as Weight) + // Standard Error: 2_000 + .saturating_add((62_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 1_000 + .saturating_add((148_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:1) + // Storage: Council Proposals (r:1 w:1) + fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight { + (28_668_000 as Weight) + // Standard Error: 0 + .saturating_add((8_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 1_000 + .saturating_add((88_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 1_000 + .saturating_add((201_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council Prime (r:1 w:0) + // Storage: Council Proposals (r:1 w:1) + // Storage: Council ProposalOf (r:0 w:1) + fn close_disapproved(m: u32, p: u32, ) -> Weight { + (30_880_000 as Weight) + // Standard Error: 2_000 + .saturating_add((70_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 1_000 + .saturating_add((149_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council Prime (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:1) + // Storage: Council Proposals (r:1 w:1) + fn close_approved(b: u32, m: u32, p: u32, ) -> Weight { + (35_158_000 as Weight) + // Standard Error: 0 + .saturating_add((6_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 1_000 + .saturating_add((72_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 1_000 + .saturating_add((193_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Council Proposals (r:1 w:1) + // Storage: Council Voting (r:0 w:1) + // Storage: Council ProposalOf (r:0 w:1) + fn disapprove_proposal(p: u32, ) -> Weight { + (16_370_000 as Weight) + // Standard Error: 1_000 + .saturating_add((192_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } +} diff --git a/runtime/dolphin/src/weights/pallet_democracy.rs b/runtime/dolphin/src/weights/pallet_democracy.rs index 19fe60d73..5c2a93d1c 100644 --- a/runtime/dolphin/src/weights/pallet_democracy.rs +++ b/runtime/dolphin/src/weights/pallet_democracy.rs @@ -43,505 +43,505 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_democracy. pub trait WeightInfo { - fn propose() -> Weight; - fn second(s: u32, ) -> Weight; - fn vote_new(r: u32, ) -> Weight; - fn vote_existing(r: u32, ) -> Weight; - fn emergency_cancel() -> Weight; - fn blacklist(p: u32, ) -> Weight; - fn external_propose(v: u32, ) -> Weight; - fn external_propose_majority() -> Weight; - fn external_propose_default() -> Weight; - fn fast_track() -> Weight; - fn veto_external(v: u32, ) -> Weight; - fn cancel_proposal(p: u32, ) -> Weight; - fn cancel_referendum() -> Weight; - fn cancel_queued(r: u32, ) -> Weight; - fn on_initialize_base(r: u32, ) -> Weight; - fn on_initialize_base_with_launch_period(r: u32, ) -> Weight; - fn delegate(r: u32, ) -> Weight; - fn undelegate(r: u32, ) -> Weight; - fn clear_public_proposals() -> Weight; - fn note_preimage(b: u32, ) -> Weight; - fn note_imminent_preimage(b: u32, ) -> Weight; - fn reap_preimage(b: u32, ) -> Weight; - fn unlock_remove(r: u32, ) -> Weight; - fn unlock_set(r: u32, ) -> Weight; - fn remove_vote(r: u32, ) -> Weight; - fn remove_other_vote(r: u32, ) -> Weight; + fn propose() -> Weight; + fn second(s: u32, ) -> Weight; + fn vote_new(r: u32, ) -> Weight; + fn vote_existing(r: u32, ) -> Weight; + fn emergency_cancel() -> Weight; + fn blacklist(p: u32, ) -> Weight; + fn external_propose(v: u32, ) -> Weight; + fn external_propose_majority() -> Weight; + fn external_propose_default() -> Weight; + fn fast_track() -> Weight; + fn veto_external(v: u32, ) -> Weight; + fn cancel_proposal(p: u32, ) -> Weight; + fn cancel_referendum() -> Weight; + fn cancel_queued(r: u32, ) -> Weight; + fn on_initialize_base(r: u32, ) -> Weight; + fn on_initialize_base_with_launch_period(r: u32, ) -> Weight; + fn delegate(r: u32, ) -> Weight; + fn undelegate(r: u32, ) -> Weight; + fn clear_public_proposals() -> Weight; + fn note_preimage(b: u32, ) -> Weight; + fn note_imminent_preimage(b: u32, ) -> Weight; + fn reap_preimage(b: u32, ) -> Weight; + fn unlock_remove(r: u32, ) -> Weight; + fn unlock_set(r: u32, ) -> Weight; + fn remove_vote(r: u32, ) -> Weight; + fn remove_other_vote(r: u32, ) -> Weight; } /// Weights for pallet_democracy using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_democracy::WeightInfo for SubstrateWeight { - // Storage: Democracy PublicPropCount (r:1 w:1) - // Storage: Democracy PublicProps (r:1 w:1) - // Storage: Democracy Blacklist (r:1 w:0) - // Storage: Democracy DepositOf (r:0 w:1) - fn propose() -> Weight { - (48_397_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy DepositOf (r:1 w:1) - fn second(s: u32, ) -> Weight { - (27_749_000 as Weight) - // Standard Error: 1_000 - .saturating_add((127_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy VotingOf (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - fn vote_new(r: u32, ) -> Weight { - (36_807_000 as Weight) - // Standard Error: 2_000 - .saturating_add((154_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy VotingOf (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - fn vote_existing(r: u32, ) -> Weight { - (36_192_000 as Weight) - // Standard Error: 2_000 - .saturating_add((159_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy Cancellations (r:1 w:1) - fn emergency_cancel() -> Weight { - (16_260_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Democracy PublicProps (r:1 w:1) - // Storage: Democracy NextExternal (r:1 w:1) - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy Blacklist (r:0 w:1) - // Storage: Democracy DepositOf (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn blacklist(p: u32, ) -> Weight { - (46_812_000 as Weight) - // Standard Error: 3_000 - .saturating_add((196_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().writes(6 as Weight)) - } - // Storage: Democracy NextExternal (r:1 w:1) - // Storage: Democracy Blacklist (r:1 w:0) - fn external_propose(v: u32, ) -> Weight { - (8_464_000 as Weight) - // Standard Error: 0 - .saturating_add((33_000 as Weight).saturating_mul(v as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy NextExternal (r:0 w:1) - fn external_propose_majority() -> Weight { - (1_446_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy NextExternal (r:0 w:1) - fn external_propose_default() -> Weight { - (1_570_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy NextExternal (r:1 w:1) - // Storage: Democracy ReferendumCount (r:1 w:1) - // Storage: Democracy ReferendumInfoOf (r:0 w:1) - fn fast_track() -> Weight { - (16_686_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy NextExternal (r:1 w:1) - // Storage: Democracy Blacklist (r:1 w:1) - fn veto_external(v: u32, ) -> Weight { - (17_780_000 as Weight) - // Standard Error: 1_000 - .saturating_add((52_000 as Weight).saturating_mul(v as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Democracy PublicProps (r:1 w:1) - // Storage: Democracy DepositOf (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn cancel_proposal(p: u32, ) -> Weight { - (31_611_000 as Weight) - // Standard Error: 2_000 - .saturating_add((177_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:0 w:1) - fn cancel_referendum() -> Weight { - (10_180_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Scheduler Lookup (r:1 w:1) - // Storage: Scheduler Agenda (r:1 w:1) - fn cancel_queued(r: u32, ) -> Weight { - (22_476_000 as Weight) - // Standard Error: 3_000 - .saturating_add((1_698_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Democracy LowestUnbaked (r:1 w:1) - // Storage: Democracy ReferendumCount (r:1 w:0) - // Storage: Democracy ReferendumInfoOf (r:1 w:0) - fn on_initialize_base(r: u32, ) -> Weight { - (4_631_000 as Weight) - // Standard Error: 5_000 - .saturating_add((3_461_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy LowestUnbaked (r:1 w:1) - // Storage: Democracy ReferendumCount (r:1 w:0) - // Storage: Democracy LastTabledWasExternal (r:1 w:0) - // Storage: Democracy NextExternal (r:1 w:0) - // Storage: Democracy PublicProps (r:1 w:0) - // Storage: Democracy ReferendumInfoOf (r:1 w:0) - fn on_initialize_base_with_launch_period(r: u32, ) -> Weight { - (8_794_000 as Weight) - // Standard Error: 5_000 - .saturating_add((3_482_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy VotingOf (r:3 w:3) - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - fn delegate(r: u32, ) -> Weight { - (36_106_000 as Weight) - // Standard Error: 7_000 - .saturating_add((4_447_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(r as Weight))) - } - // Storage: Democracy VotingOf (r:2 w:2) - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - fn undelegate(r: u32, ) -> Weight { - (18_183_000 as Weight) - // Standard Error: 6_000 - .saturating_add((4_502_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(r as Weight))) - } - // Storage: Democracy PublicProps (r:0 w:1) - fn clear_public_proposals() -> Weight { - (1_864_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy Preimages (r:1 w:1) - fn note_preimage(b: u32, ) -> Weight { - (24_883_000 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy Preimages (r:1 w:1) - fn note_imminent_preimage(b: u32, ) -> Weight { - (16_705_000 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy Preimages (r:1 w:1) - // Storage: System Account (r:1 w:0) - fn reap_preimage(b: u32, ) -> Weight { - (25_072_000 as Weight) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy VotingOf (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn unlock_remove(r: u32, ) -> Weight { - (23_308_000 as Weight) - // Standard Error: 1_000 - .saturating_add((54_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy VotingOf (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn unlock_set(r: u32, ) -> Weight { - (22_464_000 as Weight) - // Standard Error: 2_000 - .saturating_add((130_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy VotingOf (r:1 w:1) - fn remove_vote(r: u32, ) -> Weight { - (13_148_000 as Weight) - // Standard Error: 1_000 - .saturating_add((135_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy VotingOf (r:1 w:1) - fn remove_other_vote(r: u32, ) -> Weight { - (13_772_000 as Weight) - // Standard Error: 1_000 - .saturating_add((117_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } + // Storage: Democracy PublicPropCount (r:1 w:1) + // Storage: Democracy PublicProps (r:1 w:1) + // Storage: Democracy Blacklist (r:1 w:0) + // Storage: Democracy DepositOf (r:0 w:1) + fn propose() -> Weight { + (48_397_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy DepositOf (r:1 w:1) + fn second(s: u32, ) -> Weight { + (27_749_000 as Weight) + // Standard Error: 1_000 + .saturating_add((127_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy VotingOf (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + fn vote_new(r: u32, ) -> Weight { + (36_807_000 as Weight) + // Standard Error: 2_000 + .saturating_add((154_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy VotingOf (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + fn vote_existing(r: u32, ) -> Weight { + (36_192_000 as Weight) + // Standard Error: 2_000 + .saturating_add((159_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy Cancellations (r:1 w:1) + fn emergency_cancel() -> Weight { + (16_260_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Democracy PublicProps (r:1 w:1) + // Storage: Democracy NextExternal (r:1 w:1) + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy Blacklist (r:0 w:1) + // Storage: Democracy DepositOf (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn blacklist(p: u32, ) -> Weight { + (46_812_000 as Weight) + // Standard Error: 3_000 + .saturating_add((196_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(6 as Weight)) + } + // Storage: Democracy NextExternal (r:1 w:1) + // Storage: Democracy Blacklist (r:1 w:0) + fn external_propose(v: u32, ) -> Weight { + (8_464_000 as Weight) + // Standard Error: 0 + .saturating_add((33_000 as Weight).saturating_mul(v as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy NextExternal (r:0 w:1) + fn external_propose_majority() -> Weight { + (1_446_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy NextExternal (r:0 w:1) + fn external_propose_default() -> Weight { + (1_570_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy NextExternal (r:1 w:1) + // Storage: Democracy ReferendumCount (r:1 w:1) + // Storage: Democracy ReferendumInfoOf (r:0 w:1) + fn fast_track() -> Weight { + (16_686_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy NextExternal (r:1 w:1) + // Storage: Democracy Blacklist (r:1 w:1) + fn veto_external(v: u32, ) -> Weight { + (17_780_000 as Weight) + // Standard Error: 1_000 + .saturating_add((52_000 as Weight).saturating_mul(v as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Democracy PublicProps (r:1 w:1) + // Storage: Democracy DepositOf (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn cancel_proposal(p: u32, ) -> Weight { + (31_611_000 as Weight) + // Standard Error: 2_000 + .saturating_add((177_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:0 w:1) + fn cancel_referendum() -> Weight { + (10_180_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Scheduler Lookup (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn cancel_queued(r: u32, ) -> Weight { + (22_476_000 as Weight) + // Standard Error: 3_000 + .saturating_add((1_698_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Democracy LowestUnbaked (r:1 w:1) + // Storage: Democracy ReferendumCount (r:1 w:0) + // Storage: Democracy ReferendumInfoOf (r:1 w:0) + fn on_initialize_base(r: u32, ) -> Weight { + (4_631_000 as Weight) + // Standard Error: 5_000 + .saturating_add((3_461_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy LowestUnbaked (r:1 w:1) + // Storage: Democracy ReferendumCount (r:1 w:0) + // Storage: Democracy LastTabledWasExternal (r:1 w:0) + // Storage: Democracy NextExternal (r:1 w:0) + // Storage: Democracy PublicProps (r:1 w:0) + // Storage: Democracy ReferendumInfoOf (r:1 w:0) + fn on_initialize_base_with_launch_period(r: u32, ) -> Weight { + (8_794_000 as Weight) + // Standard Error: 5_000 + .saturating_add((3_482_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy VotingOf (r:3 w:3) + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + fn delegate(r: u32, ) -> Weight { + (36_106_000 as Weight) + // Standard Error: 7_000 + .saturating_add((4_447_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(r as Weight))) + } + // Storage: Democracy VotingOf (r:2 w:2) + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + fn undelegate(r: u32, ) -> Weight { + (18_183_000 as Weight) + // Standard Error: 6_000 + .saturating_add((4_502_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(r as Weight))) + } + // Storage: Democracy PublicProps (r:0 w:1) + fn clear_public_proposals() -> Weight { + (1_864_000 as Weight) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy Preimages (r:1 w:1) + fn note_preimage(b: u32, ) -> Weight { + (24_883_000 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy Preimages (r:1 w:1) + fn note_imminent_preimage(b: u32, ) -> Weight { + (16_705_000 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy Preimages (r:1 w:1) + // Storage: System Account (r:1 w:0) + fn reap_preimage(b: u32, ) -> Weight { + (25_072_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy VotingOf (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn unlock_remove(r: u32, ) -> Weight { + (23_308_000 as Weight) + // Standard Error: 1_000 + .saturating_add((54_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy VotingOf (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn unlock_set(r: u32, ) -> Weight { + (22_464_000 as Weight) + // Standard Error: 2_000 + .saturating_add((130_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy VotingOf (r:1 w:1) + fn remove_vote(r: u32, ) -> Weight { + (13_148_000 as Weight) + // Standard Error: 1_000 + .saturating_add((135_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy VotingOf (r:1 w:1) + fn remove_other_vote(r: u32, ) -> Weight { + (13_772_000 as Weight) + // Standard Error: 1_000 + .saturating_add((117_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Democracy PublicPropCount (r:1 w:1) - // Storage: Democracy PublicProps (r:1 w:1) - // Storage: Democracy Blacklist (r:1 w:0) - // Storage: Democracy DepositOf (r:0 w:1) - fn propose() -> Weight { - (48_397_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy DepositOf (r:1 w:1) - fn second(s: u32, ) -> Weight { - (27_749_000 as Weight) - // Standard Error: 1_000 - .saturating_add((127_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy VotingOf (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - fn vote_new(r: u32, ) -> Weight { - (36_807_000 as Weight) - // Standard Error: 2_000 - .saturating_add((154_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy VotingOf (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - fn vote_existing(r: u32, ) -> Weight { - (36_192_000 as Weight) - // Standard Error: 2_000 - .saturating_add((159_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy Cancellations (r:1 w:1) - fn emergency_cancel() -> Weight { - (16_260_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Democracy PublicProps (r:1 w:1) - // Storage: Democracy NextExternal (r:1 w:1) - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy Blacklist (r:0 w:1) - // Storage: Democracy DepositOf (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn blacklist(p: u32, ) -> Weight { - (46_812_000 as Weight) - // Standard Error: 3_000 - .saturating_add((196_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(6 as Weight)) - } - // Storage: Democracy NextExternal (r:1 w:1) - // Storage: Democracy Blacklist (r:1 w:0) - fn external_propose(v: u32, ) -> Weight { - (8_464_000 as Weight) - // Standard Error: 0 - .saturating_add((33_000 as Weight).saturating_mul(v as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy NextExternal (r:0 w:1) - fn external_propose_majority() -> Weight { - (1_446_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy NextExternal (r:0 w:1) - fn external_propose_default() -> Weight { - (1_570_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy NextExternal (r:1 w:1) - // Storage: Democracy ReferendumCount (r:1 w:1) - // Storage: Democracy ReferendumInfoOf (r:0 w:1) - fn fast_track() -> Weight { - (16_686_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy NextExternal (r:1 w:1) - // Storage: Democracy Blacklist (r:1 w:1) - fn veto_external(v: u32, ) -> Weight { - (17_780_000 as Weight) - // Standard Error: 1_000 - .saturating_add((52_000 as Weight).saturating_mul(v as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Democracy PublicProps (r:1 w:1) - // Storage: Democracy DepositOf (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn cancel_proposal(p: u32, ) -> Weight { - (31_611_000 as Weight) - // Standard Error: 2_000 - .saturating_add((177_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:0 w:1) - fn cancel_referendum() -> Weight { - (10_180_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Scheduler Lookup (r:1 w:1) - // Storage: Scheduler Agenda (r:1 w:1) - fn cancel_queued(r: u32, ) -> Weight { - (22_476_000 as Weight) - // Standard Error: 3_000 - .saturating_add((1_698_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Democracy LowestUnbaked (r:1 w:1) - // Storage: Democracy ReferendumCount (r:1 w:0) - // Storage: Democracy ReferendumInfoOf (r:1 w:0) - fn on_initialize_base(r: u32, ) -> Weight { - (4_631_000 as Weight) - // Standard Error: 5_000 - .saturating_add((3_461_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy LowestUnbaked (r:1 w:1) - // Storage: Democracy ReferendumCount (r:1 w:0) - // Storage: Democracy LastTabledWasExternal (r:1 w:0) - // Storage: Democracy NextExternal (r:1 w:0) - // Storage: Democracy PublicProps (r:1 w:0) - // Storage: Democracy ReferendumInfoOf (r:1 w:0) - fn on_initialize_base_with_launch_period(r: u32, ) -> Weight { - (8_794_000 as Weight) - // Standard Error: 5_000 - .saturating_add((3_482_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy VotingOf (r:3 w:3) - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - fn delegate(r: u32, ) -> Weight { - (36_106_000 as Weight) - // Standard Error: 7_000 - .saturating_add((4_447_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(r as Weight))) - } - // Storage: Democracy VotingOf (r:2 w:2) - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - fn undelegate(r: u32, ) -> Weight { - (18_183_000 as Weight) - // Standard Error: 6_000 - .saturating_add((4_502_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(r as Weight))) - } - // Storage: Democracy PublicProps (r:0 w:1) - fn clear_public_proposals() -> Weight { - (1_864_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy Preimages (r:1 w:1) - fn note_preimage(b: u32, ) -> Weight { - (24_883_000 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy Preimages (r:1 w:1) - fn note_imminent_preimage(b: u32, ) -> Weight { - (16_705_000 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy Preimages (r:1 w:1) - // Storage: System Account (r:1 w:0) - fn reap_preimage(b: u32, ) -> Weight { - (25_072_000 as Weight) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Democracy VotingOf (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn unlock_remove(r: u32, ) -> Weight { - (23_308_000 as Weight) - // Standard Error: 1_000 - .saturating_add((54_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy VotingOf (r:1 w:1) - // Storage: Balances Locks (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn unlock_set(r: u32, ) -> Weight { - (22_464_000 as Weight) - // Standard Error: 2_000 - .saturating_add((130_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy VotingOf (r:1 w:1) - fn remove_vote(r: u32, ) -> Weight { - (13_148_000 as Weight) - // Standard Error: 1_000 - .saturating_add((135_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Democracy ReferendumInfoOf (r:1 w:1) - // Storage: Democracy VotingOf (r:1 w:1) - fn remove_other_vote(r: u32, ) -> Weight { - (13_772_000 as Weight) - // Standard Error: 1_000 - .saturating_add((117_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } -} \ No newline at end of file + // Storage: Democracy PublicPropCount (r:1 w:1) + // Storage: Democracy PublicProps (r:1 w:1) + // Storage: Democracy Blacklist (r:1 w:0) + // Storage: Democracy DepositOf (r:0 w:1) + fn propose() -> Weight { + (48_397_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy DepositOf (r:1 w:1) + fn second(s: u32, ) -> Weight { + (27_749_000 as Weight) + // Standard Error: 1_000 + .saturating_add((127_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy VotingOf (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + fn vote_new(r: u32, ) -> Weight { + (36_807_000 as Weight) + // Standard Error: 2_000 + .saturating_add((154_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy VotingOf (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + fn vote_existing(r: u32, ) -> Weight { + (36_192_000 as Weight) + // Standard Error: 2_000 + .saturating_add((159_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy Cancellations (r:1 w:1) + fn emergency_cancel() -> Weight { + (16_260_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Democracy PublicProps (r:1 w:1) + // Storage: Democracy NextExternal (r:1 w:1) + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy Blacklist (r:0 w:1) + // Storage: Democracy DepositOf (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn blacklist(p: u32, ) -> Weight { + (46_812_000 as Weight) + // Standard Error: 3_000 + .saturating_add((196_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().writes(6 as Weight)) + } + // Storage: Democracy NextExternal (r:1 w:1) + // Storage: Democracy Blacklist (r:1 w:0) + fn external_propose(v: u32, ) -> Weight { + (8_464_000 as Weight) + // Standard Error: 0 + .saturating_add((33_000 as Weight).saturating_mul(v as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy NextExternal (r:0 w:1) + fn external_propose_majority() -> Weight { + (1_446_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy NextExternal (r:0 w:1) + fn external_propose_default() -> Weight { + (1_570_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy NextExternal (r:1 w:1) + // Storage: Democracy ReferendumCount (r:1 w:1) + // Storage: Democracy ReferendumInfoOf (r:0 w:1) + fn fast_track() -> Weight { + (16_686_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy NextExternal (r:1 w:1) + // Storage: Democracy Blacklist (r:1 w:1) + fn veto_external(v: u32, ) -> Weight { + (17_780_000 as Weight) + // Standard Error: 1_000 + .saturating_add((52_000 as Weight).saturating_mul(v as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Democracy PublicProps (r:1 w:1) + // Storage: Democracy DepositOf (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn cancel_proposal(p: u32, ) -> Weight { + (31_611_000 as Weight) + // Standard Error: 2_000 + .saturating_add((177_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:0 w:1) + fn cancel_referendum() -> Weight { + (10_180_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Scheduler Lookup (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn cancel_queued(r: u32, ) -> Weight { + (22_476_000 as Weight) + // Standard Error: 3_000 + .saturating_add((1_698_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Democracy LowestUnbaked (r:1 w:1) + // Storage: Democracy ReferendumCount (r:1 w:0) + // Storage: Democracy ReferendumInfoOf (r:1 w:0) + fn on_initialize_base(r: u32, ) -> Weight { + (4_631_000 as Weight) + // Standard Error: 5_000 + .saturating_add((3_461_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy LowestUnbaked (r:1 w:1) + // Storage: Democracy ReferendumCount (r:1 w:0) + // Storage: Democracy LastTabledWasExternal (r:1 w:0) + // Storage: Democracy NextExternal (r:1 w:0) + // Storage: Democracy PublicProps (r:1 w:0) + // Storage: Democracy ReferendumInfoOf (r:1 w:0) + fn on_initialize_base_with_launch_period(r: u32, ) -> Weight { + (8_794_000 as Weight) + // Standard Error: 5_000 + .saturating_add((3_482_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy VotingOf (r:3 w:3) + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + fn delegate(r: u32, ) -> Weight { + (36_106_000 as Weight) + // Standard Error: 7_000 + .saturating_add((4_447_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(r as Weight))) + } + // Storage: Democracy VotingOf (r:2 w:2) + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + fn undelegate(r: u32, ) -> Weight { + (18_183_000 as Weight) + // Standard Error: 6_000 + .saturating_add((4_502_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(r as Weight))) + } + // Storage: Democracy PublicProps (r:0 w:1) + fn clear_public_proposals() -> Weight { + (1_864_000 as Weight) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy Preimages (r:1 w:1) + fn note_preimage(b: u32, ) -> Weight { + (24_883_000 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy Preimages (r:1 w:1) + fn note_imminent_preimage(b: u32, ) -> Weight { + (16_705_000 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy Preimages (r:1 w:1) + // Storage: System Account (r:1 w:0) + fn reap_preimage(b: u32, ) -> Weight { + (25_072_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Democracy VotingOf (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn unlock_remove(r: u32, ) -> Weight { + (23_308_000 as Weight) + // Standard Error: 1_000 + .saturating_add((54_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy VotingOf (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn unlock_set(r: u32, ) -> Weight { + (22_464_000 as Weight) + // Standard Error: 2_000 + .saturating_add((130_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy VotingOf (r:1 w:1) + fn remove_vote(r: u32, ) -> Weight { + (13_148_000 as Weight) + // Standard Error: 1_000 + .saturating_add((135_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Democracy ReferendumInfoOf (r:1 w:1) + // Storage: Democracy VotingOf (r:1 w:1) + fn remove_other_vote(r: u32, ) -> Weight { + (13_772_000 as Weight) + // Standard Error: 1_000 + .saturating_add((117_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } +} diff --git a/runtime/dolphin/src/weights/pallet_manta_pay.rs b/runtime/dolphin/src/weights/pallet_manta_pay.rs index 594132405..571b9f653 100644 --- a/runtime/dolphin/src/weights/pallet_manta_pay.rs +++ b/runtime/dolphin/src/weights/pallet_manta_pay.rs @@ -43,107 +43,107 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_manta_pay. pub trait WeightInfo { - fn to_private() -> Weight; - fn to_public() -> Weight; - fn private_transfer() -> Weight; - fn public_transfer() -> Weight; + fn to_private() -> Weight; + fn to_public() -> Weight; + fn private_transfer() -> Weight; + fn public_transfer() -> Weight; } /// Weights for pallet_manta_pay using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_manta_pay::WeightInfo for SubstrateWeight { - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - // Storage: MantaPay UtxoSet (r:1 w:1) - // Storage: MantaPay VoidNumberSetSize (r:1 w:0) - // Storage: MantaPay ShardTrees (r:1 w:1) - // Storage: MantaPay UtxoAccumulatorOutputs (r:0 w:1) - // Storage: MantaPay Shards (r:0 w:1) - fn to_private() -> Weight { - (66_660_730_000 as Weight) - .saturating_add(T::DbWeight::get().reads(6 as Weight)) - .saturating_add(T::DbWeight::get().writes(7 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - // Storage: MantaPay UtxoAccumulatorOutputs (r:2 w:1) - // Storage: MantaPay VoidNumberSet (r:2 w:2) - // Storage: MantaPay UtxoSet (r:1 w:1) - // Storage: MantaPay VoidNumberSetSize (r:1 w:1) - // Storage: MantaPay ShardTrees (r:1 w:1) - // Storage: MantaPay VoidNumberSetInsertionOrder (r:0 w:2) - // Storage: MantaPay Shards (r:0 w:1) - fn to_public() -> Weight { - (82_371_125_000 as Weight) - .saturating_add(T::DbWeight::get().reads(10 as Weight)) - .saturating_add(T::DbWeight::get().writes(12 as Weight)) - } - // Storage: MantaPay UtxoAccumulatorOutputs (r:2 w:2) - // Storage: MantaPay VoidNumberSet (r:2 w:2) - // Storage: MantaPay UtxoSet (r:2 w:2) - // Storage: MantaPay VoidNumberSetSize (r:1 w:1) - // Storage: MantaPay ShardTrees (r:2 w:2) - // Storage: MantaPay VoidNumberSetInsertionOrder (r:0 w:2) - // Storage: MantaPay Shards (r:0 w:2) - fn private_transfer() -> Weight { - (89_243_134_000 as Weight) - .saturating_add(T::DbWeight::get().reads(9 as Weight)) - .saturating_add(T::DbWeight::get().writes(13 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - fn public_transfer() -> Weight { - (38_433_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + // Storage: MantaPay UtxoSet (r:1 w:1) + // Storage: MantaPay VoidNumberSetSize (r:1 w:0) + // Storage: MantaPay ShardTrees (r:1 w:1) + // Storage: MantaPay UtxoAccumulatorOutputs (r:0 w:1) + // Storage: MantaPay Shards (r:0 w:1) + fn to_private() -> Weight { + (66_660_730_000 as Weight) + .saturating_add(T::DbWeight::get().reads(6 as Weight)) + .saturating_add(T::DbWeight::get().writes(7 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + // Storage: MantaPay UtxoAccumulatorOutputs (r:2 w:1) + // Storage: MantaPay VoidNumberSet (r:2 w:2) + // Storage: MantaPay UtxoSet (r:1 w:1) + // Storage: MantaPay VoidNumberSetSize (r:1 w:1) + // Storage: MantaPay ShardTrees (r:1 w:1) + // Storage: MantaPay VoidNumberSetInsertionOrder (r:0 w:2) + // Storage: MantaPay Shards (r:0 w:1) + fn to_public() -> Weight { + (82_371_125_000 as Weight) + .saturating_add(T::DbWeight::get().reads(10 as Weight)) + .saturating_add(T::DbWeight::get().writes(12 as Weight)) + } + // Storage: MantaPay UtxoAccumulatorOutputs (r:2 w:2) + // Storage: MantaPay VoidNumberSet (r:2 w:2) + // Storage: MantaPay UtxoSet (r:2 w:2) + // Storage: MantaPay VoidNumberSetSize (r:1 w:1) + // Storage: MantaPay ShardTrees (r:2 w:2) + // Storage: MantaPay VoidNumberSetInsertionOrder (r:0 w:2) + // Storage: MantaPay Shards (r:0 w:2) + fn private_transfer() -> Weight { + (89_243_134_000 as Weight) + .saturating_add(T::DbWeight::get().reads(9 as Weight)) + .saturating_add(T::DbWeight::get().writes(13 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + fn public_transfer() -> Weight { + (38_433_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - // Storage: MantaPay UtxoSet (r:1 w:1) - // Storage: MantaPay VoidNumberSetSize (r:1 w:0) - // Storage: MantaPay ShardTrees (r:1 w:1) - // Storage: MantaPay UtxoAccumulatorOutputs (r:0 w:1) - // Storage: MantaPay Shards (r:0 w:1) - fn to_private() -> Weight { - (66_660_730_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(6 as Weight)) - .saturating_add(RocksDbWeight::get().writes(7 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - // Storage: MantaPay UtxoAccumulatorOutputs (r:2 w:1) - // Storage: MantaPay VoidNumberSet (r:2 w:2) - // Storage: MantaPay UtxoSet (r:1 w:1) - // Storage: MantaPay VoidNumberSetSize (r:1 w:1) - // Storage: MantaPay ShardTrees (r:1 w:1) - // Storage: MantaPay VoidNumberSetInsertionOrder (r:0 w:2) - // Storage: MantaPay Shards (r:0 w:1) - fn to_public() -> Weight { - (82_371_125_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(10 as Weight)) - .saturating_add(RocksDbWeight::get().writes(12 as Weight)) - } - // Storage: MantaPay UtxoAccumulatorOutputs (r:2 w:2) - // Storage: MantaPay VoidNumberSet (r:2 w:2) - // Storage: MantaPay UtxoSet (r:2 w:2) - // Storage: MantaPay VoidNumberSetSize (r:1 w:1) - // Storage: MantaPay ShardTrees (r:2 w:2) - // Storage: MantaPay VoidNumberSetInsertionOrder (r:0 w:2) - // Storage: MantaPay Shards (r:0 w:2) - fn private_transfer() -> Weight { - (89_243_134_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(9 as Weight)) - .saturating_add(RocksDbWeight::get().writes(13 as Weight)) - } - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:2 w:2) - fn public_transfer() -> Weight { - (38_433_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } -} \ No newline at end of file + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + // Storage: MantaPay UtxoSet (r:1 w:1) + // Storage: MantaPay VoidNumberSetSize (r:1 w:0) + // Storage: MantaPay ShardTrees (r:1 w:1) + // Storage: MantaPay UtxoAccumulatorOutputs (r:0 w:1) + // Storage: MantaPay Shards (r:0 w:1) + fn to_private() -> Weight { + (66_660_730_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(6 as Weight)) + .saturating_add(RocksDbWeight::get().writes(7 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + // Storage: MantaPay UtxoAccumulatorOutputs (r:2 w:1) + // Storage: MantaPay VoidNumberSet (r:2 w:2) + // Storage: MantaPay UtxoSet (r:1 w:1) + // Storage: MantaPay VoidNumberSetSize (r:1 w:1) + // Storage: MantaPay ShardTrees (r:1 w:1) + // Storage: MantaPay VoidNumberSetInsertionOrder (r:0 w:2) + // Storage: MantaPay Shards (r:0 w:1) + fn to_public() -> Weight { + (82_371_125_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(10 as Weight)) + .saturating_add(RocksDbWeight::get().writes(12 as Weight)) + } + // Storage: MantaPay UtxoAccumulatorOutputs (r:2 w:2) + // Storage: MantaPay VoidNumberSet (r:2 w:2) + // Storage: MantaPay UtxoSet (r:2 w:2) + // Storage: MantaPay VoidNumberSetSize (r:1 w:1) + // Storage: MantaPay ShardTrees (r:2 w:2) + // Storage: MantaPay VoidNumberSetInsertionOrder (r:0 w:2) + // Storage: MantaPay Shards (r:0 w:2) + fn private_transfer() -> Weight { + (89_243_134_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(9 as Weight)) + .saturating_add(RocksDbWeight::get().writes(13 as Weight)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + fn public_transfer() -> Weight { + (38_433_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } +} diff --git a/runtime/dolphin/src/weights/pallet_membership.rs b/runtime/dolphin/src/weights/pallet_membership.rs index 2f56e1adf..447847d85 100644 --- a/runtime/dolphin/src/weights/pallet_membership.rs +++ b/runtime/dolphin/src/weights/pallet_membership.rs @@ -43,174 +43,174 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_membership. pub trait WeightInfo { - fn add_member(m: u32, ) -> Weight; - fn remove_member(m: u32, ) -> Weight; - fn swap_member(m: u32, ) -> Weight; - fn reset_member(m: u32, ) -> Weight; - fn change_key(m: u32, ) -> Weight; - fn set_prime(m: u32, ) -> Weight; - fn clear_prime(m: u32, ) -> Weight; + fn add_member(m: u32, ) -> Weight; + fn remove_member(m: u32, ) -> Weight; + fn swap_member(m: u32, ) -> Weight; + fn reset_member(m: u32, ) -> Weight; + fn change_key(m: u32, ) -> Weight; + fn set_prime(m: u32, ) -> Weight; + fn clear_prime(m: u32, ) -> Weight; } /// Weights for pallet_membership using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_membership::WeightInfo for SubstrateWeight { - // Storage: CouncilMembership Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: Council Members (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn add_member(m: u32, ) -> Weight { - (15_992_000 as Weight) - // Standard Error: 1_000 - .saturating_add((57_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: CouncilMembership Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: CouncilMembership Prime (r:1 w:0) - // Storage: Council Members (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn remove_member(m: u32, ) -> Weight { - (19_169_000 as Weight) - // Standard Error: 0 - .saturating_add((50_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: CouncilMembership Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: CouncilMembership Prime (r:1 w:0) - // Storage: Council Members (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn swap_member(m: u32, ) -> Weight { - (19_090_000 as Weight) - // Standard Error: 1_000 - .saturating_add((66_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: CouncilMembership Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: CouncilMembership Prime (r:1 w:0) - // Storage: Council Members (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn reset_member(m: u32, ) -> Weight { - (19_277_000 as Weight) - // Standard Error: 1_000 - .saturating_add((187_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: CouncilMembership Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: CouncilMembership Prime (r:1 w:1) - // Storage: Council Members (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn change_key(m: u32, ) -> Weight { - (19_595_000 as Weight) - // Standard Error: 1_000 - .saturating_add((68_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - } - // Storage: CouncilMembership Members (r:1 w:0) - // Storage: CouncilMembership Prime (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn set_prime(m: u32, ) -> Weight { - (5_474_000 as Weight) - // Standard Error: 0 - .saturating_add((32_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: CouncilMembership Prime (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn clear_prime(m: u32, ) -> Weight { - (1_913_000 as Weight) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } + // Storage: CouncilMembership Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn add_member(m: u32, ) -> Weight { + (15_992_000 as Weight) + // Standard Error: 1_000 + .saturating_add((57_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: CouncilMembership Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: CouncilMembership Prime (r:1 w:0) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn remove_member(m: u32, ) -> Weight { + (19_169_000 as Weight) + // Standard Error: 0 + .saturating_add((50_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: CouncilMembership Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: CouncilMembership Prime (r:1 w:0) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn swap_member(m: u32, ) -> Weight { + (19_090_000 as Weight) + // Standard Error: 1_000 + .saturating_add((66_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: CouncilMembership Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: CouncilMembership Prime (r:1 w:0) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn reset_member(m: u32, ) -> Weight { + (19_277_000 as Weight) + // Standard Error: 1_000 + .saturating_add((187_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: CouncilMembership Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: CouncilMembership Prime (r:1 w:1) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn change_key(m: u32, ) -> Weight { + (19_595_000 as Weight) + // Standard Error: 1_000 + .saturating_add((68_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + // Storage: CouncilMembership Members (r:1 w:0) + // Storage: CouncilMembership Prime (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn set_prime(m: u32, ) -> Weight { + (5_474_000 as Weight) + // Standard Error: 0 + .saturating_add((32_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: CouncilMembership Prime (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn clear_prime(m: u32, ) -> Weight { + (1_913_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: CouncilMembership Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: Council Members (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn add_member(m: u32, ) -> Weight { - (15_992_000 as Weight) - // Standard Error: 1_000 - .saturating_add((57_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: CouncilMembership Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: CouncilMembership Prime (r:1 w:0) - // Storage: Council Members (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn remove_member(m: u32, ) -> Weight { - (19_169_000 as Weight) - // Standard Error: 0 - .saturating_add((50_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: CouncilMembership Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: CouncilMembership Prime (r:1 w:0) - // Storage: Council Members (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn swap_member(m: u32, ) -> Weight { - (19_090_000 as Weight) - // Standard Error: 1_000 - .saturating_add((66_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: CouncilMembership Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: CouncilMembership Prime (r:1 w:0) - // Storage: Council Members (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn reset_member(m: u32, ) -> Weight { - (19_277_000 as Weight) - // Standard Error: 1_000 - .saturating_add((187_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: CouncilMembership Members (r:1 w:1) - // Storage: Council Proposals (r:1 w:0) - // Storage: CouncilMembership Prime (r:1 w:1) - // Storage: Council Members (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn change_key(m: u32, ) -> Weight { - (19_595_000 as Weight) - // Standard Error: 1_000 - .saturating_add((68_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - } - // Storage: CouncilMembership Members (r:1 w:0) - // Storage: CouncilMembership Prime (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn set_prime(m: u32, ) -> Weight { - (5_474_000 as Weight) - // Standard Error: 0 - .saturating_add((32_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: CouncilMembership Prime (r:0 w:1) - // Storage: Council Prime (r:0 w:1) - fn clear_prime(m: u32, ) -> Weight { - (1_913_000 as Weight) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(m as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } -} \ No newline at end of file + // Storage: CouncilMembership Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn add_member(m: u32, ) -> Weight { + (15_992_000 as Weight) + // Standard Error: 1_000 + .saturating_add((57_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: CouncilMembership Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: CouncilMembership Prime (r:1 w:0) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn remove_member(m: u32, ) -> Weight { + (19_169_000 as Weight) + // Standard Error: 0 + .saturating_add((50_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: CouncilMembership Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: CouncilMembership Prime (r:1 w:0) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn swap_member(m: u32, ) -> Weight { + (19_090_000 as Weight) + // Standard Error: 1_000 + .saturating_add((66_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: CouncilMembership Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: CouncilMembership Prime (r:1 w:0) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn reset_member(m: u32, ) -> Weight { + (19_277_000 as Weight) + // Standard Error: 1_000 + .saturating_add((187_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: CouncilMembership Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: CouncilMembership Prime (r:1 w:1) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn change_key(m: u32, ) -> Weight { + (19_595_000 as Weight) + // Standard Error: 1_000 + .saturating_add((68_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + // Storage: CouncilMembership Members (r:1 w:0) + // Storage: CouncilMembership Prime (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn set_prime(m: u32, ) -> Weight { + (5_474_000 as Weight) + // Standard Error: 0 + .saturating_add((32_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: CouncilMembership Prime (r:0 w:1) + // Storage: Council Prime (r:0 w:1) + fn clear_prime(m: u32, ) -> Weight { + (1_913_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(m as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } +} diff --git a/runtime/dolphin/src/weights/pallet_multisig.rs b/runtime/dolphin/src/weights/pallet_multisig.rs index 53a15d64e..5c563631c 100644 --- a/runtime/dolphin/src/weights/pallet_multisig.rs +++ b/runtime/dolphin/src/weights/pallet_multisig.rs @@ -43,219 +43,219 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_multisig. pub trait WeightInfo { - fn as_multi_threshold_1(z: u32, ) -> Weight; - fn as_multi_create(s: u32, z: u32, ) -> Weight; - fn as_multi_create_store(s: u32, z: u32, ) -> Weight; - fn as_multi_approve(s: u32, z: u32, ) -> Weight; - fn as_multi_approve_store(s: u32, z: u32, ) -> Weight; - fn as_multi_complete(s: u32, z: u32, ) -> Weight; - fn approve_as_multi_create(s: u32, ) -> Weight; - fn approve_as_multi_approve(s: u32, ) -> Weight; - fn approve_as_multi_complete(s: u32, ) -> Weight; - fn cancel_as_multi(s: u32, ) -> Weight; + fn as_multi_threshold_1(z: u32, ) -> Weight; + fn as_multi_create(s: u32, z: u32, ) -> Weight; + fn as_multi_create_store(s: u32, z: u32, ) -> Weight; + fn as_multi_approve(s: u32, z: u32, ) -> Weight; + fn as_multi_approve_store(s: u32, z: u32, ) -> Weight; + fn as_multi_complete(s: u32, z: u32, ) -> Weight; + fn approve_as_multi_create(s: u32, ) -> Weight; + fn approve_as_multi_approve(s: u32, ) -> Weight; + fn approve_as_multi_complete(s: u32, ) -> Weight; + fn cancel_as_multi(s: u32, ) -> Weight; } /// Weights for pallet_multisig using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_multisig::WeightInfo for SubstrateWeight { - fn as_multi_threshold_1(z: u32, ) -> Weight { - (14_147_000 as Weight) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) - fn as_multi_create(s: u32, z: u32, ) -> Weight { - (32_979_000 as Weight) - // Standard Error: 1_000 - .saturating_add((95_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) - fn as_multi_create_store(s: u32, z: u32, ) -> Weight { - (37_484_000 as Weight) - // Standard Error: 2_000 - .saturating_add((92_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - fn as_multi_approve(s: u32, z: u32, ) -> Weight { - (21_837_000 as Weight) - // Standard Error: 1_000 - .saturating_add((89_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - fn as_multi_approve_store(s: u32, z: u32, ) -> Weight { - (35_080_000 as Weight) - // Standard Error: 2_000 - .saturating_add((104_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn as_multi_complete(s: u32, z: u32, ) -> Weight { - (44_180_000 as Weight) - // Standard Error: 1_000 - .saturating_add((139_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((3_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) - fn approve_as_multi_create(s: u32, ) -> Weight { - (30_106_000 as Weight) - // Standard Error: 1_000 - .saturating_add((126_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:0) - fn approve_as_multi_approve(s: u32, ) -> Weight { - (18_057_000 as Weight) - // Standard Error: 1_000 - .saturating_add((114_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn approve_as_multi_complete(s: u32, ) -> Weight { - (62_849_000 as Weight) - // Standard Error: 2_000 - .saturating_add((163_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - fn cancel_as_multi(s: u32, ) -> Weight { - (48_862_000 as Weight) - // Standard Error: 2_000 - .saturating_add((126_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } + fn as_multi_threshold_1(z: u32, ) -> Weight { + (14_147_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) + fn as_multi_create(s: u32, z: u32, ) -> Weight { + (32_979_000 as Weight) + // Standard Error: 1_000 + .saturating_add((95_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) + fn as_multi_create_store(s: u32, z: u32, ) -> Weight { + (37_484_000 as Weight) + // Standard Error: 2_000 + .saturating_add((92_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + fn as_multi_approve(s: u32, z: u32, ) -> Weight { + (21_837_000 as Weight) + // Standard Error: 1_000 + .saturating_add((89_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + fn as_multi_approve_store(s: u32, z: u32, ) -> Weight { + (35_080_000 as Weight) + // Standard Error: 2_000 + .saturating_add((104_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn as_multi_complete(s: u32, z: u32, ) -> Weight { + (44_180_000 as Weight) + // Standard Error: 1_000 + .saturating_add((139_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((3_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) + fn approve_as_multi_create(s: u32, ) -> Weight { + (30_106_000 as Weight) + // Standard Error: 1_000 + .saturating_add((126_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:0) + fn approve_as_multi_approve(s: u32, ) -> Weight { + (18_057_000 as Weight) + // Standard Error: 1_000 + .saturating_add((114_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn approve_as_multi_complete(s: u32, ) -> Weight { + (62_849_000 as Weight) + // Standard Error: 2_000 + .saturating_add((163_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + fn cancel_as_multi(s: u32, ) -> Weight { + (48_862_000 as Weight) + // Standard Error: 2_000 + .saturating_add((126_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - fn as_multi_threshold_1(z: u32, ) -> Weight { - (14_147_000 as Weight) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) - fn as_multi_create(s: u32, z: u32, ) -> Weight { - (32_979_000 as Weight) - // Standard Error: 1_000 - .saturating_add((95_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) - fn as_multi_create_store(s: u32, z: u32, ) -> Weight { - (37_484_000 as Weight) - // Standard Error: 2_000 - .saturating_add((92_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - fn as_multi_approve(s: u32, z: u32, ) -> Weight { - (21_837_000 as Weight) - // Standard Error: 1_000 - .saturating_add((89_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - fn as_multi_approve_store(s: u32, z: u32, ) -> Weight { - (35_080_000 as Weight) - // Standard Error: 2_000 - .saturating_add((104_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn as_multi_complete(s: u32, z: u32, ) -> Weight { - (44_180_000 as Weight) - // Standard Error: 1_000 - .saturating_add((139_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((3_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) - fn approve_as_multi_create(s: u32, ) -> Weight { - (30_106_000 as Weight) - // Standard Error: 1_000 - .saturating_add((126_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:0) - fn approve_as_multi_approve(s: u32, ) -> Weight { - (18_057_000 as Weight) - // Standard Error: 1_000 - .saturating_add((114_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn approve_as_multi_complete(s: u32, ) -> Weight { - (62_849_000 as Weight) - // Standard Error: 2_000 - .saturating_add((163_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - fn cancel_as_multi(s: u32, ) -> Weight { - (48_862_000 as Weight) - // Standard Error: 2_000 - .saturating_add((126_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } -} \ No newline at end of file + fn as_multi_threshold_1(z: u32, ) -> Weight { + (14_147_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) + fn as_multi_create(s: u32, z: u32, ) -> Weight { + (32_979_000 as Weight) + // Standard Error: 1_000 + .saturating_add((95_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) + fn as_multi_create_store(s: u32, z: u32, ) -> Weight { + (37_484_000 as Weight) + // Standard Error: 2_000 + .saturating_add((92_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + fn as_multi_approve(s: u32, z: u32, ) -> Weight { + (21_837_000 as Weight) + // Standard Error: 1_000 + .saturating_add((89_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + fn as_multi_approve_store(s: u32, z: u32, ) -> Weight { + (35_080_000 as Weight) + // Standard Error: 2_000 + .saturating_add((104_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn as_multi_complete(s: u32, z: u32, ) -> Weight { + (44_180_000 as Weight) + // Standard Error: 1_000 + .saturating_add((139_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((3_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) + fn approve_as_multi_create(s: u32, ) -> Weight { + (30_106_000 as Weight) + // Standard Error: 1_000 + .saturating_add((126_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:0) + fn approve_as_multi_approve(s: u32, ) -> Weight { + (18_057_000 as Weight) + // Standard Error: 1_000 + .saturating_add((114_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn approve_as_multi_complete(s: u32, ) -> Weight { + (62_849_000 as Weight) + // Standard Error: 2_000 + .saturating_add((163_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + fn cancel_as_multi(s: u32, ) -> Weight { + (48_862_000 as Weight) + // Standard Error: 2_000 + .saturating_add((126_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } +} diff --git a/runtime/dolphin/src/weights/pallet_preimage.rs b/runtime/dolphin/src/weights/pallet_preimage.rs index 59887c44e..58df7237c 100644 --- a/runtime/dolphin/src/weights/pallet_preimage.rs +++ b/runtime/dolphin/src/weights/pallet_preimage.rs @@ -43,195 +43,195 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_preimage. pub trait WeightInfo { - fn note_preimage(s: u32, ) -> Weight; - fn note_requested_preimage(s: u32, ) -> Weight; - fn note_no_deposit_preimage(s: u32, ) -> Weight; - fn unnote_preimage() -> Weight; - fn unnote_no_deposit_preimage() -> Weight; - fn request_preimage() -> Weight; - fn request_no_deposit_preimage() -> Weight; - fn request_unnoted_preimage() -> Weight; - fn request_requested_preimage() -> Weight; - fn unrequest_preimage() -> Weight; - fn unrequest_unnoted_preimage() -> Weight; - fn unrequest_multi_referenced_preimage() -> Weight; + fn note_preimage(s: u32, ) -> Weight; + fn note_requested_preimage(s: u32, ) -> Weight; + fn note_no_deposit_preimage(s: u32, ) -> Weight; + fn unnote_preimage() -> Weight; + fn unnote_no_deposit_preimage() -> Weight; + fn request_preimage() -> Weight; + fn request_no_deposit_preimage() -> Weight; + fn request_unnoted_preimage() -> Weight; + fn request_requested_preimage() -> Weight; + fn unrequest_preimage() -> Weight; + fn unrequest_unnoted_preimage() -> Weight; + fn unrequest_multi_referenced_preimage() -> Weight; } /// Weights for pallet_preimage using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_preimage::WeightInfo for SubstrateWeight { - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - fn note_preimage(s: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:0) - fn note_requested_preimage(s: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:0) - fn note_no_deposit_preimage(s: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unnote_preimage() -> Weight { - (30_611_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unnote_no_deposit_preimage() -> Weight { - (17_386_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_preimage() -> Weight { - (29_363_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_no_deposit_preimage() -> Weight { - (16_399_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_unnoted_preimage() -> Weight { - (12_806_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_requested_preimage() -> Weight { - (4_849_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unrequest_preimage() -> Weight { - (17_430_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unrequest_unnoted_preimage() -> Weight { - (14_189_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn unrequest_multi_referenced_preimage() -> Weight { - (4_674_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + fn note_preimage(s: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:0) + fn note_requested_preimage(s: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:0) + fn note_no_deposit_preimage(s: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unnote_preimage() -> Weight { + (30_611_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unnote_no_deposit_preimage() -> Weight { + (17_386_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_preimage() -> Weight { + (29_363_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_no_deposit_preimage() -> Weight { + (16_399_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_unnoted_preimage() -> Weight { + (12_806_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_requested_preimage() -> Weight { + (4_849_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unrequest_preimage() -> Weight { + (17_430_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unrequest_unnoted_preimage() -> Weight { + (14_189_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn unrequest_multi_referenced_preimage() -> Weight { + (4_674_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - fn note_preimage(s: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:0) - fn note_requested_preimage(s: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:0) - fn note_no_deposit_preimage(s: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unnote_preimage() -> Weight { - (30_611_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unnote_no_deposit_preimage() -> Weight { - (17_386_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_preimage() -> Weight { - (29_363_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_no_deposit_preimage() -> Weight { - (16_399_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_unnoted_preimage() -> Weight { - (12_806_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_requested_preimage() -> Weight { - (4_849_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unrequest_preimage() -> Weight { - (17_430_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unrequest_unnoted_preimage() -> Weight { - (14_189_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn unrequest_multi_referenced_preimage() -> Weight { - (4_674_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } -} \ No newline at end of file + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + fn note_preimage(s: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:0) + fn note_requested_preimage(s: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:0) + fn note_no_deposit_preimage(s: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unnote_preimage() -> Weight { + (30_611_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unnote_no_deposit_preimage() -> Weight { + (17_386_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_preimage() -> Weight { + (29_363_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_no_deposit_preimage() -> Weight { + (16_399_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_unnoted_preimage() -> Weight { + (12_806_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_requested_preimage() -> Weight { + (4_849_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unrequest_preimage() -> Weight { + (17_430_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unrequest_unnoted_preimage() -> Weight { + (14_189_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn unrequest_multi_referenced_preimage() -> Weight { + (4_674_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } +} diff --git a/runtime/dolphin/src/weights/pallet_scheduler.rs b/runtime/dolphin/src/weights/pallet_scheduler.rs index ee3e9c841..0855c20e1 100644 --- a/runtime/dolphin/src/weights/pallet_scheduler.rs +++ b/runtime/dolphin/src/weights/pallet_scheduler.rs @@ -43,319 +43,319 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_scheduler. pub trait WeightInfo { - fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight; - fn on_initialize_named_resolved(s: u32, ) -> Weight; - fn on_initialize_periodic_resolved(s: u32, ) -> Weight; - fn on_initialize_resolved(s: u32, ) -> Weight; - fn on_initialize_named_aborted(s: u32, ) -> Weight; - fn on_initialize_aborted(s: u32, ) -> Weight; - fn on_initialize_periodic_named(s: u32, ) -> Weight; - fn on_initialize_periodic(s: u32, ) -> Weight; - fn on_initialize_named(s: u32, ) -> Weight; - fn on_initialize(s: u32, ) -> Weight; - fn schedule(s: u32, ) -> Weight; - fn cancel(s: u32, ) -> Weight; - fn schedule_named(s: u32, ) -> Weight; - fn cancel_named(s: u32, ) -> Weight; + fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight; + fn on_initialize_named_resolved(s: u32, ) -> Weight; + fn on_initialize_periodic_resolved(s: u32, ) -> Weight; + fn on_initialize_resolved(s: u32, ) -> Weight; + fn on_initialize_named_aborted(s: u32, ) -> Weight; + fn on_initialize_aborted(s: u32, ) -> Weight; + fn on_initialize_periodic_named(s: u32, ) -> Weight; + fn on_initialize_periodic(s: u32, ) -> Weight; + fn on_initialize_named(s: u32, ) -> Weight; + fn on_initialize(s: u32, ) -> Weight; + fn schedule(s: u32, ) -> Weight; + fn cancel(s: u32, ) -> Weight; + fn schedule_named(s: u32, ) -> Weight; + fn cancel_named(s: u32, ) -> Weight; } /// Weights for pallet_scheduler using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_scheduler::WeightInfo for SubstrateWeight { - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight { - (12_309_000 as Weight) - // Standard Error: 49_000 - .saturating_add((24_661_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((4 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_named_resolved(s: u32, ) -> Weight { - (10_936_000 as Weight) - // Standard Error: 46_000 - .saturating_add((19_627_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - fn on_initialize_periodic_resolved(s: u32, ) -> Weight { - (13_808_000 as Weight) - // Standard Error: 46_000 - .saturating_add((21_464_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - fn on_initialize_resolved(s: u32, ) -> Weight { - (10_022_000 as Weight) - // Standard Error: 45_000 - .saturating_add((18_200_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:0) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_named_aborted(s: u32, ) -> Weight { - (7_017_000 as Weight) - // Standard Error: 28_000 - .saturating_add((8_806_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:0) - fn on_initialize_aborted(s: u32, ) -> Weight { - (8_804_000 as Weight) - // Standard Error: 21_000 - .saturating_add((5_819_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_periodic_named(s: u32, ) -> Weight { - (14_322_000 as Weight) - // Standard Error: 40_000 - .saturating_add((13_518_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - fn on_initialize_periodic(s: u32, ) -> Weight { - (12_056_000 as Weight) - // Standard Error: 33_000 - .saturating_add((10_680_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_named(s: u32, ) -> Weight { - (13_083_000 as Weight) - // Standard Error: 28_000 - .saturating_add((8_632_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - fn on_initialize(s: u32, ) -> Weight { - (13_043_000 as Weight) - // Standard Error: 26_000 - .saturating_add((7_433_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Scheduler Agenda (r:1 w:1) - fn schedule(s: u32, ) -> Weight { - (16_174_000 as Weight) - // Standard Error: 2_000 - .saturating_add((88_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn cancel(s: u32, ) -> Weight { - (15_987_000 as Weight) - // Standard Error: 6_000 - .saturating_add((1_711_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Scheduler Lookup (r:1 w:1) - // Storage: Scheduler Agenda (r:1 w:1) - fn schedule_named(s: u32, ) -> Weight { - (18_905_000 as Weight) - // Standard Error: 2_000 - .saturating_add((119_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Scheduler Lookup (r:1 w:1) - // Storage: Scheduler Agenda (r:1 w:1) - fn cancel_named(s: u32, ) -> Weight { - (18_088_000 as Weight) - // Standard Error: 7_000 - .saturating_add((1_719_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight { + (12_309_000 as Weight) + // Standard Error: 49_000 + .saturating_add((24_661_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((4 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_named_resolved(s: u32, ) -> Weight { + (10_936_000 as Weight) + // Standard Error: 46_000 + .saturating_add((19_627_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + fn on_initialize_periodic_resolved(s: u32, ) -> Weight { + (13_808_000 as Weight) + // Standard Error: 46_000 + .saturating_add((21_464_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + fn on_initialize_resolved(s: u32, ) -> Weight { + (10_022_000 as Weight) + // Standard Error: 45_000 + .saturating_add((18_200_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:0) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_named_aborted(s: u32, ) -> Weight { + (7_017_000 as Weight) + // Standard Error: 28_000 + .saturating_add((8_806_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:0) + fn on_initialize_aborted(s: u32, ) -> Weight { + (8_804_000 as Weight) + // Standard Error: 21_000 + .saturating_add((5_819_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_periodic_named(s: u32, ) -> Weight { + (14_322_000 as Weight) + // Standard Error: 40_000 + .saturating_add((13_518_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + fn on_initialize_periodic(s: u32, ) -> Weight { + (12_056_000 as Weight) + // Standard Error: 33_000 + .saturating_add((10_680_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_named(s: u32, ) -> Weight { + (13_083_000 as Weight) + // Standard Error: 28_000 + .saturating_add((8_632_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + fn on_initialize(s: u32, ) -> Weight { + (13_043_000 as Weight) + // Standard Error: 26_000 + .saturating_add((7_433_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Scheduler Agenda (r:1 w:1) + fn schedule(s: u32, ) -> Weight { + (16_174_000 as Weight) + // Standard Error: 2_000 + .saturating_add((88_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn cancel(s: u32, ) -> Weight { + (15_987_000 as Weight) + // Standard Error: 6_000 + .saturating_add((1_711_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Scheduler Lookup (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn schedule_named(s: u32, ) -> Weight { + (18_905_000 as Weight) + // Standard Error: 2_000 + .saturating_add((119_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Scheduler Lookup (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn cancel_named(s: u32, ) -> Weight { + (18_088_000 as Weight) + // Standard Error: 7_000 + .saturating_add((1_719_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight { - (12_309_000 as Weight) - // Standard Error: 49_000 - .saturating_add((24_661_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((4 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_named_resolved(s: u32, ) -> Weight { - (10_936_000 as Weight) - // Standard Error: 46_000 - .saturating_add((19_627_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - fn on_initialize_periodic_resolved(s: u32, ) -> Weight { - (13_808_000 as Weight) - // Standard Error: 46_000 - .saturating_add((21_464_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - fn on_initialize_resolved(s: u32, ) -> Weight { - (10_022_000 as Weight) - // Standard Error: 45_000 - .saturating_add((18_200_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:0) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_named_aborted(s: u32, ) -> Weight { - (7_017_000 as Weight) - // Standard Error: 28_000 - .saturating_add((8_806_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:0) - fn on_initialize_aborted(s: u32, ) -> Weight { - (8_804_000 as Weight) - // Standard Error: 21_000 - .saturating_add((5_819_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_periodic_named(s: u32, ) -> Weight { - (14_322_000 as Weight) - // Standard Error: 40_000 - .saturating_add((13_518_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - fn on_initialize_periodic(s: u32, ) -> Weight { - (12_056_000 as Weight) - // Standard Error: 33_000 - .saturating_add((10_680_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_named(s: u32, ) -> Weight { - (13_083_000 as Weight) - // Standard Error: 28_000 - .saturating_add((8_632_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - fn on_initialize(s: u32, ) -> Weight { - (13_043_000 as Weight) - // Standard Error: 26_000 - .saturating_add((7_433_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Scheduler Agenda (r:1 w:1) - fn schedule(s: u32, ) -> Weight { - (16_174_000 as Weight) - // Standard Error: 2_000 - .saturating_add((88_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn cancel(s: u32, ) -> Weight { - (15_987_000 as Weight) - // Standard Error: 6_000 - .saturating_add((1_711_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Scheduler Lookup (r:1 w:1) - // Storage: Scheduler Agenda (r:1 w:1) - fn schedule_named(s: u32, ) -> Weight { - (18_905_000 as Weight) - // Standard Error: 2_000 - .saturating_add((119_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Scheduler Lookup (r:1 w:1) - // Storage: Scheduler Agenda (r:1 w:1) - fn cancel_named(s: u32, ) -> Weight { - (18_088_000 as Weight) - // Standard Error: 7_000 - .saturating_add((1_719_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } -} \ No newline at end of file + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight { + (12_309_000 as Weight) + // Standard Error: 49_000 + .saturating_add((24_661_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((4 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_named_resolved(s: u32, ) -> Weight { + (10_936_000 as Weight) + // Standard Error: 46_000 + .saturating_add((19_627_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + fn on_initialize_periodic_resolved(s: u32, ) -> Weight { + (13_808_000 as Weight) + // Standard Error: 46_000 + .saturating_add((21_464_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + fn on_initialize_resolved(s: u32, ) -> Weight { + (10_022_000 as Weight) + // Standard Error: 45_000 + .saturating_add((18_200_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:0) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_named_aborted(s: u32, ) -> Weight { + (7_017_000 as Weight) + // Standard Error: 28_000 + .saturating_add((8_806_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:0) + fn on_initialize_aborted(s: u32, ) -> Weight { + (8_804_000 as Weight) + // Standard Error: 21_000 + .saturating_add((5_819_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_periodic_named(s: u32, ) -> Weight { + (14_322_000 as Weight) + // Standard Error: 40_000 + .saturating_add((13_518_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + fn on_initialize_periodic(s: u32, ) -> Weight { + (12_056_000 as Weight) + // Standard Error: 33_000 + .saturating_add((10_680_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_named(s: u32, ) -> Weight { + (13_083_000 as Weight) + // Standard Error: 28_000 + .saturating_add((8_632_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + fn on_initialize(s: u32, ) -> Weight { + (13_043_000 as Weight) + // Standard Error: 26_000 + .saturating_add((7_433_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Scheduler Agenda (r:1 w:1) + fn schedule(s: u32, ) -> Weight { + (16_174_000 as Weight) + // Standard Error: 2_000 + .saturating_add((88_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn cancel(s: u32, ) -> Weight { + (15_987_000 as Weight) + // Standard Error: 6_000 + .saturating_add((1_711_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Scheduler Lookup (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn schedule_named(s: u32, ) -> Weight { + (18_905_000 as Weight) + // Standard Error: 2_000 + .saturating_add((119_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Scheduler Lookup (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn cancel_named(s: u32, ) -> Weight { + (18_088_000 as Weight) + // Standard Error: 7_000 + .saturating_add((1_719_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } +} diff --git a/runtime/dolphin/src/weights/pallet_session.rs b/runtime/dolphin/src/weights/pallet_session.rs index cc0fa168f..5cdc2deb6 100644 --- a/runtime/dolphin/src/weights/pallet_session.rs +++ b/runtime/dolphin/src/weights/pallet_session.rs @@ -43,43 +43,43 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_session. pub trait WeightInfo { - fn set_keys() -> Weight; - fn purge_keys() -> Weight; + fn set_keys() -> Weight; + fn purge_keys() -> Weight; } /// Weights for pallet_session using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_session::WeightInfo for SubstrateWeight { - // Storage: Session NextKeys (r:1 w:1) - // Storage: Session KeyOwner (r:1 w:1) - fn set_keys() -> Weight { - (14_329_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Session NextKeys (r:1 w:1) - // Storage: Session KeyOwner (r:0 w:1) - fn purge_keys() -> Weight { - (10_750_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } + // Storage: Session NextKeys (r:1 w:1) + // Storage: Session KeyOwner (r:1 w:1) + fn set_keys() -> Weight { + (14_329_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Session NextKeys (r:1 w:1) + // Storage: Session KeyOwner (r:0 w:1) + fn purge_keys() -> Weight { + (10_750_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Session NextKeys (r:1 w:1) - // Storage: Session KeyOwner (r:1 w:1) - fn set_keys() -> Weight { - (14_329_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Session NextKeys (r:1 w:1) - // Storage: Session KeyOwner (r:0 w:1) - fn purge_keys() -> Weight { - (10_750_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } -} \ No newline at end of file + // Storage: Session NextKeys (r:1 w:1) + // Storage: Session KeyOwner (r:1 w:1) + fn set_keys() -> Weight { + (14_329_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Session NextKeys (r:1 w:1) + // Storage: Session KeyOwner (r:0 w:1) + fn purge_keys() -> Weight { + (10_750_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } +} diff --git a/runtime/dolphin/src/weights/pallet_timestamp.rs b/runtime/dolphin/src/weights/pallet_timestamp.rs index 4a940c0ae..4b4821c91 100644 --- a/runtime/dolphin/src/weights/pallet_timestamp.rs +++ b/runtime/dolphin/src/weights/pallet_timestamp.rs @@ -43,33 +43,33 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_timestamp. pub trait WeightInfo { - fn set() -> Weight; - fn on_finalize() -> Weight; + fn set() -> Weight; + fn on_finalize() -> Weight; } /// Weights for pallet_timestamp using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_timestamp::WeightInfo for SubstrateWeight { - // Storage: Timestamp Now (r:1 w:1) - fn set() -> Weight { - (4_689_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn on_finalize() -> Weight { - (2_969_000 as Weight) - } + // Storage: Timestamp Now (r:1 w:1) + fn set() -> Weight { + (4_689_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + fn on_finalize() -> Weight { + (2_969_000 as Weight) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Timestamp Now (r:1 w:1) - fn set() -> Weight { - (4_689_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - fn on_finalize() -> Weight { - (2_969_000 as Weight) - } -} \ No newline at end of file + // Storage: Timestamp Now (r:1 w:1) + fn set() -> Weight { + (4_689_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + fn on_finalize() -> Weight { + (2_969_000 as Weight) + } +} diff --git a/runtime/dolphin/src/weights/pallet_treasury.rs b/runtime/dolphin/src/weights/pallet_treasury.rs index a204cbf57..a15e41a78 100644 --- a/runtime/dolphin/src/weights/pallet_treasury.rs +++ b/runtime/dolphin/src/weights/pallet_treasury.rs @@ -43,87 +43,87 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_treasury. pub trait WeightInfo { - fn propose_spend() -> Weight; - fn reject_proposal() -> Weight; - fn approve_proposal(p: u32, ) -> Weight; - fn on_initialize_proposals(p: u32, ) -> Weight; + fn propose_spend() -> Weight; + fn reject_proposal() -> Weight; + fn approve_proposal(p: u32, ) -> Weight; + fn on_initialize_proposals(p: u32, ) -> Weight; } /// Weights for pallet_treasury using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_treasury::WeightInfo for SubstrateWeight { - // Storage: Treasury ProposalCount (r:1 w:1) - // Storage: Treasury Proposals (r:0 w:1) - fn propose_spend() -> Weight { - (25_170_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Treasury Proposals (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn reject_proposal() -> Weight { - (45_793_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Treasury Proposals (r:1 w:0) - // Storage: Treasury Approvals (r:1 w:1) - fn approve_proposal(p: u32, ) -> Weight { - (10_320_000 as Weight) - // Standard Error: 1_000 - .saturating_add((73_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Treasury Approvals (r:1 w:1) - // Storage: Treasury Proposals (r:2 w:2) - // Storage: System Account (r:4 w:4) - fn on_initialize_proposals(p: u32, ) -> Weight { - (29_308_000 as Weight) - // Standard Error: 36_000 - .saturating_add((32_496_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(p as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(p as Weight))) - } + // Storage: Treasury ProposalCount (r:1 w:1) + // Storage: Treasury Proposals (r:0 w:1) + fn propose_spend() -> Weight { + (25_170_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Treasury Proposals (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn reject_proposal() -> Weight { + (45_793_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Treasury Proposals (r:1 w:0) + // Storage: Treasury Approvals (r:1 w:1) + fn approve_proposal(p: u32, ) -> Weight { + (10_320_000 as Weight) + // Standard Error: 1_000 + .saturating_add((73_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Treasury Approvals (r:1 w:1) + // Storage: Treasury Proposals (r:2 w:2) + // Storage: System Account (r:4 w:4) + fn on_initialize_proposals(p: u32, ) -> Weight { + (29_308_000 as Weight) + // Standard Error: 36_000 + .saturating_add((32_496_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(p as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(p as Weight))) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Treasury ProposalCount (r:1 w:1) - // Storage: Treasury Proposals (r:0 w:1) - fn propose_spend() -> Weight { - (25_170_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Treasury Proposals (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn reject_proposal() -> Weight { - (45_793_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Treasury Proposals (r:1 w:0) - // Storage: Treasury Approvals (r:1 w:1) - fn approve_proposal(p: u32, ) -> Weight { - (10_320_000 as Weight) - // Standard Error: 1_000 - .saturating_add((73_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Treasury Approvals (r:1 w:1) - // Storage: Treasury Proposals (r:2 w:2) - // Storage: System Account (r:4 w:4) - fn on_initialize_proposals(p: u32, ) -> Weight { - (29_308_000 as Weight) - // Standard Error: 36_000 - .saturating_add((32_496_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(p as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(p as Weight))) - } -} \ No newline at end of file + // Storage: Treasury ProposalCount (r:1 w:1) + // Storage: Treasury Proposals (r:0 w:1) + fn propose_spend() -> Weight { + (25_170_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Treasury Proposals (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn reject_proposal() -> Weight { + (45_793_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Treasury Proposals (r:1 w:0) + // Storage: Treasury Approvals (r:1 w:1) + fn approve_proposal(p: u32, ) -> Weight { + (10_320_000 as Weight) + // Standard Error: 1_000 + .saturating_add((73_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Treasury Approvals (r:1 w:1) + // Storage: Treasury Proposals (r:2 w:2) + // Storage: System Account (r:4 w:4) + fn on_initialize_proposals(p: u32, ) -> Weight { + (29_308_000 as Weight) + // Standard Error: 36_000 + .saturating_add((32_496_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(p as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(p as Weight))) + } +} diff --git a/runtime/dolphin/src/weights/pallet_tx_pause.rs b/runtime/dolphin/src/weights/pallet_tx_pause.rs index 8bd5e8e21..8a297b7a7 100644 --- a/runtime/dolphin/src/weights/pallet_tx_pause.rs +++ b/runtime/dolphin/src/weights/pallet_tx_pause.rs @@ -43,39 +43,39 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_tx_pause. pub trait WeightInfo { - fn pause_transaction() -> Weight; - fn unpause_transaction() -> Weight; + fn pause_transaction() -> Weight; + fn unpause_transaction() -> Weight; } /// Weights for pallet_tx_pause using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_tx_pause::WeightInfo for SubstrateWeight { - // Storage: TransactionPause PausedTransactions (r:1 w:1) - fn pause_transaction() -> Weight { - (12_241_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: TransactionPause PausedTransactions (r:1 w:1) - fn unpause_transaction() -> Weight { - (13_232_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } + // Storage: TransactionPause PausedTransactions (r:1 w:1) + fn pause_transaction() -> Weight { + (12_241_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: TransactionPause PausedTransactions (r:1 w:1) + fn unpause_transaction() -> Weight { + (13_232_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: TransactionPause PausedTransactions (r:1 w:1) - fn pause_transaction() -> Weight { - (12_241_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: TransactionPause PausedTransactions (r:1 w:1) - fn unpause_transaction() -> Weight { - (13_232_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } -} \ No newline at end of file + // Storage: TransactionPause PausedTransactions (r:1 w:1) + fn pause_transaction() -> Weight { + (12_241_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: TransactionPause PausedTransactions (r:1 w:1) + fn unpause_transaction() -> Weight { + (13_232_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } +} diff --git a/runtime/dolphin/src/weights/pallet_utility.rs b/runtime/dolphin/src/weights/pallet_utility.rs index 836aae2fd..7bf653107 100644 --- a/runtime/dolphin/src/weights/pallet_utility.rs +++ b/runtime/dolphin/src/weights/pallet_utility.rs @@ -43,49 +43,49 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_utility. pub trait WeightInfo { - fn batch(c: u32, ) -> Weight; - fn as_derivative() -> Weight; - fn batch_all(c: u32, ) -> Weight; - fn dispatch_as() -> Weight; + fn batch(c: u32, ) -> Weight; + fn as_derivative() -> Weight; + fn batch_all(c: u32, ) -> Weight; + fn dispatch_as() -> Weight; } /// Weights for pallet_utility using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_utility::WeightInfo for SubstrateWeight { - fn batch(c: u32, ) -> Weight { - (19_973_000 as Weight) - // Standard Error: 5_000 - .saturating_add((3_533_000 as Weight).saturating_mul(c as Weight)) - } - fn as_derivative() -> Weight { - (2_306_000 as Weight) - } - fn batch_all(c: u32, ) -> Weight { - (27_560_000 as Weight) - // Standard Error: 4_000 - .saturating_add((3_786_000 as Weight).saturating_mul(c as Weight)) - } - fn dispatch_as() -> Weight { - (9_329_000 as Weight) - } + fn batch(c: u32, ) -> Weight { + (19_973_000 as Weight) + // Standard Error: 5_000 + .saturating_add((3_533_000 as Weight).saturating_mul(c as Weight)) + } + fn as_derivative() -> Weight { + (2_306_000 as Weight) + } + fn batch_all(c: u32, ) -> Weight { + (27_560_000 as Weight) + // Standard Error: 4_000 + .saturating_add((3_786_000 as Weight).saturating_mul(c as Weight)) + } + fn dispatch_as() -> Weight { + (9_329_000 as Weight) + } } // For backwards compatibility and tests impl WeightInfo for () { - fn batch(c: u32, ) -> Weight { - (19_973_000 as Weight) - // Standard Error: 5_000 - .saturating_add((3_533_000 as Weight).saturating_mul(c as Weight)) - } - fn as_derivative() -> Weight { - (2_306_000 as Weight) - } - fn batch_all(c: u32, ) -> Weight { - (27_560_000 as Weight) - // Standard Error: 4_000 - .saturating_add((3_786_000 as Weight).saturating_mul(c as Weight)) - } - fn dispatch_as() -> Weight { - (9_329_000 as Weight) - } -} \ No newline at end of file + fn batch(c: u32, ) -> Weight { + (19_973_000 as Weight) + // Standard Error: 5_000 + .saturating_add((3_533_000 as Weight).saturating_mul(c as Weight)) + } + fn as_derivative() -> Weight { + (2_306_000 as Weight) + } + fn batch_all(c: u32, ) -> Weight { + (27_560_000 as Weight) + // Standard Error: 4_000 + .saturating_add((3_786_000 as Weight).saturating_mul(c as Weight)) + } + fn dispatch_as() -> Weight { + (9_329_000 as Weight) + } +} diff --git a/runtime/dolphin/src/xcm_config.rs b/runtime/dolphin/src/xcm_config.rs index 9afcd89bb..8e5fefa1b 100644 --- a/runtime/dolphin/src/xcm_config.rs +++ b/runtime/dolphin/src/xcm_config.rs @@ -15,9 +15,9 @@ // along with Manta. If not, see . use super::{ - AssetManager, Assets, Balances, Call, DmpQueue, EnsureRootOrMoreThanHalfCouncil, Event, Origin, - ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, Treasury, XcmpQueue, - MAXIMUM_BLOCK_WEIGHT, + AssetManager, Assets, Balances, Call, DmpQueue, EnsureRootOrMoreThanHalfCouncil, Event, Origin, + ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, Treasury, XcmpQueue, + MAXIMUM_BLOCK_WEIGHT, }; use codec::{Decode, Encode}; @@ -26,15 +26,15 @@ use scale_info::TypeInfo; use sp_std::prelude::*; use frame_support::{ - match_type, parameter_types, - traits::{Everything, Nothing}, - weights::Weight, + match_type, parameter_types, + traits::{Everything, Nothing}, + weights::Weight, }; use frame_system::EnsureRoot; use manta_primitives::{ - assets::{AssetIdLocationConvert, AssetLocation}, - types::{AccountId, AssetId, Balance}, - xcm::{AccountIdToMultiLocation, FirstAssetTrader, IsNativeConcrete, MultiNativeAsset}, + assets::{AssetIdLocationConvert, AssetLocation}, + types::{AccountId, AssetId, Balance}, + xcm::{AccountIdToMultiLocation, FirstAssetTrader, IsNativeConcrete, MultiNativeAsset}, }; #[cfg(any(feature = "std", test))] @@ -46,29 +46,29 @@ use polkadot_parachain::primitives::Sibling; use xcm::latest::prelude::*; use xcm_builder::{ - AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, - AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, ConvertedConcreteAssetId, - CurrencyAdapter as XcmCurrencyAdapter, EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, - FungiblesAdapter, LocationInverter, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, - SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, - SovereignSignedViaLocation, TakeWeightCredit, + AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, + AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, ConvertedConcreteAssetId, + CurrencyAdapter as XcmCurrencyAdapter, EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, + FungiblesAdapter, LocationInverter, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, + SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, + SovereignSignedViaLocation, TakeWeightCredit, }; use xcm_executor::{traits::JustTry, Config, XcmExecutor}; parameter_types! { - pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; - pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; + pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; + pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; } impl cumulus_pallet_parachain_system::Config for Runtime { - type Event = Event; - type SelfParaId = parachain_info::Pallet; - type DmpMessageHandler = DmpQueue; - type ReservedDmpWeight = ReservedDmpWeight; - type OutboundXcmpMessageSource = XcmpQueue; - type XcmpMessageHandler = XcmpQueue; - type ReservedXcmpWeight = ReservedXcmpWeight; - type OnSystemEvent = (); + type Event = Event; + type SelfParaId = parachain_info::Pallet; + type DmpMessageHandler = DmpQueue; + type ReservedDmpWeight = ReservedDmpWeight; + type OutboundXcmpMessageSource = XcmpQueue; + type XcmpMessageHandler = XcmpQueue; + type ReservedXcmpWeight = ReservedXcmpWeight; + type OnSystemEvent = (); } impl parachain_info::Config for Runtime {} @@ -76,38 +76,38 @@ impl parachain_info::Config for Runtime {} impl cumulus_pallet_aura_ext::Config for Runtime {} parameter_types! { - pub const KsmLocation: MultiLocation = MultiLocation::parent(); - pub const RelayNetwork: NetworkId = NetworkId::Kusama; - pub RelayChainOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into(); - pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into(); - pub SelfReserve: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::parachain_id().into()))); - pub CheckingAccount: AccountId = PolkadotXcm::check_account(); + pub const KsmLocation: MultiLocation = MultiLocation::parent(); + pub const RelayNetwork: NetworkId = NetworkId::Kusama; + pub RelayChainOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into(); + pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into(); + pub SelfReserve: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::parachain_id().into()))); + pub CheckingAccount: AccountId = PolkadotXcm::check_account(); } /// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used /// when determining ownership of accounts for asset transacting and when attempting to use XCM /// `Transact` in order to determine the dispatch Origin. pub type LocationToAccountId = ( - // The parent (Relay-chain) origin converts to the default `AccountId`. - ParentIsPreset, - // Sibling parachain origins convert to AccountId via the `ParaId::into`. - SiblingParachainConvertsVia, - // Straight up local `AccountId32` origins just alias directly to `AccountId`. - AccountId32Aliases, + // The parent (Relay-chain) origin converts to the default `AccountId`. + ParentIsPreset, + // Sibling parachain origins convert to AccountId via the `ParaId::into`. + SiblingParachainConvertsVia, + // Straight up local `AccountId32` origins just alias directly to `AccountId`. + AccountId32Aliases, ); /// Transactor for native currency, i.e. implements `fungible` trait pub type LocalAssetTransactor = XcmCurrencyAdapter< - // Transacting native currency, i.e. MANTA, KMA, DOL - Balances, - // Used when the incoming asset is a fungible concrete asset matching the given location or name: - IsNativeConcrete, - // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: - LocationToAccountId, - // Our chain's account ID type (we can't get away without mentioning it explicitly): - AccountId, - // We don't track any teleports. - (), + // Transacting native currency, i.e. MANTA, KMA, DOL + Balances, + // Used when the incoming asset is a fungible concrete asset matching the given location or name: + IsNativeConcrete, + // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: + LocationToAccountId, + // Our chain's account ID type (we can't get away without mentioning it explicitly): + AccountId, + // We don't track any teleports. + (), >; /// This is the type to convert an (incoming) XCM origin into a local `Origin` instance, @@ -115,130 +115,130 @@ pub type LocalAssetTransactor = XcmCurrencyAdapter< /// It uses some Rust magic macro to do the pattern matching sequentially. /// There is an `OriginKind` which can biases the kind of local `Origin` it will become. pub type XcmOriginToCallOrigin = ( - // Sovereign account converter; this attempts to derive an `AccountId` from the origin location - // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for - // foreign chains who want to have a local sovereign account on this chain which they control. - SovereignSignedViaLocation, - // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when - // recognised. - RelayChainAsNative, - // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when - // recognised. - SiblingParachainAsNative, - // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a - // transaction from the Root origin. - ParentAsSuperuser, - // If the incoming XCM origin is of type `AccountId32` and the Network is Network::Any - // or `RelayNetwork`, convert it to a Native 32 byte account. - SignedAccountId32AsNative, - // Xcm origins can be represented natively under the Xcm pallet's Xcm origin. - XcmPassthrough, + // Sovereign account converter; this attempts to derive an `AccountId` from the origin location + // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for + // foreign chains who want to have a local sovereign account on this chain which they control. + SovereignSignedViaLocation, + // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when + // recognised. + RelayChainAsNative, + // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when + // recognised. + SiblingParachainAsNative, + // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a + // transaction from the Root origin. + ParentAsSuperuser, + // If the incoming XCM origin is of type `AccountId32` and the Network is Network::Any + // or `RelayNetwork`, convert it to a Native 32 byte account. + SignedAccountId32AsNative, + // Xcm origins can be represented natively under the Xcm pallet's Xcm origin. + XcmPassthrough, ); parameter_types! { - // One XCM operation is 1_000_000_000 weight - almost certainly a conservative estimate. - pub UnitWeightCost: Weight = 1_000_000_000; - // Used in native traders - // This might be able to skipped. - // We have to use `here()` because of reanchoring logic - pub ParaTokenPerSecond: (xcm::v2::AssetId, u128) = (Concrete(MultiLocation::here()), 1_000_000_000); - pub const MaxInstructions: u32 = 100; + // One XCM operation is 1_000_000_000 weight - almost certainly a conservative estimate. + pub UnitWeightCost: Weight = 1_000_000_000; + // Used in native traders + // This might be able to skipped. + // We have to use `here()` because of reanchoring logic + pub ParaTokenPerSecond: (xcm::v2::AssetId, u128) = (Concrete(MultiLocation::here()), 1_000_000_000); + pub const MaxInstructions: u32 = 100; } /// Transactor for currency in pallet-assets, i.e. implements `fungibles` trait pub type FungiblesTransactor = FungiblesAdapter< - Assets, - ConvertedConcreteAssetId< - AssetId, - Balance, - AssetIdLocationConvert, - JustTry, - >, - // "default" implementation of converting a `MultiLocation` to an `AccountId` - LocationToAccountId, - AccountId, - // No teleport support. - Nothing, - // No teleport tracking. - CheckingAccount, + Assets, + ConvertedConcreteAssetId< + AssetId, + Balance, + AssetIdLocationConvert, + JustTry, + >, + // "default" implementation of converting a `MultiLocation` to an `AccountId` + LocationToAccountId, + AccountId, + // No teleport support. + Nothing, + // No teleport tracking. + CheckingAccount, >; match_type! { - pub type ParentOrParentsExecutivePlurality: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Executive, .. }) } - }; + pub type ParentOrParentsExecutivePlurality: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Executive, .. }) } + }; } match_type! { - pub type ParentOrSiblings: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(_) } - }; + pub type ParentOrSiblings: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(_) } + }; } pub type Barrier = ( - // Allows local origin messages which call weight_credit >= weight_limit. - TakeWeightCredit, - // Allows non-local origin messages, for example from from the xcmp queue, - // which have the ability to deposit assets and pay for their own execution. - AllowTopLevelPaidExecutionFrom, - // Parent and its exec plurality get free execution - AllowUnpaidExecutionFrom, - // Expected responses are OK. - // Allows `Pending` or `VersionNotifier` query responses. - AllowKnownQueryResponses, - // Subscriptions for version tracking are OK. - // Allows execution of `SubscribeVersion` or `UnsubscribeVersion` instruction, - // from parent or sibling chains. - AllowSubscriptionsFrom, + // Allows local origin messages which call weight_credit >= weight_limit. + TakeWeightCredit, + // Allows non-local origin messages, for example from from the xcmp queue, + // which have the ability to deposit assets and pay for their own execution. + AllowTopLevelPaidExecutionFrom, + // Parent and its exec plurality get free execution + AllowUnpaidExecutionFrom, + // Expected responses are OK. + // Allows `Pending` or `VersionNotifier` query responses. + AllowKnownQueryResponses, + // Subscriptions for version tracking are OK. + // Allows execution of `SubscribeVersion` or `UnsubscribeVersion` instruction, + // from parent or sibling chains. + AllowSubscriptionsFrom, ); parameter_types! { - pub XcmFeesAccount: AccountId = Treasury::account_id(); + pub XcmFeesAccount: AccountId = Treasury::account_id(); } pub type XcmFeesToAccount = manta_primitives::xcm::XcmFeesToAccount< - Assets, - ConvertedConcreteAssetId< - AssetId, - Balance, - AssetIdLocationConvert, - JustTry, - >, - AccountId, - XcmFeesAccount, + Assets, + ConvertedConcreteAssetId< + AssetId, + Balance, + AssetIdLocationConvert, + JustTry, + >, + AccountId, + XcmFeesAccount, >; pub struct XcmExecutorConfig; impl Config for XcmExecutorConfig { - type Call = Call; - type XcmSender = XcmRouter; - // Defines how to Withdraw and Deposit instruction work - // Under the hood, substrate framework will do pattern matching in macro, - // as a result, the order of the following tuple matters. - type AssetTransactor = (LocalAssetTransactor, FungiblesTransactor); - type OriginConverter = XcmOriginToCallOrigin; - // Combinations of (Location, Asset) pairs which we trust as reserves. - type IsReserve = MultiNativeAsset; - type IsTeleporter = (); - type LocationInverter = LocationInverter; - type Barrier = Barrier; - type Weigher = FixedWeightBounds; - // Trader is the means to purchasing weight credit for XCM execution. - // We define two traders: - // The first one will charge parachain's native currency, who's `MultiLocation` - // is defined in `SelfReserve`. - // The second one will charge the first asset in the MultiAssets with pre-defined rate - // i.e. units_per_second in `AssetManager` - type Trader = ( - FixedRateOfFungible, - FirstAssetTrader, - ); - type ResponseHandler = PolkadotXcm; - type AssetTrap = PolkadotXcm; - type AssetClaims = PolkadotXcm; - // This is needed for the version change notifier work - type SubscriptionService = PolkadotXcm; + type Call = Call; + type XcmSender = XcmRouter; + // Defines how to Withdraw and Deposit instruction work + // Under the hood, substrate framework will do pattern matching in macro, + // as a result, the order of the following tuple matters. + type AssetTransactor = (LocalAssetTransactor, FungiblesTransactor); + type OriginConverter = XcmOriginToCallOrigin; + // Combinations of (Location, Asset) pairs which we trust as reserves. + type IsReserve = MultiNativeAsset; + type IsTeleporter = (); + type LocationInverter = LocationInverter; + type Barrier = Barrier; + type Weigher = FixedWeightBounds; + // Trader is the means to purchasing weight credit for XCM execution. + // We define two traders: + // The first one will charge parachain's native currency, who's `MultiLocation` + // is defined in `SelfReserve`. + // The second one will charge the first asset in the MultiAssets with pre-defined rate + // i.e. units_per_second in `AssetManager` + type Trader = ( + FixedRateOfFungible, + FirstAssetTrader, + ); + type ResponseHandler = PolkadotXcm; + type AssetTrap = PolkadotXcm; + type AssetClaims = PolkadotXcm; + // This is needed for the version change notifier work + type SubscriptionService = PolkadotXcm; } /// No one is allowed to dispatch XCM sends/executions. @@ -247,99 +247,99 @@ pub type LocalOriginToLocation = (); /// The means for routing XCM messages which are not for local execution into the right message /// queues. pub type XcmRouter = ( - // Two routers - use UMP to communicate with the relay chain: - cumulus_primitives_utility::ParentAsUmp, - // ..and XCMP to communicate with the sibling chains. - XcmpQueue, + // Two routers - use UMP to communicate with the relay chain: + cumulus_primitives_utility::ParentAsUmp, + // ..and XCMP to communicate with the sibling chains. + XcmpQueue, ); impl pallet_xcm::Config for Runtime { - const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; - - type Origin = Origin; - type Call = Call; - type Event = Event; - type SendXcmOrigin = EnsureXcmOrigin; - type XcmRouter = XcmRouter; - type ExecuteXcmOrigin = EnsureXcmOrigin; - /// This means that no location will pass XcmExecuteFilter, so a dispatched `execute` message will be filtered. - /// This shouldn't be reachable since `LocalOriginToLocation = ();`, but let's be on the safe side. - type XcmExecuteFilter = Nothing; - type XcmExecutor = XcmExecutor; - type XcmTeleportFilter = Nothing; - type XcmReserveTransferFilter = Nothing; - type Weigher = FixedWeightBounds; - type LocationInverter = LocationInverter; - type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; + const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; + + type Origin = Origin; + type Call = Call; + type Event = Event; + type SendXcmOrigin = EnsureXcmOrigin; + type XcmRouter = XcmRouter; + type ExecuteXcmOrigin = EnsureXcmOrigin; + /// This means that no location will pass XcmExecuteFilter, so a dispatched `execute` message will be filtered. + /// This shouldn't be reachable since `LocalOriginToLocation = ();`, but let's be on the safe side. + type XcmExecuteFilter = Nothing; + type XcmExecutor = XcmExecutor; + type XcmTeleportFilter = Nothing; + type XcmReserveTransferFilter = Nothing; + type Weigher = FixedWeightBounds; + type LocationInverter = LocationInverter; + type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; } impl cumulus_pallet_xcm::Config for Runtime { - type Event = Event; - type XcmExecutor = XcmExecutor; + type Event = Event; + type XcmExecutor = XcmExecutor; } impl cumulus_pallet_xcmp_queue::Config for Runtime { - type Event = Event; - type XcmExecutor = XcmExecutor; - type ChannelInfo = ParachainSystem; - type VersionWrapper = PolkadotXcm; - type ExecuteOverweightOrigin = EnsureRoot; - type ControllerOrigin = EnsureRootOrMoreThanHalfCouncil; - type ControllerOriginConverter = XcmOriginToCallOrigin; - type WeightInfo = crate::weights::cumulus_pallet_xcmp_queue::SubstrateWeight; + type Event = Event; + type XcmExecutor = XcmExecutor; + type ChannelInfo = ParachainSystem; + type VersionWrapper = PolkadotXcm; + type ExecuteOverweightOrigin = EnsureRoot; + type ControllerOrigin = EnsureRootOrMoreThanHalfCouncil; + type ControllerOriginConverter = XcmOriginToCallOrigin; + type WeightInfo = crate::weights::cumulus_pallet_xcmp_queue::SubstrateWeight; } impl cumulus_pallet_dmp_queue::Config for Runtime { - type Event = Event; - type XcmExecutor = XcmExecutor; - type ExecuteOverweightOrigin = EnsureRoot; + type Event = Event; + type XcmExecutor = XcmExecutor; + type ExecuteOverweightOrigin = EnsureRoot; } // We wrap AssetId for XToken #[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)] pub enum CurrencyId { - MantaCurrency(AssetId), + MantaCurrency(AssetId), } pub struct CurrencyIdtoMultiLocation(sp_std::marker::PhantomData); impl sp_runtime::traits::Convert> - for CurrencyIdtoMultiLocation + for CurrencyIdtoMultiLocation where - AssetXConverter: xcm_executor::traits::Convert, + AssetXConverter: xcm_executor::traits::Convert, { - fn convert(currency: CurrencyId) -> Option { - match currency { - CurrencyId::MantaCurrency(asset_id) => match AssetXConverter::reverse_ref(&asset_id) { - Ok(location) => Some(location), - Err(_) => None, - }, - } - } + fn convert(currency: CurrencyId) -> Option { + match currency { + CurrencyId::MantaCurrency(asset_id) => match AssetXConverter::reverse_ref(&asset_id) { + Ok(location) => Some(location), + Err(_) => None, + }, + } + } } parameter_types! { - pub const BaseXcmWeight: Weight = 100_000_000; - pub const MaxAssetsForTransfer: usize = 1; + pub const BaseXcmWeight: Weight = 100_000_000; + pub const MaxAssetsForTransfer: usize = 1; } // The XCM message wrapper wrapper impl orml_xtokens::Config for Runtime { - type Event = Event; - type Balance = Balance; - type CurrencyId = CurrencyId; - type AccountIdToMultiLocation = AccountIdToMultiLocation; - type CurrencyIdConvert = - CurrencyIdtoMultiLocation>; - type XcmExecutor = XcmExecutor; - type SelfLocation = SelfReserve; - // Take note that this pallet does not have the typical configurable WeightInfo. - // It uses the Weigher configuration to calculate weights for the user callable extrinsics on this chain, - // as well as weights for execution on the destination chain. Both based on the composed xcm messages. - type Weigher = FixedWeightBounds; - type BaseXcmWeight = BaseXcmWeight; - type LocationInverter = LocationInverter; - type MaxAssetsForTransfer = MaxAssetsForTransfer; - type MinXcmFee = AssetManager; - type MultiLocationsFilter = AssetManager; - type ReserveProvider = orml_traits::location::AbsoluteReserveProvider; + type Event = Event; + type Balance = Balance; + type CurrencyId = CurrencyId; + type AccountIdToMultiLocation = AccountIdToMultiLocation; + type CurrencyIdConvert = + CurrencyIdtoMultiLocation>; + type XcmExecutor = XcmExecutor; + type SelfLocation = SelfReserve; + // Take note that this pallet does not have the typical configurable WeightInfo. + // It uses the Weigher configuration to calculate weights for the user callable extrinsics on this chain, + // as well as weights for execution on the destination chain. Both based on the composed xcm messages. + type Weigher = FixedWeightBounds; + type BaseXcmWeight = BaseXcmWeight; + type LocationInverter = LocationInverter; + type MaxAssetsForTransfer = MaxAssetsForTransfer; + type MinXcmFee = AssetManager; + type MultiLocationsFilter = AssetManager; + type ReserveProvider = orml_traits::location::AbsoluteReserveProvider; } diff --git a/runtime/manta/Cargo.toml b/runtime/manta/Cargo.toml index 98bc9386f..77e621b56 100644 --- a/runtime/manta/Cargo.toml +++ b/runtime/manta/Cargo.toml @@ -20,7 +20,7 @@ sp-block-builder = { git = 'https://github.com/paritytech/substrate.git', defaul sp-consensus-aura = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } sp-core = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } sp-inherents = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } -sp-io = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } +sp-io = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } sp-offchain = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } sp-runtime = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } sp-session = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } @@ -30,10 +30,10 @@ sp-version = { git = 'https://github.com/paritytech/substrate.git', default-feat # Substrate frames frame-benchmarking = { git = 'https://github.com/paritytech/substrate.git', default-features = false, optional = true, branch = "polkadot-v0.9.18" } -frame-system-benchmarking = { git = 'https://github.com/paritytech/substrate.git', default-features = false, optional = true, branch = "polkadot-v0.9.18" } frame-executive = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } frame-support = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } frame-system = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } +frame-system-benchmarking = { git = 'https://github.com/paritytech/substrate.git', default-features = false, optional = true, branch = "polkadot-v0.9.18" } frame-system-rpc-runtime-api = { git = 'https://github.com/paritytech/substrate.git', default-features = false, branch = "polkadot-v0.9.18" } frame-try-runtime = { git = "https://github.com/paritytech/substrate.git", default-features = false, optional = true, branch = "polkadot-v0.9.18" } @@ -53,25 +53,25 @@ pallet-utility = { git = 'https://github.com/paritytech/substrate.git', default- # Cumulus dependencies cumulus-pallet-aura-ext = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } +cumulus-pallet-dmp-queue = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } cumulus-pallet-parachain-system = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } +cumulus-pallet-session-benchmarking = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, optional = true, branch = "polkadot-v0.9.18" } +cumulus-pallet-xcm = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } +cumulus-pallet-xcmp-queue = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } cumulus-primitives-core = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } cumulus-primitives-timestamp = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } cumulus-primitives-utility = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } -cumulus-pallet-dmp-queue = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } -cumulus-pallet-session-benchmarking = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, optional = true, branch = "polkadot-v0.9.18" } -cumulus-pallet-xcmp-queue = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } -cumulus-pallet-xcm = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } pallet-collator-selection = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } parachain-info = { git = 'https://github.com/paritytech/cumulus.git', default-features = false, branch = "polkadot-v0.9.18" } # Polkadot dependencies +pallet-xcm = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } +polkadot-parachain = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } polkadot-primitives = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } polkadot-runtime-common = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } -polkadot-parachain = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } xcm = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } xcm-builder = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } xcm-executor = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } -pallet-xcm = { git = 'https://github.com/paritytech/polkadot.git', default-features = false, branch = "release-v0.9.18" } # Self dependencies manta-primitives = { path = '../../primitives', default-features = false } @@ -86,80 +86,80 @@ substrate-wasm-builder = { git = 'https://github.com/paritytech/substrate.git', [features] default = ['std'] -try-runtime = [ - 'frame-executive/try-runtime', - 'frame-try-runtime', -] runtime-benchmarks = [ - 'cumulus-pallet-session-benchmarking/runtime-benchmarks', - 'hex-literal', - 'sp-runtime/runtime-benchmarks', - 'xcm-builder/runtime-benchmarks', - 'frame-benchmarking', - 'frame-system-benchmarking', - 'frame-support/runtime-benchmarks', - 'frame-system/runtime-benchmarks', - 'pallet-balances/runtime-benchmarks', - 'pallet-multisig/runtime-benchmarks', - 'pallet-utility/runtime-benchmarks', - 'pallet-timestamp/runtime-benchmarks', - 'pallet-xcm/runtime-benchmarks', - 'pallet-collator-selection/runtime-benchmarks', - 'pallet-scheduler/runtime-benchmarks', - 'pallet-tx-pause/runtime-benchmarks', - 'pallet-preimage/runtime-benchmarks', + 'cumulus-pallet-session-benchmarking/runtime-benchmarks', + 'hex-literal', + 'sp-runtime/runtime-benchmarks', + 'xcm-builder/runtime-benchmarks', + 'frame-benchmarking', + 'frame-system-benchmarking', + 'frame-support/runtime-benchmarks', + 'frame-system/runtime-benchmarks', + 'pallet-balances/runtime-benchmarks', + 'pallet-multisig/runtime-benchmarks', + 'pallet-utility/runtime-benchmarks', + 'pallet-timestamp/runtime-benchmarks', + 'pallet-xcm/runtime-benchmarks', + 'pallet-collator-selection/runtime-benchmarks', + 'pallet-scheduler/runtime-benchmarks', + 'pallet-tx-pause/runtime-benchmarks', + 'pallet-preimage/runtime-benchmarks', +] +try-runtime = [ + 'frame-executive/try-runtime', + 'frame-try-runtime', ] # Set timing constants (e.g. session period) to faster versions to speed up testing. fast-runtime = [] std = [ - 'codec/std', - 'serde', - 'sp-consensus-aura/std', - 'pallet-aura/std', - 'sp-api/std', - 'sp-std/std', - 'sp-io/std', - 'sp-core/std', - 'sp-runtime/std', - 'sp-version/std', - 'sp-offchain/std', - 'sp-session/std', - 'sp-block-builder/std', - 'sp-transaction-pool/std', - 'sp-inherents/std', - 'frame-support/std', - 'frame-executive/std', - 'frame-system/std', - 'frame-system-rpc-runtime-api/std', - 'frame-try-runtime/std', - 'pallet-authorship/std', - 'pallet-balances/std', - 'pallet-preimage/std', - 'pallet-multisig/std', - 'pallet-utility/std', - 'pallet-transaction-payment-rpc-runtime-api/std', - 'pallet-timestamp/std', - 'pallet-scheduler/std', - 'pallet-session/std', - 'pallet-sudo/std', - 'pallet-xcm/std', - 'pallet-transaction-payment/std', - 'manta-primitives/std', - 'runtime-common/std', - 'parachain-info/std', - "cumulus-pallet-aura-ext/std", - 'cumulus-pallet-parachain-system/std', - 'cumulus-pallet-dmp-queue/std', - "cumulus-pallet-xcmp-queue/std", - "cumulus-pallet-xcm/std", - "cumulus-primitives-core/std", - "cumulus-primitives-timestamp/std", - "cumulus-primitives-utility/std", - 'xcm/std', - 'xcm-builder/std', - 'xcm-executor/std', - 'polkadot-runtime-common/std', - 'polkadot-primitives/std', - 'pallet-collator-selection/std', - 'pallet-tx-pause/std', + 'codec/std', + 'serde', + 'sp-consensus-aura/std', + 'pallet-aura/std', + 'sp-api/std', + 'sp-std/std', + 'sp-io/std', + 'sp-core/std', + 'sp-runtime/std', + 'sp-version/std', + 'sp-offchain/std', + 'sp-session/std', + 'sp-block-builder/std', + 'sp-transaction-pool/std', + 'sp-inherents/std', + 'frame-support/std', + 'frame-executive/std', + 'frame-system/std', + 'frame-system-rpc-runtime-api/std', + 'frame-try-runtime/std', + 'pallet-authorship/std', + 'pallet-balances/std', + 'pallet-preimage/std', + 'pallet-multisig/std', + 'pallet-utility/std', + 'pallet-transaction-payment-rpc-runtime-api/std', + 'pallet-timestamp/std', + 'pallet-scheduler/std', + 'pallet-session/std', + 'pallet-sudo/std', + 'pallet-xcm/std', + 'pallet-transaction-payment/std', + 'manta-primitives/std', + 'runtime-common/std', + 'parachain-info/std', + "cumulus-pallet-aura-ext/std", + 'cumulus-pallet-parachain-system/std', + 'cumulus-pallet-dmp-queue/std', + "cumulus-pallet-xcmp-queue/std", + "cumulus-pallet-xcm/std", + "cumulus-primitives-core/std", + "cumulus-primitives-timestamp/std", + "cumulus-primitives-utility/std", + 'xcm/std', + 'xcm-builder/std', + 'xcm-executor/std', + 'polkadot-runtime-common/std', + 'polkadot-primitives/std', + 'pallet-collator-selection/std', + 'pallet-tx-pause/std', ] diff --git a/runtime/manta/build.rs b/runtime/manta/build.rs index 46ffd8513..ebc6ed273 100644 --- a/runtime/manta/build.rs +++ b/runtime/manta/build.rs @@ -17,9 +17,9 @@ use substrate_wasm_builder::WasmBuilder; fn main() { - WasmBuilder::new() - .with_current_project() - .export_heap_base() - .import_memory() - .build() + WasmBuilder::new() + .with_current_project() + .export_heap_base() + .import_memory() + .build() } diff --git a/runtime/manta/src/currency.rs b/runtime/manta/src/currency.rs index 09c0a1371..8ec271cf7 100644 --- a/runtime/manta/src/currency.rs +++ b/runtime/manta/src/currency.rs @@ -23,5 +23,5 @@ pub const mMANTA: Balance = MANTA / 1_000; // 15 decimal, milli-MA pub const uMANTA: Balance = MANTA / 1_000_000; // 12 decimal, micro-MA pub const fn deposit(items: u32, bytes: u32) -> Balance { - items as Balance * 15 * mMANTA + (bytes as Balance) * 6 * mMANTA // TODO: revisit the storage cost here + items as Balance * 15 * mMANTA + (bytes as Balance) * 6 * mMANTA // TODO: revisit the storage cost here } diff --git a/runtime/manta/src/fee.rs b/runtime/manta/src/fee.rs index 00e9a5fef..9708202e2 100644 --- a/runtime/manta/src/fee.rs +++ b/runtime/manta/src/fee.rs @@ -16,8 +16,8 @@ use crate::currency; use frame_support::weights::{ - constants::ExtrinsicBaseWeight, WeightToFeeCoefficient, WeightToFeeCoefficients, - WeightToFeePolynomial, + constants::ExtrinsicBaseWeight, WeightToFeeCoefficient, WeightToFeeCoefficients, + WeightToFeePolynomial, }; use manta_primitives::types::Balance; use smallvec::smallvec; @@ -38,18 +38,18 @@ pub const TARGET_BLOCK_FULLNESS: Perbill = Perbill::from_percent(25); /// - Setting it to `1` will cause the literal `#[weight = x]` values to be charged. pub struct WeightToFee; impl WeightToFeePolynomial for WeightToFee { - type Balance = Balance; - fn polynomial() -> WeightToFeeCoefficients { - // in Polkadot, extrinsic base weight (smallest non-zero weight) is mapped to 1/10 CENT: - // in Manta Parachain, we map to 1/10 of that, or 1/100 CENT - // TODO, revisit here to figure out why use this polynomial - let p = currency::cMANTA; - let q = 100 * Balance::from(ExtrinsicBaseWeight::get()); - smallvec![WeightToFeeCoefficient { - degree: 1, - negative: false, - coeff_frac: Perbill::from_rational(p % q, q), - coeff_integer: p / q, - }] - } + type Balance = Balance; + fn polynomial() -> WeightToFeeCoefficients { + // in Polkadot, extrinsic base weight (smallest non-zero weight) is mapped to 1/10 CENT: + // in Manta Parachain, we map to 1/10 of that, or 1/100 CENT + // TODO, revisit here to figure out why use this polynomial + let p = currency::cMANTA; + let q = 100 * Balance::from(ExtrinsicBaseWeight::get()); + smallvec![WeightToFeeCoefficient { + degree: 1, + negative: false, + coeff_frac: Perbill::from_rational(p % q, q), + coeff_integer: p / q, + }] + } } diff --git a/runtime/manta/src/impls.rs b/runtime/manta/src/impls.rs index 3436f236b..08eee4b71 100644 --- a/runtime/manta/src/impls.rs +++ b/runtime/manta/src/impls.rs @@ -19,23 +19,23 @@ use frame_support::traits::{Currency, Imbalance, OnUnbalanced}; pub struct Author; impl OnUnbalanced for Author { - fn on_nonzero_unbalanced(amount: NegativeImbalance) { - if let Some(author) = Authorship::author() { - Balances::resolve_creating(&author, amount); - } - } + fn on_nonzero_unbalanced(amount: NegativeImbalance) { + if let Some(author) = Authorship::author() { + Balances::resolve_creating(&author, amount); + } + } } pub struct DealWithFees; impl OnUnbalanced for DealWithFees { - fn on_unbalanceds(mut fees_then_tips: impl Iterator) { - if let Some(fees) = fees_then_tips.next() { - let mut split = fees.ration(0, 100); - if let Some(tips) = fees_then_tips.next() { - // for tips, if any, 0% to treasury, 100% to block author (though this can be anything) - tips.ration_merge_into(0, 100, &mut split); - } - Author::on_unbalanced(split.1); - } - } + fn on_unbalanceds(mut fees_then_tips: impl Iterator) { + if let Some(fees) = fees_then_tips.next() { + let mut split = fees.ration(0, 100); + if let Some(tips) = fees_then_tips.next() { + // for tips, if any, 0% to treasury, 100% to block author (though this can be anything) + tips.ration_merge_into(0, 100, &mut split); + } + Author::on_unbalanced(split.1); + } + } } diff --git a/runtime/manta/src/lib.rs b/runtime/manta/src/lib.rs index 461619cae..b5406ad22 100644 --- a/runtime/manta/src/lib.rs +++ b/runtime/manta/src/lib.rs @@ -16,6 +16,7 @@ //! Manta Parachain runtime. +#![allow(clippy::identity_op)] // keep e.g. 1 * DAYS for legibility #![cfg_attr(not(feature = "std"), no_std)] #![recursion_limit = "256"] @@ -26,10 +27,10 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, - traits::{AccountIdLookup, BlakeTwo256, Block as BlockT}, - transaction_validity::{TransactionSource, TransactionValidity}, - ApplyExtrinsicResult, + create_runtime_str, generic, impl_opaque_keys, + traits::{AccountIdLookup, BlakeTwo256, Block as BlockT}, + transaction_validity::{TransactionSource, TransactionValidity}, + ApplyExtrinsicResult, }; use sp_std::prelude::*; @@ -38,21 +39,21 @@ use sp_version::NativeVersion; use sp_version::RuntimeVersion; use frame_support::{ - construct_runtime, match_type, parameter_types, - traits::{ConstU16, ConstU32, ConstU8, Contains, Currency, EnsureOneOf, Everything, Nothing}, - weights::{ - constants::{BlockExecutionWeight, ExtrinsicBaseWeight, WEIGHT_PER_SECOND}, - DispatchClass, IdentityFee, Weight, - }, - PalletId, + construct_runtime, match_type, parameter_types, + traits::{ConstU16, ConstU32, ConstU8, Contains, Currency, EnsureOneOf, Everything, Nothing}, + weights::{ + constants::{BlockExecutionWeight, ExtrinsicBaseWeight, WEIGHT_PER_SECOND}, + DispatchClass, IdentityFee, Weight, + }, + PalletId, }; use frame_system::{ - limits::{BlockLength, BlockWeights}, - EnsureRoot, + limits::{BlockLength, BlockWeights}, + EnsureRoot, }; use manta_primitives::{ - constants::{time::*, STAKING_PALLET_ID}, - types::{AccountId, AuraId, Balance, BlockNumber, Hash, Header, Index, Signature}, + constants::{time::*, STAKING_PALLET_ID}, + types::{AccountId, AuraId, Balance, BlockNumber, Hash, Header, Index, Signature}, }; use runtime_common::prod_or_fast; use sp_runtime::Perbill; @@ -66,11 +67,11 @@ use polkadot_parachain::primitives::Sibling; use polkadot_runtime_common::{BlockHashCount, RocksDbWeight, SlowAdjustingFeeUpdate}; use xcm::latest::prelude::*; use xcm_builder::{ - AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, - AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter, EnsureXcmOrigin, - FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset, ParentAsSuperuser, - ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, - SignedAccountId32AsNative, SovereignSignedViaLocation, TakeWeightCredit, UsingComponents, + AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, + AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter, EnsureXcmOrigin, + FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset, ParentAsSuperuser, + ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, + SignedAccountId32AsNative, SovereignSignedViaLocation, TakeWeightCredit, UsingComponents, }; use xcm_executor::{Config, XcmExecutor}; @@ -89,19 +90,19 @@ pub type NegativeImbalance = >::NegativeImbalanc /// of data like extrinsics, allowing for them to continue syncing the network through upgrades /// to even the core data structures. pub mod opaque { - use super::*; - pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic; - /// Opaque block header type. - pub type Header = generic::Header; - /// Opaque block type. - pub type Block = generic::Block; - /// Opaque block identifier type. - pub type BlockId = generic::BlockId; - impl_opaque_keys! { - pub struct SessionKeys { - pub aura: Aura, - } - } + use super::*; + pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic; + /// Opaque block header type. + pub type Header = generic::Header; + /// Opaque block type. + pub type Block = generic::Block; + /// Opaque block identifier type. + pub type BlockId = generic::BlockId; + impl_opaque_keys! { + pub struct SessionKeys { + pub aura: Aura, + } + } } // Weights used in the runtime. @@ -109,23 +110,23 @@ mod weights; #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("manta"), - impl_name: create_runtime_str!("manta"), - authoring_version: 1, - spec_version: 3200, - impl_version: 1, - apis: RUNTIME_API_VERSIONS, - transaction_version: 1, - state_version: 0, + spec_name: create_runtime_str!("manta"), + impl_name: create_runtime_str!("manta"), + authoring_version: 1, + spec_version: 3200, + impl_version: 1, + apis: RUNTIME_API_VERSIONS, + transaction_version: 1, + state_version: 0, }; /// The version information used to identify this runtime when compiled natively. #[cfg(feature = "std")] pub fn native_version() -> NativeVersion { - NativeVersion { - runtime_version: VERSION, - can_author_with: Default::default(), - } + NativeVersion { + runtime_version: VERSION, + can_author_with: Default::default(), + } } /// We assume that ~10% of the block weight is consumed by `on_initialize` handlers. This is @@ -139,226 +140,239 @@ pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(70); pub const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2; parameter_types! { - pub const Version: RuntimeVersion = VERSION; - pub RuntimeBlockLength: BlockLength = - BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); - pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder() - .base_block(BlockExecutionWeight::get()) - .for_class(DispatchClass::all(), |weights| { - weights.base_extrinsic = ExtrinsicBaseWeight::get(); - }) - .for_class(DispatchClass::Normal, |weights| { - weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); - }) - .for_class(DispatchClass::Operational, |weights| { - weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT); - // Operational transactions have some extra reserved space, so that they - // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`. - weights.reserved = Some( - MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT - ); - }) - .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) - .build_or_panic(); - pub const SS58Prefix: u8 = manta_primitives::constants::MANTA_SS58PREFIX; + pub const Version: RuntimeVersion = VERSION; + pub RuntimeBlockLength: BlockLength = + BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); + pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder() + .base_block(BlockExecutionWeight::get()) + .for_class(DispatchClass::all(), |weights| { + weights.base_extrinsic = ExtrinsicBaseWeight::get(); + }) + .for_class(DispatchClass::Normal, |weights| { + weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); + }) + .for_class(DispatchClass::Operational, |weights| { + weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT); + // Operational transactions have some extra reserved space, so that they + // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`. + weights.reserved = Some( + MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT + ); + }) + .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) + .build_or_panic(); + pub const SS58Prefix: u8 = manta_primitives::constants::MANTA_SS58PREFIX; } impl pallet_tx_pause::Config for Runtime { - type Event = Event; - type UpdateOrigin = EnsureRoot; - type WeightInfo = weights::pallet_tx_pause::SubstrateWeight; + type Event = Event; + type UpdateOrigin = EnsureRoot; + type WeightInfo = weights::pallet_tx_pause::SubstrateWeight; } // Don't allow permission-less asset creation. pub struct MantaFilter; impl Contains for MantaFilter { - fn contains(call: &Call) -> bool { - if matches!( - call, - Call::Timestamp(_) | Call::ParachainSystem(_) | Call::System(_) - ) { - // always allow core call - // pallet-timestamp and parachainSystem could not be filtered because they are used in communication between releychain and parachain. - return true; - } - - if pallet_tx_pause::PausedTransactionFilter::::contains(call) { - // no paused call - return false; - } - - match call { - Call::Authorship(_) | Call::Sudo(_) | Call::Multisig(_) | Call::Balances(_) => true, - // Sudo also cannot be filtered because it is used in runtime upgrade. - _ => false, - // Filter Utility to prevent users from setting keys and selecting collator for parachain (couldn't use now). - // Filter Session and CollatorSelection to prevent users from utility operation. - // Filter XCM pallet. - } - } + fn contains(call: &Call) -> bool { + if matches!( + call, + Call::Timestamp(_) | Call::ParachainSystem(_) | Call::System(_) + ) { + // always allow core call + // pallet-timestamp and parachainSystem could not be filtered because they are used in communication between releychain and parachain. + return true; + } + + if pallet_tx_pause::PausedTransactionFilter::::contains(call) { + // no paused call + return false; + } + + #[allow(clippy::match_like_matches_macro)] + // keep CallFilter with explicit true/false for documentation + match call { + // Explicitly DISALLOWED calls + // Filter Utility to prevent users from setting keys and selecting collator for parachain (couldn't use now). + Call::Utility(_) + // Filter Session and CollatorSelection to prevent users from utility operation. + | Call::Session(_) + | Call::CollatorSelection(_) + | Call::XcmpQueue(_) | Call::PolkadotXcm(_) | Call::DmpQueue(_) => false, // Filter XCM pallets + + // Explicitly ALLOWED calls + | Call::Authorship(_) + // Sudo also cannot be filtered because it is used in runtime upgrade. + | Call::Sudo(_) + | Call::Multisig(_) + | Call::Balances(_) => true, + + // DISALLOW anything else + _ => false, + } + } } // Configure FRAME pallets to include in runtime. impl frame_system::Config for Runtime { - type BaseCallFilter = MantaFilter; // Customized Filter for Manta - type BlockWeights = RuntimeBlockWeights; - type BlockLength = RuntimeBlockLength; - type AccountId = AccountId; - type Call = Call; - type Lookup = AccountIdLookup; - type Index = Index; - type BlockNumber = BlockNumber; - type Hash = Hash; - type Hashing = BlakeTwo256; - type Header = Header; - type Event = Event; - type Origin = Origin; - type BlockHashCount = BlockHashCount; - type DbWeight = RocksDbWeight; - type Version = Version; - type PalletInfo = PalletInfo; - type OnNewAccount = (); - type OnKilledAccount = (); - type AccountData = pallet_balances::AccountData; - type SystemWeightInfo = weights::frame_system::SubstrateWeight; - type SS58Prefix = SS58Prefix; - type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; - type MaxConsumers = frame_support::traits::ConstU32<16>; + type BaseCallFilter = MantaFilter; // Customized Filter for Manta + type BlockWeights = RuntimeBlockWeights; + type BlockLength = RuntimeBlockLength; + type AccountId = AccountId; + type Call = Call; + type Lookup = AccountIdLookup; + type Index = Index; + type BlockNumber = BlockNumber; + type Hash = Hash; + type Hashing = BlakeTwo256; + type Header = Header; + type Event = Event; + type Origin = Origin; + type BlockHashCount = BlockHashCount; + type DbWeight = RocksDbWeight; + type Version = Version; + type PalletInfo = PalletInfo; + type OnNewAccount = (); + type OnKilledAccount = (); + type AccountData = pallet_balances::AccountData; + type SystemWeightInfo = weights::frame_system::SubstrateWeight; + type SS58Prefix = SS58Prefix; + type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; + type MaxConsumers = frame_support::traits::ConstU32<16>; } parameter_types! { - pub const MinimumPeriod: u64 = SLOT_DURATION / 2; + pub const MinimumPeriod: u64 = SLOT_DURATION / 2; } impl pallet_timestamp::Config for Runtime { - /// A timestamp: milliseconds since the unix epoch. - type Moment = u64; - type OnTimestampSet = (); - type MinimumPeriod = MinimumPeriod; - type WeightInfo = weights::pallet_timestamp::SubstrateWeight; + /// A timestamp: milliseconds since the unix epoch. + type Moment = u64; + type OnTimestampSet = (); + type MinimumPeriod = MinimumPeriod; + type WeightInfo = weights::pallet_timestamp::SubstrateWeight; } impl pallet_authorship::Config for Runtime { - type FindAuthor = pallet_session::FindAccountFromAuthorIndex; - type UncleGenerations = ConstU32<0>; - type FilterUncle = (); - type EventHandler = (CollatorSelection,); + type FindAuthor = pallet_session::FindAccountFromAuthorIndex; + type UncleGenerations = ConstU32<0>; + type FilterUncle = (); + type EventHandler = (CollatorSelection,); } parameter_types! { - pub const NativeTokenExistentialDeposit: u128 = MANTA; + pub const NativeTokenExistentialDeposit: u128 = MANTA; } impl pallet_balances::Config for Runtime { - type MaxLocks = ConstU32<50>; - type MaxReserves = ConstU32<50>; - type ReserveIdentifier = [u8; 8]; - type Balance = Balance; - type DustRemoval = (); - type Event = Event; - type ExistentialDeposit = NativeTokenExistentialDeposit; - type AccountStore = frame_system::Pallet; - type WeightInfo = weights::pallet_balances::SubstrateWeight; + type MaxLocks = ConstU32<50>; + type MaxReserves = ConstU32<50>; + type ReserveIdentifier = [u8; 8]; + type Balance = Balance; + type DustRemoval = (); + type Event = Event; + type ExistentialDeposit = NativeTokenExistentialDeposit; + type AccountStore = frame_system::Pallet; + type WeightInfo = weights::pallet_balances::SubstrateWeight; } parameter_types! { - /// Relay Chain `TransactionByteFee` / 10 - pub const TransactionByteFee: Balance = mMANTA/10; + /// Relay Chain `TransactionByteFee` / 10 + pub const TransactionByteFee: Balance = mMANTA/10; } impl pallet_transaction_payment::Config for Runtime { - type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter; - type TransactionByteFee = TransactionByteFee; - type WeightToFee = WeightToFee; - type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; - type OperationalFeeMultiplier = ConstU8<5>; + type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter; + type TransactionByteFee = TransactionByteFee; + type WeightToFee = WeightToFee; + type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; + type OperationalFeeMultiplier = ConstU8<5>; } parameter_types! { - // One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes. - pub const DepositBase: Balance = deposit(1, 88); - // Additional storage item size of 32 bytes. - pub const DepositFactor: Balance = deposit(0, 32); + // One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes. + pub const DepositBase: Balance = deposit(1, 88); + // Additional storage item size of 32 bytes. + pub const DepositFactor: Balance = deposit(0, 32); } impl pallet_multisig::Config for Runtime { - type Event = Event; - type Call = Call; - type Currency = Balances; - type DepositBase = DepositBase; - type DepositFactor = DepositFactor; - type MaxSignatories = ConstU16<100>; - type WeightInfo = weights::pallet_multisig::SubstrateWeight; + type Event = Event; + type Call = Call; + type Currency = Balances; + type DepositBase = DepositBase; + type DepositFactor = DepositFactor; + type MaxSignatories = ConstU16<100>; + type WeightInfo = weights::pallet_multisig::SubstrateWeight; } impl pallet_utility::Config for Runtime { - type Event = Event; - type Call = Call; - type PalletsOrigin = OriginCaller; - type WeightInfo = pallet_utility::weights::SubstrateWeight; + type Event = Event; + type Call = Call; + type PalletsOrigin = OriginCaller; + type WeightInfo = pallet_utility::weights::SubstrateWeight; } impl pallet_sudo::Config for Runtime { - type Event = Event; - type Call = Call; + type Event = Event; + type Call = Call; } parameter_types! { - // The maximum weight that may be scheduled per block for any - // dispatchables of less priority than schedule::HARD_DEADLINE. - pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * - RuntimeBlockWeights::get().max_block; - pub const NoPreimagePostponement: Option = Some(10); + // The maximum weight that may be scheduled per block for any + // dispatchables of less priority than schedule::HARD_DEADLINE. + pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * + RuntimeBlockWeights::get().max_block; + pub const NoPreimagePostponement: Option = Some(10); } type ScheduleOrigin = EnsureRoot; impl pallet_scheduler::Config for Runtime { - type Event = Event; - type Origin = Origin; - type PalletsOrigin = OriginCaller; - type Call = Call; - type MaximumWeight = MaximumSchedulerWeight; - type ScheduleOrigin = ScheduleOrigin; - type MaxScheduledPerBlock = ConstU32<50>; // 50 scheduled calls at most in the queue for a single block. - type WeightInfo = weights::pallet_scheduler::SubstrateWeight; - type OriginPrivilegeCmp = frame_support::traits::EqualPrivilegeOnly; - type PreimageProvider = Preimage; - type NoPreimagePostponement = NoPreimagePostponement; + type Event = Event; + type Origin = Origin; + type PalletsOrigin = OriginCaller; + type Call = Call; + type MaximumWeight = MaximumSchedulerWeight; + type ScheduleOrigin = ScheduleOrigin; + type MaxScheduledPerBlock = ConstU32<50>; // 50 scheduled calls at most in the queue for a single block. + type WeightInfo = weights::pallet_scheduler::SubstrateWeight; + type OriginPrivilegeCmp = frame_support::traits::EqualPrivilegeOnly; + type PreimageProvider = Preimage; + type NoPreimagePostponement = NoPreimagePostponement; } parameter_types! { - // Our NORMAL_DISPATCH_RATIO is 70% of the 5MB limit - // So anything more than 3.5MB doesn't make sense here - pub const PreimageMaxSize: u32 = 3584 * 1024; - pub const PreimageBaseDeposit: Balance = 1 * MANTA; - // One cent: $10,000 / MB - pub const PreimageByteDeposit: Balance = 1 * cMANTA; + // Our NORMAL_DISPATCH_RATIO is 70% of the 5MB limit + // So anything more than 3.5MB doesn't make sense here + pub const PreimageMaxSize: u32 = 3584 * 1024; + pub const PreimageBaseDeposit: Balance = 1 * MANTA; + // One cent: $10,000 / MB + pub const PreimageByteDeposit: Balance = 1 * cMANTA; } impl pallet_preimage::Config for Runtime { - type WeightInfo = weights::pallet_preimage::SubstrateWeight; - type Event = Event; - type Currency = Balances; - type ManagerOrigin = EnsureRoot; - type MaxSize = PreimageMaxSize; - type BaseDeposit = PreimageBaseDeposit; - type ByteDeposit = PreimageByteDeposit; + type WeightInfo = weights::pallet_preimage::SubstrateWeight; + type Event = Event; + type Currency = Balances; + type ManagerOrigin = EnsureRoot; + type MaxSize = PreimageMaxSize; + type BaseDeposit = PreimageBaseDeposit; + type ByteDeposit = PreimageByteDeposit; } parameter_types! { - pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; - pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; + pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; + pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; } impl cumulus_pallet_parachain_system::Config for Runtime { - type Event = Event; - type OnSystemEvent = (); - type SelfParaId = parachain_info::Pallet; - type DmpMessageHandler = DmpQueue; - type ReservedDmpWeight = ReservedDmpWeight; - type OutboundXcmpMessageSource = XcmpQueue; - type XcmpMessageHandler = XcmpQueue; - type ReservedXcmpWeight = ReservedXcmpWeight; + type Event = Event; + type OnSystemEvent = (); + type SelfParaId = parachain_info::Pallet; + type DmpMessageHandler = DmpQueue; + type ReservedDmpWeight = ReservedDmpWeight; + type OutboundXcmpMessageSource = XcmpQueue; + type XcmpMessageHandler = XcmpQueue; + type ReservedXcmpWeight = ReservedXcmpWeight; } impl parachain_info::Config for Runtime {} @@ -366,113 +380,113 @@ impl parachain_info::Config for Runtime {} impl cumulus_pallet_aura_ext::Config for Runtime {} parameter_types! { - pub const DotLocation: MultiLocation = MultiLocation::parent(); - pub const RelayNetwork: NetworkId = NetworkId::Polkadot; - pub RelayChainOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into(); - pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into(); + pub const DotLocation: MultiLocation = MultiLocation::parent(); + pub const RelayNetwork: NetworkId = NetworkId::Polkadot; + pub RelayChainOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into(); + pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into(); } /// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used /// when determining ownership of accounts for asset transacting and when attempting to use XCM /// `Transact` in order to determine the dispatch Origin. pub type LocationToAccountId = ( - // The parent (Relay-chain) origin converts to the default `AccountId`. - ParentIsPreset, - // Sibling parachain origins convert to AccountId via the `ParaId::into`. - SiblingParachainConvertsVia, - // Straight up local `AccountId32` origins just alias directly to `AccountId`. - AccountId32Aliases, + // The parent (Relay-chain) origin converts to the default `AccountId`. + ParentIsPreset, + // Sibling parachain origins convert to AccountId via the `ParaId::into`. + SiblingParachainConvertsVia, + // Straight up local `AccountId32` origins just alias directly to `AccountId`. + AccountId32Aliases, ); /// Means for transacting assets on this chain. pub type LocalAssetTransactor = CurrencyAdapter< - // Use this currency: - Balances, - // Use this currency when it is a fungible asset matching the given location or name: - IsConcrete, - // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: - LocationToAccountId, - // Our chain's account ID type (we can't get away without mentioning it explicitly): - AccountId, - // We don't track any teleports. - (), + // Use this currency: + Balances, + // Use this currency when it is a fungible asset matching the given location or name: + IsConcrete, + // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: + LocationToAccountId, + // Our chain's account ID type (we can't get away without mentioning it explicitly): + AccountId, + // We don't track any teleports. + (), >; /// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance, /// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can /// biases the kind of local `Origin` it will become. pub type XcmOriginToTransactDispatchOrigin = ( - // Sovereign account converter; this attempts to derive an `AccountId` from the origin location - // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for - // foreign chains who want to have a local sovereign account on this chain which they control. - SovereignSignedViaLocation, - // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when - // recognised. - RelayChainAsNative, - // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when - // recognised. - SiblingParachainAsNative, - // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a - // transaction from the Root origin. - ParentAsSuperuser, - // Native signed account converter; this just converts an `AccountId32` origin into a normal - // `Origin::Signed` origin of the same 32-byte value. - SignedAccountId32AsNative, - // Xcm origins can be represented natively under the Xcm pallet's Xcm origin. - XcmPassthrough, + // Sovereign account converter; this attempts to derive an `AccountId` from the origin location + // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for + // foreign chains who want to have a local sovereign account on this chain which they control. + SovereignSignedViaLocation, + // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when + // recognised. + RelayChainAsNative, + // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when + // recognised. + SiblingParachainAsNative, + // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a + // transaction from the Root origin. + ParentAsSuperuser, + // Native signed account converter; this just converts an `AccountId32` origin into a normal + // `Origin::Signed` origin of the same 32-byte value. + SignedAccountId32AsNative, + // Xcm origins can be represented natively under the Xcm pallet's Xcm origin. + XcmPassthrough, ); parameter_types! { - // One XCM operation is 1_000_000_000 weight - almost certainly a conservative estimate. - // see https://github.com/paritytech/cumulus/blob/master/polkadot-parachains/statemine/src/lib.rs#L551 - pub UnitWeightCost: Weight = 1_000_000_000; - pub const MaxInstructions: u32 = 100; + // One XCM operation is 1_000_000_000 weight - almost certainly a conservative estimate. + // see https://github.com/paritytech/cumulus/blob/master/polkadot-parachains/statemine/src/lib.rs#L551 + pub UnitWeightCost: Weight = 1_000_000_000; + pub const MaxInstructions: u32 = 100; } match_type! { - pub type ParentOrParentsExecutivePlurality: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Executive, .. }) } - }; + pub type ParentOrParentsExecutivePlurality: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Executive, .. }) } + }; } match_type! { - pub type ParentOrSiblings: impl Contains = { - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(_) } - }; + pub type ParentOrSiblings: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(_) } + }; } pub type Barrier = ( - TakeWeightCredit, - AllowTopLevelPaidExecutionFrom, - // Parent and its exec plurality get free execution - AllowUnpaidExecutionFrom, - // Expected responses are OK. - // Allows `Pending` or `VersionNotifier` query responses. - AllowKnownQueryResponses, - // Subscriptions for version tracking are OK. - // Allows execution of `SubscribeVersion` or `UnsubscribeVersion` instruction, - // from parent or sibling chains. - AllowSubscriptionsFrom, + TakeWeightCredit, + AllowTopLevelPaidExecutionFrom, + // Parent and its exec plurality get free execution + AllowUnpaidExecutionFrom, + // Expected responses are OK. + // Allows `Pending` or `VersionNotifier` query responses. + AllowKnownQueryResponses, + // Subscriptions for version tracking are OK. + // Allows execution of `SubscribeVersion` or `UnsubscribeVersion` instruction, + // from parent or sibling chains. + AllowSubscriptionsFrom, ); pub struct XcmConfig; impl Config for XcmConfig { - type Call = Call; - type XcmSender = XcmRouter; - // How to withdraw and deposit an asset. - type AssetTransactor = LocalAssetTransactor; - type OriginConverter = XcmOriginToTransactDispatchOrigin; - type IsReserve = NativeAsset; - type IsTeleporter = NativeAsset; // <- should be enough to allow teleportation of DOT - type LocationInverter = LocationInverter; - type Barrier = Barrier; - type Weigher = FixedWeightBounds; - type Trader = UsingComponents, DotLocation, AccountId, Balances, ()>; - type ResponseHandler = PolkadotXcm; - type AssetTrap = PolkadotXcm; - type AssetClaims = PolkadotXcm; - type SubscriptionService = PolkadotXcm; + type Call = Call; + type XcmSender = XcmRouter; + // How to withdraw and deposit an asset. + type AssetTransactor = LocalAssetTransactor; + type OriginConverter = XcmOriginToTransactDispatchOrigin; + type IsReserve = NativeAsset; + type IsTeleporter = NativeAsset; // <- should be enough to allow teleportation of DOT + type LocationInverter = LocationInverter; + type Barrier = Barrier; + type Weigher = FixedWeightBounds; + type Trader = UsingComponents, DotLocation, AccountId, Balances, ()>; + type ResponseHandler = PolkadotXcm; + type AssetTrap = PolkadotXcm; + type AssetClaims = PolkadotXcm; + type SubscriptionService = PolkadotXcm; } /// No local origins on this chain are allowed to dispatch XCM sends/executions. @@ -481,149 +495,149 @@ pub type LocalOriginToLocation = (); /// The means for routing XCM messages which are not for local execution into the right message /// queues. pub type XcmRouter = ( - // Two routers - use UMP to communicate with the relay chain: - cumulus_primitives_utility::ParentAsUmp, - // ..and XCMP to communicate with the sibling chains. - XcmpQueue, + // Two routers - use UMP to communicate with the relay chain: + cumulus_primitives_utility::ParentAsUmp, + // ..and XCMP to communicate with the sibling chains. + XcmpQueue, ); impl pallet_xcm::Config for Runtime { - const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; - - type Origin = Origin; - type Call = Call; - type Event = Event; - type SendXcmOrigin = EnsureXcmOrigin; - type XcmRouter = XcmRouter; - type ExecuteXcmOrigin = EnsureXcmOrigin; - type XcmExecuteFilter = Nothing; - type XcmExecutor = XcmExecutor; - type XcmTeleportFilter = Everything; - type XcmReserveTransferFilter = Everything; - type Weigher = FixedWeightBounds; - type LocationInverter = LocationInverter; - type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; + const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; + + type Origin = Origin; + type Call = Call; + type Event = Event; + type SendXcmOrigin = EnsureXcmOrigin; + type XcmRouter = XcmRouter; + type ExecuteXcmOrigin = EnsureXcmOrigin; + type XcmExecuteFilter = Nothing; + type XcmExecutor = XcmExecutor; + type XcmTeleportFilter = Everything; + type XcmReserveTransferFilter = Everything; + type Weigher = FixedWeightBounds; + type LocationInverter = LocationInverter; + type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; } impl cumulus_pallet_xcm::Config for Runtime { - type Event = Event; - type XcmExecutor = XcmExecutor; + type Event = Event; + type XcmExecutor = XcmExecutor; } impl cumulus_pallet_xcmp_queue::Config for Runtime { - type Event = Event; - type XcmExecutor = XcmExecutor; - type ChannelInfo = ParachainSystem; - type VersionWrapper = PolkadotXcm; - type ExecuteOverweightOrigin = EnsureRoot; - type ControllerOrigin = CollatorSelectionUpdateOrigin; - type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin; - type WeightInfo = (); + type Event = Event; + type XcmExecutor = XcmExecutor; + type ChannelInfo = ParachainSystem; + type VersionWrapper = PolkadotXcm; + type ExecuteOverweightOrigin = EnsureRoot; + type ControllerOrigin = CollatorSelectionUpdateOrigin; + type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin; + type WeightInfo = (); } impl cumulus_pallet_dmp_queue::Config for Runtime { - type Event = Event; - type XcmExecutor = XcmExecutor; - type ExecuteOverweightOrigin = EnsureRoot; + type Event = Event; + type XcmExecutor = XcmExecutor; + type ExecuteOverweightOrigin = EnsureRoot; } parameter_types! { - pub Period: u32 = prod_or_fast!(7 * HOURS, 2 * MINUTES, "MANTA_PERIOD"); - pub const Offset: u32 = 0; + pub Period: u32 = prod_or_fast!(7 * HOURS, 2 * MINUTES, "MANTA_PERIOD"); + pub const Offset: u32 = 0; } impl pallet_session::Config for Runtime { - type Event = Event; - type ValidatorId = ::AccountId; - // we don't have stash and controller, thus we don't need the convert as well. - type ValidatorIdOf = pallet_collator_selection::IdentityCollator; - type ShouldEndSession = pallet_session::PeriodicSessions; - type NextSessionRotation = pallet_session::PeriodicSessions; - type SessionManager = CollatorSelection; - // Essentially just Aura, but lets be pedantic. - type SessionHandler = - ::KeyTypeIdProviders; - type Keys = opaque::SessionKeys; - type WeightInfo = weights::pallet_session::SubstrateWeight; + type Event = Event; + type ValidatorId = ::AccountId; + // we don't have stash and controller, thus we don't need the convert as well. + type ValidatorIdOf = pallet_collator_selection::IdentityCollator; + type ShouldEndSession = pallet_session::PeriodicSessions; + type NextSessionRotation = pallet_session::PeriodicSessions; + type SessionManager = CollatorSelection; + // Essentially just Aura, but lets be pedantic. + type SessionHandler = + ::KeyTypeIdProviders; + type Keys = opaque::SessionKeys; + type WeightInfo = weights::pallet_session::SubstrateWeight; } impl pallet_aura::Config for Runtime { - type AuthorityId = AuraId; - type DisabledValidators = (); - type MaxAuthorities = ConstU32<100_000>; + type AuthorityId = AuraId; + type DisabledValidators = (); + type MaxAuthorities = ConstU32<100_000>; } parameter_types! { - // Pallet account for record rewards and give rewards to collator. - pub const PotId: PalletId = STAKING_PALLET_ID; + // Pallet account for record rewards and give rewards to collator. + pub const PotId: PalletId = STAKING_PALLET_ID; } parameter_types! { - pub const ExecutiveBody: BodyId = BodyId::Executive; + pub const ExecutiveBody: BodyId = BodyId::Executive; } /// We allow root and the Relay Chain council to execute privileged collator selection operations. pub type CollatorSelectionUpdateOrigin = - EnsureOneOf, EnsureXcm>>; + EnsureOneOf, EnsureXcm>>; impl pallet_collator_selection::Config for Runtime { - type Event = Event; - type Currency = Balances; - type UpdateOrigin = CollatorSelectionUpdateOrigin; - type PotId = PotId; - type MaxCandidates = ConstU32<50>; // 50 candidates at most - type MinCandidates = ConstU32<3>; // 3 candidates at least - type MaxInvulnerables = ConstU32<5>; // 5 invulnerables at most - type KickThreshold = Period; // should be a multiple of session or things will get inconsistent - type ValidatorId = ::AccountId; - type ValidatorIdOf = pallet_collator_selection::IdentityCollator; - type ValidatorRegistration = Session; - type WeightInfo = pallet_collator_selection::weights::SubstrateWeight; + type Event = Event; + type Currency = Balances; + type UpdateOrigin = CollatorSelectionUpdateOrigin; + type PotId = PotId; + type MaxCandidates = ConstU32<50>; // 50 candidates at most + type MinCandidates = ConstU32<3>; // 3 candidates at least + type MaxInvulnerables = ConstU32<5>; // 5 invulnerables at most + type KickThreshold = Period; // should be a multiple of session or things will get inconsistent + type ValidatorId = ::AccountId; + type ValidatorIdOf = pallet_collator_selection::IdentityCollator; + type ValidatorRegistration = Session; + type WeightInfo = pallet_collator_selection::weights::SubstrateWeight; } // Create the runtime by composing the FRAME pallets that were previously configured. construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = opaque::Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - // System support stuff. - System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, - ParachainSystem: cumulus_pallet_parachain_system::{ - Pallet, Call, Config, Storage, Inherent, Event, ValidateUnsigned, - } = 1, - Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 2, - ParachainInfo: parachain_info::{Pallet, Storage, Config} = 3, - TransactionPause: pallet_tx_pause::{Pallet, Call, Storage, Event} = 9, - // Monetary stuff. - Balances: pallet_balances::{Pallet, Call, Storage, Config, Event} = 10, - TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 11, - - // Collator support. the order of these 5 are important and shall not change. - Authorship: pallet_authorship::{Pallet, Call, Storage} = 20, - CollatorSelection: pallet_collator_selection::{Pallet, Call, Storage, Event, Config} = 21, - Session: pallet_session::{Pallet, Call, Storage, Event, Config} = 22, - Aura: pallet_aura::{Pallet, Storage, Config} = 23, - AuraExt: cumulus_pallet_aura_ext::{Pallet, Storage, Config} = 24, - - // Preimage registrar. - Preimage: pallet_preimage::{Pallet, Call, Storage, Event} = 28, - // System scheduler - Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event} = 29, - - // XCM helpers. - XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event} = 30, - PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event, Origin, Config} = 31, - CumulusXcm: cumulus_pallet_xcm::{Pallet, Event, Origin} = 32, - DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event} = 33, - - // Handy utilities. - Utility: pallet_utility::{Pallet, Call, Event} = 40, - Multisig: pallet_multisig::{Pallet, Call, Storage, Event} = 41, - // Temporary - Sudo: pallet_sudo::{Pallet, Call, Config, Storage, Event} = 42, - } + pub enum Runtime where + Block = Block, + NodeBlock = opaque::Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + // System support stuff. + System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, + ParachainSystem: cumulus_pallet_parachain_system::{ + Pallet, Call, Config, Storage, Inherent, Event, ValidateUnsigned, + } = 1, + Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 2, + ParachainInfo: parachain_info::{Pallet, Storage, Config} = 3, + TransactionPause: pallet_tx_pause::{Pallet, Call, Storage, Event} = 9, + // Monetary stuff. + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event} = 10, + TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 11, + + // Collator support. the order of these 5 are important and shall not change. + Authorship: pallet_authorship::{Pallet, Call, Storage} = 20, + CollatorSelection: pallet_collator_selection::{Pallet, Call, Storage, Event, Config} = 21, + Session: pallet_session::{Pallet, Call, Storage, Event, Config} = 22, + Aura: pallet_aura::{Pallet, Storage, Config} = 23, + AuraExt: cumulus_pallet_aura_ext::{Pallet, Storage, Config} = 24, + + // Preimage registrar. + Preimage: pallet_preimage::{Pallet, Call, Storage, Event} = 28, + // System scheduler + Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event} = 29, + + // XCM helpers. + XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event} = 30, + PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event, Origin, Config} = 31, + CumulusXcm: cumulus_pallet_xcm::{Pallet, Event, Origin} = 32, + DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event} = 33, + + // Handy utilities. + Utility: pallet_utility::{Pallet, Call, Event} = 40, + Multisig: pallet_multisig::{Pallet, Call, Storage, Event} = 41, + // Temporary + Sudo: pallet_sudo::{Pallet, Call, Config, Storage, Event} = 42, + } ); /// The address format for describing accounts. @@ -636,13 +650,13 @@ pub type SignedBlock = generic::SignedBlock; pub type BlockId = generic::BlockId; /// The SignedExtension to the basic transaction logic. pub type SignedExtra = ( - frame_system::CheckSpecVersion, - frame_system::CheckTxVersion, - frame_system::CheckGenesis, - frame_system::CheckEra, - frame_system::CheckNonce, - frame_system::CheckWeight, - pallet_transaction_payment::ChargeTransactionPayment, + frame_system::CheckSpecVersion, + frame_system::CheckTxVersion, + frame_system::CheckGenesis, + frame_system::CheckEra, + frame_system::CheckNonce, + frame_system::CheckWeight, + pallet_transaction_payment::ChargeTransactionPayment, ); /// Unchecked extrinsic type as expected by this runtime. pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; @@ -650,11 +664,11 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; /// Executive: handles dispatch to the various modules. pub type Executive = frame_executive::Executive< - Runtime, - Block, - frame_system::ChainContext, - Runtime, - AllPalletsReversedWithSystemFirst, + Runtime, + Block, + frame_system::ChainContext, + Runtime, + AllPalletsReversedWithSystemFirst, >; #[cfg(feature = "runtime-benchmarks")] @@ -663,216 +677,216 @@ extern crate frame_benchmarking; #[cfg(feature = "runtime-benchmarks")] mod benches { - frame_benchmarking::define_benchmarks!( - // Substrate pallets - [pallet_balances, Balances] - [pallet_multisig, Multisig] - [frame_system, SystemBench::] - [pallet_timestamp, Timestamp] - [pallet_utility, Utility] - [pallet_preimage, Preimage] - [pallet_scheduler, Scheduler] - [pallet_session, SessionBench::] - [pallet_collator_selection, CollatorSelection] - // Manta pallets - [pallet_tx_pause, TransactionPause] - ); + frame_benchmarking::define_benchmarks!( + // Substrate pallets + [pallet_balances, Balances] + [pallet_multisig, Multisig] + [frame_system, SystemBench::] + [pallet_timestamp, Timestamp] + [pallet_utility, Utility] + [pallet_preimage, Preimage] + [pallet_scheduler, Scheduler] + [pallet_session, SessionBench::] + [pallet_collator_selection, CollatorSelection] + // Manta pallets + [pallet_tx_pause, TransactionPause] + ); } impl_runtime_apis! { - impl sp_consensus_aura::AuraApi for Runtime { - fn slot_duration() -> sp_consensus_aura::SlotDuration { - sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) - } - - fn authorities() -> Vec { - Aura::authorities().into_inner() - } - } - - impl sp_api::Core for Runtime { - fn version() -> RuntimeVersion { - VERSION - } - - fn execute_block(block: Block) { - Executive::execute_block(block) - } - - fn initialize_block(header: &::Header) { - Executive::initialize_block(header) - } - } - - impl sp_api::Metadata for Runtime { - fn metadata() -> OpaqueMetadata { - OpaqueMetadata::new(Runtime::metadata().into()) - } - } - - impl sp_block_builder::BlockBuilder for Runtime { - fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { - Executive::apply_extrinsic(extrinsic) - } - - fn finalize_block() -> ::Header { - Executive::finalize_block() - } - - fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { - data.create_extrinsics() - } - - fn check_inherents( - block: Block, - data: sp_inherents::InherentData, - ) -> sp_inherents::CheckInherentsResult { - data.check_extrinsics(&block) - } - } - - impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { - fn validate_transaction( - source: TransactionSource, - tx: ::Extrinsic, - block_hash: ::Hash, - ) -> TransactionValidity { - Executive::validate_transaction(source, tx, block_hash) - } - } - - impl sp_offchain::OffchainWorkerApi for Runtime { - fn offchain_worker(header: &::Header) { - Executive::offchain_worker(header) - } - } - - impl sp_session::SessionKeys for Runtime { - fn generate_session_keys(seed: Option>) -> Vec { - opaque::SessionKeys::generate(seed) - } - - fn decode_session_keys( - encoded: Vec, - ) -> Option, KeyTypeId)>> { - opaque::SessionKeys::decode_into_raw_public_keys(&encoded) - } - } - - impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { - fn account_nonce(account: AccountId) -> Index { - System::account_nonce(account) - } - } - - impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { - fn query_info( - uxt: ::Extrinsic, - len: u32, - ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { - TransactionPayment::query_info(uxt, len) - } - fn query_fee_details( - uxt: ::Extrinsic, - len: u32, - ) -> pallet_transaction_payment::FeeDetails { - TransactionPayment::query_fee_details(uxt, len) - } - } - - impl cumulus_primitives_core::CollectCollationInfo for Runtime { - fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { - ParachainSystem::collect_collation_info(header) - } - } - - #[cfg(feature = "try-runtime")] - impl frame_try_runtime::TryRuntime for Runtime { - fn on_runtime_upgrade() -> (Weight, Weight) { - let weight = Executive::try_runtime_upgrade().unwrap(); - (weight, RuntimeBlockWeights::get().max_block) - } - - fn execute_block_no_check(block: Block) -> Weight { - Executive::execute_block_no_check(block) - } - } - - #[cfg(feature = "runtime-benchmarks")] - impl frame_benchmarking::Benchmark for Runtime { - fn benchmark_metadata(extra: bool) -> ( - Vec, - Vec, - ) { - use frame_benchmarking::{Benchmarking, BenchmarkList}; - use frame_support::traits::StorageInfoTrait; - use frame_system_benchmarking::Pallet as SystemBench; - use cumulus_pallet_session_benchmarking::Pallet as SessionBench; - - let mut list = Vec::::new(); - list_benchmarks!(list, extra); - - let storage_info = AllPalletsReversedWithSystemFirst::storage_info(); - (list, storage_info) - } - - fn dispatch_benchmark( - config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { - use frame_benchmarking::{Benchmarking, BenchmarkBatch, TrackedStorageKey}; - - use frame_system_benchmarking::Pallet as SystemBench; - impl frame_system_benchmarking::Config for Runtime {} - - use cumulus_pallet_session_benchmarking::Pallet as SessionBench; - impl cumulus_pallet_session_benchmarking::Config for Runtime {} - - let whitelist: Vec = vec![ - // Block Number - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(), - // Total Issuance - hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(), - // Execution Phase - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(), - // Event Count - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(), - // System Events - hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(), - ]; - - let mut batches = Vec::::new(); - let params = (&config, &whitelist); - - add_benchmarks!(params, batches); - - if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } - Ok(batches) - } - } + impl sp_consensus_aura::AuraApi for Runtime { + fn slot_duration() -> sp_consensus_aura::SlotDuration { + sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) + } + + fn authorities() -> Vec { + Aura::authorities().into_inner() + } + } + + impl sp_api::Core for Runtime { + fn version() -> RuntimeVersion { + VERSION + } + + fn execute_block(block: Block) { + Executive::execute_block(block) + } + + fn initialize_block(header: &::Header) { + Executive::initialize_block(header) + } + } + + impl sp_api::Metadata for Runtime { + fn metadata() -> OpaqueMetadata { + OpaqueMetadata::new(Runtime::metadata().into()) + } + } + + impl sp_block_builder::BlockBuilder for Runtime { + fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { + Executive::apply_extrinsic(extrinsic) + } + + fn finalize_block() -> ::Header { + Executive::finalize_block() + } + + fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { + data.create_extrinsics() + } + + fn check_inherents( + block: Block, + data: sp_inherents::InherentData, + ) -> sp_inherents::CheckInherentsResult { + data.check_extrinsics(&block) + } + } + + impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { + fn validate_transaction( + source: TransactionSource, + tx: ::Extrinsic, + block_hash: ::Hash, + ) -> TransactionValidity { + Executive::validate_transaction(source, tx, block_hash) + } + } + + impl sp_offchain::OffchainWorkerApi for Runtime { + fn offchain_worker(header: &::Header) { + Executive::offchain_worker(header) + } + } + + impl sp_session::SessionKeys for Runtime { + fn generate_session_keys(seed: Option>) -> Vec { + opaque::SessionKeys::generate(seed) + } + + fn decode_session_keys( + encoded: Vec, + ) -> Option, KeyTypeId)>> { + opaque::SessionKeys::decode_into_raw_public_keys(&encoded) + } + } + + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Index { + System::account_nonce(account) + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { + fn query_info( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { + TransactionPayment::query_info(uxt, len) + } + fn query_fee_details( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_fee_details(uxt, len) + } + } + + impl cumulus_primitives_core::CollectCollationInfo for Runtime { + fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { + ParachainSystem::collect_collation_info(header) + } + } + + #[cfg(feature = "try-runtime")] + impl frame_try_runtime::TryRuntime for Runtime { + fn on_runtime_upgrade() -> (Weight, Weight) { + let weight = Executive::try_runtime_upgrade().unwrap(); + (weight, RuntimeBlockWeights::get().max_block) + } + + fn execute_block_no_check(block: Block) -> Weight { + Executive::execute_block_no_check(block) + } + } + + #[cfg(feature = "runtime-benchmarks")] + impl frame_benchmarking::Benchmark for Runtime { + fn benchmark_metadata(extra: bool) -> ( + Vec, + Vec, + ) { + use frame_benchmarking::{Benchmarking, BenchmarkList}; + use frame_support::traits::StorageInfoTrait; + use frame_system_benchmarking::Pallet as SystemBench; + use cumulus_pallet_session_benchmarking::Pallet as SessionBench; + + let mut list = Vec::::new(); + list_benchmarks!(list, extra); + + let storage_info = AllPalletsReversedWithSystemFirst::storage_info(); + (list, storage_info) + } + + fn dispatch_benchmark( + config: frame_benchmarking::BenchmarkConfig + ) -> Result, sp_runtime::RuntimeString> { + use frame_benchmarking::{Benchmarking, BenchmarkBatch, TrackedStorageKey}; + + use frame_system_benchmarking::Pallet as SystemBench; + impl frame_system_benchmarking::Config for Runtime {} + + use cumulus_pallet_session_benchmarking::Pallet as SessionBench; + impl cumulus_pallet_session_benchmarking::Config for Runtime {} + + let whitelist: Vec = vec![ + // Block Number + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(), + // Total Issuance + hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(), + // Execution Phase + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(), + // Event Count + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(), + // System Events + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(), + ]; + + let mut batches = Vec::::new(); + let params = (&config, &whitelist); + + add_benchmarks!(params, batches); + + if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } + Ok(batches) + } + } } struct CheckInherents; impl cumulus_pallet_parachain_system::CheckInherents for CheckInherents { - fn check_inherents( - block: &Block, - relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof, - ) -> sp_inherents::CheckInherentsResult { - let relay_chain_slot = relay_state_proof - .read_slot() - .expect("Could not read the relay chain slot from the proof"); - let inherent_data = - cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration( - relay_chain_slot, - sp_std::time::Duration::from_secs(6), - ) - .create_inherent_data() - .expect("Could not create the timestamp inherent data"); - inherent_data.check_extrinsics(block) - } + fn check_inherents( + block: &Block, + relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof, + ) -> sp_inherents::CheckInherentsResult { + let relay_chain_slot = relay_state_proof + .read_slot() + .expect("Could not read the relay chain slot from the proof"); + let inherent_data = + cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration( + relay_chain_slot, + sp_std::time::Duration::from_secs(6), + ) + .create_inherent_data() + .expect("Could not create the timestamp inherent data"); + inherent_data.check_extrinsics(block) + } } cumulus_pallet_parachain_system::register_validate_block! { - Runtime = Runtime, - BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::, - CheckInherents = CheckInherents, + Runtime = Runtime, + BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::, + CheckInherents = CheckInherents, } diff --git a/runtime/manta/src/weights/frame_system.rs b/runtime/manta/src/weights/frame_system.rs index 9d6dcf454..6ac7b0937 100644 --- a/runtime/manta/src/weights/frame_system.rs +++ b/runtime/manta/src/weights/frame_system.rs @@ -43,95 +43,95 @@ use sp_std::marker::PhantomData; /// Weight functions needed for frame_system. pub trait WeightInfo { - fn remark(b: u32, ) -> Weight; - fn remark_with_event(b: u32, ) -> Weight; - fn set_heap_pages() -> Weight; - fn set_storage(i: u32, ) -> Weight; - fn kill_storage(i: u32, ) -> Weight; - fn kill_prefix(p: u32, ) -> Weight; + fn remark(b: u32, ) -> Weight; + fn remark_with_event(b: u32, ) -> Weight; + fn set_heap_pages() -> Weight; + fn set_storage(i: u32, ) -> Weight; + fn kill_storage(i: u32, ) -> Weight; + fn kill_prefix(p: u32, ) -> Weight; } /// Weights for frame_system using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl frame_system::WeightInfo for SubstrateWeight { - fn remark(b: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) - } - fn remark_with_event(b: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - } - // Storage: System Digest (r:1 w:1) - // Storage: unknown [0x3a686561707061676573] (r:0 w:1) - fn set_heap_pages() -> Weight { - (3_343_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Skipped Metadata (r:0 w:0) - fn set_storage(i: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((596_000 as Weight).saturating_mul(i as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) - } - // Storage: Skipped Metadata (r:0 w:0) - fn kill_storage(i: u32, ) -> Weight { - (231_000 as Weight) - // Standard Error: 1_000 - .saturating_add((429_000 as Weight).saturating_mul(i as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) - } - // Storage: Skipped Metadata (r:0 w:0) - fn kill_prefix(p: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 1_000 - .saturating_add((959_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) - } + fn remark(b: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) + } + fn remark_with_event(b: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + } + // Storage: System Digest (r:1 w:1) + // Storage: unknown [0x3a686561707061676573] (r:0 w:1) + fn set_heap_pages() -> Weight { + (3_343_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Skipped Metadata (r:0 w:0) + fn set_storage(i: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((596_000 as Weight).saturating_mul(i as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) + } + // Storage: Skipped Metadata (r:0 w:0) + fn kill_storage(i: u32, ) -> Weight { + (231_000 as Weight) + // Standard Error: 1_000 + .saturating_add((429_000 as Weight).saturating_mul(i as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) + } + // Storage: Skipped Metadata (r:0 w:0) + fn kill_prefix(p: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 1_000 + .saturating_add((959_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) + } } // For backwards compatibility and tests impl WeightInfo for () { - fn remark(b: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) - } - fn remark_with_event(b: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - } - // Storage: System Digest (r:1 w:1) - // Storage: unknown [0x3a686561707061676573] (r:0 w:1) - fn set_heap_pages() -> Weight { - (3_343_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Skipped Metadata (r:0 w:0) - fn set_storage(i: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((596_000 as Weight).saturating_mul(i as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) - } - // Storage: Skipped Metadata (r:0 w:0) - fn kill_storage(i: u32, ) -> Weight { - (231_000 as Weight) - // Standard Error: 1_000 - .saturating_add((429_000 as Weight).saturating_mul(i as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) - } - // Storage: Skipped Metadata (r:0 w:0) - fn kill_prefix(p: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 1_000 - .saturating_add((959_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) - } + fn remark(b: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) + } + fn remark_with_event(b: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + } + // Storage: System Digest (r:1 w:1) + // Storage: unknown [0x3a686561707061676573] (r:0 w:1) + fn set_heap_pages() -> Weight { + (3_343_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Skipped Metadata (r:0 w:0) + fn set_storage(i: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((596_000 as Weight).saturating_mul(i as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) + } + // Storage: Skipped Metadata (r:0 w:0) + fn kill_storage(i: u32, ) -> Weight { + (231_000 as Weight) + // Standard Error: 1_000 + .saturating_add((429_000 as Weight).saturating_mul(i as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) + } + // Storage: Skipped Metadata (r:0 w:0) + fn kill_prefix(p: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 1_000 + .saturating_add((959_000 as Weight).saturating_mul(p as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) + } } diff --git a/runtime/manta/src/weights/pallet_balances.rs b/runtime/manta/src/weights/pallet_balances.rs index 29054a797..44aeb56fa 100644 --- a/runtime/manta/src/weights/pallet_balances.rs +++ b/runtime/manta/src/weights/pallet_balances.rs @@ -43,104 +43,104 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_balances. pub trait WeightInfo { - fn transfer() -> Weight; - fn transfer_keep_alive() -> Weight; - fn set_balance_creating() -> Weight; - fn set_balance_killing() -> Weight; - fn force_transfer() -> Weight; - fn transfer_all() -> Weight; - fn force_unreserve() -> Weight; + fn transfer() -> Weight; + fn transfer_keep_alive() -> Weight; + fn set_balance_creating() -> Weight; + fn set_balance_killing() -> Weight; + fn force_transfer() -> Weight; + fn transfer_all() -> Weight; + fn force_unreserve() -> Weight; } /// Weights for pallet_balances using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_balances::WeightInfo for SubstrateWeight { - // Storage: System Account (r:1 w:1) - fn transfer() -> Weight { - (47_987_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn transfer_keep_alive() -> Weight { - (35_651_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn set_balance_creating() -> Weight { - (21_345_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn set_balance_killing() -> Weight { - (25_736_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:2 w:2) - fn force_transfer() -> Weight { - (46_545_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn transfer_all() -> Weight { - (43_259_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn force_unreserve() -> Weight { - (19_026_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } + // Storage: System Account (r:1 w:1) + fn transfer() -> Weight { + (47_987_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn transfer_keep_alive() -> Weight { + (35_651_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn set_balance_creating() -> Weight { + (21_345_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn set_balance_killing() -> Weight { + (25_736_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:2 w:2) + fn force_transfer() -> Weight { + (46_545_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn transfer_all() -> Weight { + (43_259_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn force_unreserve() -> Weight { + (19_026_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: System Account (r:1 w:1) - fn transfer() -> Weight { - (47_987_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn transfer_keep_alive() -> Weight { - (35_651_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn set_balance_creating() -> Weight { - (21_345_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn set_balance_killing() -> Weight { - (25_736_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:2 w:2) - fn force_transfer() -> Weight { - (46_545_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn transfer_all() -> Weight { - (43_259_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: System Account (r:1 w:1) - fn force_unreserve() -> Weight { - (19_026_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } + // Storage: System Account (r:1 w:1) + fn transfer() -> Weight { + (47_987_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn transfer_keep_alive() -> Weight { + (35_651_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn set_balance_creating() -> Weight { + (21_345_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn set_balance_killing() -> Weight { + (25_736_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:2 w:2) + fn force_transfer() -> Weight { + (46_545_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn transfer_all() -> Weight { + (43_259_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:1) + fn force_unreserve() -> Weight { + (19_026_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } } diff --git a/runtime/manta/src/weights/pallet_multisig.rs b/runtime/manta/src/weights/pallet_multisig.rs index 17d943141..2a2bda271 100644 --- a/runtime/manta/src/weights/pallet_multisig.rs +++ b/runtime/manta/src/weights/pallet_multisig.rs @@ -43,219 +43,219 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_multisig. pub trait WeightInfo { - fn as_multi_threshold_1(z: u32, ) -> Weight; - fn as_multi_create(s: u32, z: u32, ) -> Weight; - fn as_multi_create_store(s: u32, z: u32, ) -> Weight; - fn as_multi_approve(s: u32, z: u32, ) -> Weight; - fn as_multi_approve_store(s: u32, z: u32, ) -> Weight; - fn as_multi_complete(s: u32, z: u32, ) -> Weight; - fn approve_as_multi_create(s: u32, ) -> Weight; - fn approve_as_multi_approve(s: u32, ) -> Weight; - fn approve_as_multi_complete(s: u32, ) -> Weight; - fn cancel_as_multi(s: u32, ) -> Weight; + fn as_multi_threshold_1(z: u32, ) -> Weight; + fn as_multi_create(s: u32, z: u32, ) -> Weight; + fn as_multi_create_store(s: u32, z: u32, ) -> Weight; + fn as_multi_approve(s: u32, z: u32, ) -> Weight; + fn as_multi_approve_store(s: u32, z: u32, ) -> Weight; + fn as_multi_complete(s: u32, z: u32, ) -> Weight; + fn approve_as_multi_create(s: u32, ) -> Weight; + fn approve_as_multi_approve(s: u32, ) -> Weight; + fn approve_as_multi_complete(s: u32, ) -> Weight; + fn cancel_as_multi(s: u32, ) -> Weight; } /// Weights for pallet_multisig using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_multisig::WeightInfo for SubstrateWeight { - fn as_multi_threshold_1(z: u32, ) -> Weight { - (24_003_000 as Weight) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) - fn as_multi_create(s: u32, z: u32, ) -> Weight { - (39_194_000 as Weight) - // Standard Error: 1_000 - .saturating_add((190_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) - fn as_multi_create_store(s: u32, z: u32, ) -> Weight { - (45_057_000 as Weight) - // Standard Error: 1_000 - .saturating_add((188_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - fn as_multi_approve(s: u32, z: u32, ) -> Weight { - (26_698_000 as Weight) - // Standard Error: 1_000 - .saturating_add((184_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - fn as_multi_approve_store(s: u32, z: u32, ) -> Weight { - (44_401_000 as Weight) - // Standard Error: 1_000 - .saturating_add((196_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn as_multi_complete(s: u32, z: u32, ) -> Weight { - (54_113_000 as Weight) - // Standard Error: 1_000 - .saturating_add((331_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((3_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) - fn approve_as_multi_create(s: u32, ) -> Weight { - (37_620_000 as Weight) - // Standard Error: 1_000 - .saturating_add((213_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:0) - fn approve_as_multi_approve(s: u32, ) -> Weight { - (22_753_000 as Weight) - // Standard Error: 1_000 - .saturating_add((220_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn approve_as_multi_complete(s: u32, ) -> Weight { - (81_265_000 as Weight) - // Standard Error: 1_000 - .saturating_add((364_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - fn cancel_as_multi(s: u32, ) -> Weight { - (63_098_000 as Weight) - // Standard Error: 1_000 - .saturating_add((218_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } + fn as_multi_threshold_1(z: u32, ) -> Weight { + (24_003_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) + fn as_multi_create(s: u32, z: u32, ) -> Weight { + (39_194_000 as Weight) + // Standard Error: 1_000 + .saturating_add((190_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) + fn as_multi_create_store(s: u32, z: u32, ) -> Weight { + (45_057_000 as Weight) + // Standard Error: 1_000 + .saturating_add((188_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + fn as_multi_approve(s: u32, z: u32, ) -> Weight { + (26_698_000 as Weight) + // Standard Error: 1_000 + .saturating_add((184_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + fn as_multi_approve_store(s: u32, z: u32, ) -> Weight { + (44_401_000 as Weight) + // Standard Error: 1_000 + .saturating_add((196_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn as_multi_complete(s: u32, z: u32, ) -> Weight { + (54_113_000 as Weight) + // Standard Error: 1_000 + .saturating_add((331_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((3_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) + fn approve_as_multi_create(s: u32, ) -> Weight { + (37_620_000 as Weight) + // Standard Error: 1_000 + .saturating_add((213_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:0) + fn approve_as_multi_approve(s: u32, ) -> Weight { + (22_753_000 as Weight) + // Standard Error: 1_000 + .saturating_add((220_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn approve_as_multi_complete(s: u32, ) -> Weight { + (81_265_000 as Weight) + // Standard Error: 1_000 + .saturating_add((364_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + fn cancel_as_multi(s: u32, ) -> Weight { + (63_098_000 as Weight) + // Standard Error: 1_000 + .saturating_add((218_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - fn as_multi_threshold_1(z: u32, ) -> Weight { - (24_003_000 as Weight) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) - fn as_multi_create(s: u32, z: u32, ) -> Weight { - (39_194_000 as Weight) - // Standard Error: 1_000 - .saturating_add((190_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) - fn as_multi_create_store(s: u32, z: u32, ) -> Weight { - (45_057_000 as Weight) - // Standard Error: 1_000 - .saturating_add((188_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - fn as_multi_approve(s: u32, z: u32, ) -> Weight { - (26_698_000 as Weight) - // Standard Error: 1_000 - .saturating_add((184_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - fn as_multi_approve_store(s: u32, z: u32, ) -> Weight { - (44_401_000 as Weight) - // Standard Error: 1_000 - .saturating_add((196_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn as_multi_complete(s: u32, z: u32, ) -> Weight { - (54_113_000 as Weight) - // Standard Error: 1_000 - .saturating_add((331_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 0 - .saturating_add((3_000 as Weight).saturating_mul(z as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) - fn approve_as_multi_create(s: u32, ) -> Weight { - (37_620_000 as Weight) - // Standard Error: 1_000 - .saturating_add((213_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:0) - fn approve_as_multi_approve(s: u32, ) -> Weight { - (22_753_000 as Weight) - // Standard Error: 1_000 - .saturating_add((220_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - // Storage: System Account (r:1 w:1) - fn approve_as_multi_complete(s: u32, ) -> Weight { - (81_265_000 as Weight) - // Standard Error: 1_000 - .saturating_add((364_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - // Storage: Multisig Multisigs (r:1 w:1) - // Storage: Multisig Calls (r:1 w:1) - fn cancel_as_multi(s: u32, ) -> Weight { - (63_098_000 as Weight) - // Standard Error: 1_000 - .saturating_add((218_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } + fn as_multi_threshold_1(z: u32, ) -> Weight { + (24_003_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) + fn as_multi_create(s: u32, z: u32, ) -> Weight { + (39_194_000 as Weight) + // Standard Error: 1_000 + .saturating_add((190_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) + fn as_multi_create_store(s: u32, z: u32, ) -> Weight { + (45_057_000 as Weight) + // Standard Error: 1_000 + .saturating_add((188_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + fn as_multi_approve(s: u32, z: u32, ) -> Weight { + (26_698_000 as Weight) + // Standard Error: 1_000 + .saturating_add((184_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + fn as_multi_approve_store(s: u32, z: u32, ) -> Weight { + (44_401_000 as Weight) + // Standard Error: 1_000 + .saturating_add((196_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn as_multi_complete(s: u32, z: u32, ) -> Weight { + (54_113_000 as Weight) + // Standard Error: 1_000 + .saturating_add((331_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((3_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) + fn approve_as_multi_create(s: u32, ) -> Weight { + (37_620_000 as Weight) + // Standard Error: 1_000 + .saturating_add((213_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:0) + fn approve_as_multi_approve(s: u32, ) -> Weight { + (22_753_000 as Weight) + // Standard Error: 1_000 + .saturating_add((220_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + // Storage: System Account (r:1 w:1) + fn approve_as_multi_complete(s: u32, ) -> Weight { + (81_265_000 as Weight) + // Standard Error: 1_000 + .saturating_add((364_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + fn cancel_as_multi(s: u32, ) -> Weight { + (63_098_000 as Weight) + // Standard Error: 1_000 + .saturating_add((218_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } } diff --git a/runtime/manta/src/weights/pallet_preimage.rs b/runtime/manta/src/weights/pallet_preimage.rs index 6efcf088f..e725de3c7 100644 --- a/runtime/manta/src/weights/pallet_preimage.rs +++ b/runtime/manta/src/weights/pallet_preimage.rs @@ -43,195 +43,195 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_preimage. pub trait WeightInfo { - fn note_preimage(s: u32, ) -> Weight; - fn note_requested_preimage(s: u32, ) -> Weight; - fn note_no_deposit_preimage(s: u32, ) -> Weight; - fn unnote_preimage() -> Weight; - fn unnote_no_deposit_preimage() -> Weight; - fn request_preimage() -> Weight; - fn request_no_deposit_preimage() -> Weight; - fn request_unnoted_preimage() -> Weight; - fn request_requested_preimage() -> Weight; - fn unrequest_preimage() -> Weight; - fn unrequest_unnoted_preimage() -> Weight; - fn unrequest_multi_referenced_preimage() -> Weight; + fn note_preimage(s: u32, ) -> Weight; + fn note_requested_preimage(s: u32, ) -> Weight; + fn note_no_deposit_preimage(s: u32, ) -> Weight; + fn unnote_preimage() -> Weight; + fn unnote_no_deposit_preimage() -> Weight; + fn request_preimage() -> Weight; + fn request_no_deposit_preimage() -> Weight; + fn request_unnoted_preimage() -> Weight; + fn request_requested_preimage() -> Weight; + fn unrequest_preimage() -> Weight; + fn unrequest_unnoted_preimage() -> Weight; + fn unrequest_multi_referenced_preimage() -> Weight; } /// Weights for pallet_preimage using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_preimage::WeightInfo for SubstrateWeight { - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - fn note_preimage(s: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:0) - fn note_requested_preimage(s: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:0) - fn note_no_deposit_preimage(s: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unnote_preimage() -> Weight { - (41_651_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unnote_no_deposit_preimage() -> Weight { - (24_546_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_preimage() -> Weight { - (42_453_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_no_deposit_preimage() -> Weight { - (22_978_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_unnoted_preimage() -> Weight { - (17_253_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_requested_preimage() -> Weight { - (6_965_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unrequest_preimage() -> Weight { - (24_969_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unrequest_unnoted_preimage() -> Weight { - (17_807_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn unrequest_multi_referenced_preimage() -> Weight { - (6_040_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + fn note_preimage(s: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:0) + fn note_requested_preimage(s: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:0) + fn note_no_deposit_preimage(s: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unnote_preimage() -> Weight { + (41_651_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unnote_no_deposit_preimage() -> Weight { + (24_546_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_preimage() -> Weight { + (42_453_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_no_deposit_preimage() -> Weight { + (22_978_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_unnoted_preimage() -> Weight { + (17_253_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_requested_preimage() -> Weight { + (6_965_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unrequest_preimage() -> Weight { + (24_969_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unrequest_unnoted_preimage() -> Weight { + (17_807_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn unrequest_multi_referenced_preimage() -> Weight { + (6_040_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - fn note_preimage(s: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:0) - fn note_requested_preimage(s: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:0) - fn note_no_deposit_preimage(s: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unnote_preimage() -> Weight { - (41_651_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unnote_no_deposit_preimage() -> Weight { - (24_546_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_preimage() -> Weight { - (42_453_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_no_deposit_preimage() -> Weight { - (22_978_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_unnoted_preimage() -> Weight { - (17_253_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn request_requested_preimage() -> Weight { - (6_965_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unrequest_preimage() -> Weight { - (24_969_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Preimage PreimageFor (r:0 w:1) - fn unrequest_unnoted_preimage() -> Weight { - (17_807_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Preimage StatusFor (r:1 w:1) - fn unrequest_multi_referenced_preimage() -> Weight { - (6_040_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + fn note_preimage(s: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:0) + fn note_requested_preimage(s: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:0) + fn note_no_deposit_preimage(s: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unnote_preimage() -> Weight { + (41_651_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unnote_no_deposit_preimage() -> Weight { + (24_546_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_preimage() -> Weight { + (42_453_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_no_deposit_preimage() -> Weight { + (22_978_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_unnoted_preimage() -> Weight { + (17_253_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn request_requested_preimage() -> Weight { + (6_965_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unrequest_preimage() -> Weight { + (24_969_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Preimage PreimageFor (r:0 w:1) + fn unrequest_unnoted_preimage() -> Weight { + (17_807_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Preimage StatusFor (r:1 w:1) + fn unrequest_multi_referenced_preimage() -> Weight { + (6_040_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } } diff --git a/runtime/manta/src/weights/pallet_scheduler.rs b/runtime/manta/src/weights/pallet_scheduler.rs index edbbd6d5a..25c59e18c 100644 --- a/runtime/manta/src/weights/pallet_scheduler.rs +++ b/runtime/manta/src/weights/pallet_scheduler.rs @@ -43,319 +43,319 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_scheduler. pub trait WeightInfo { - fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight; - fn on_initialize_named_resolved(s: u32, ) -> Weight; - fn on_initialize_periodic_resolved(s: u32, ) -> Weight; - fn on_initialize_resolved(s: u32, ) -> Weight; - fn on_initialize_named_aborted(s: u32, ) -> Weight; - fn on_initialize_aborted(s: u32, ) -> Weight; - fn on_initialize_periodic_named(s: u32, ) -> Weight; - fn on_initialize_periodic(s: u32, ) -> Weight; - fn on_initialize_named(s: u32, ) -> Weight; - fn on_initialize(s: u32, ) -> Weight; - fn schedule(s: u32, ) -> Weight; - fn cancel(s: u32, ) -> Weight; - fn schedule_named(s: u32, ) -> Weight; - fn cancel_named(s: u32, ) -> Weight; + fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight; + fn on_initialize_named_resolved(s: u32, ) -> Weight; + fn on_initialize_periodic_resolved(s: u32, ) -> Weight; + fn on_initialize_resolved(s: u32, ) -> Weight; + fn on_initialize_named_aborted(s: u32, ) -> Weight; + fn on_initialize_aborted(s: u32, ) -> Weight; + fn on_initialize_periodic_named(s: u32, ) -> Weight; + fn on_initialize_periodic(s: u32, ) -> Weight; + fn on_initialize_named(s: u32, ) -> Weight; + fn on_initialize(s: u32, ) -> Weight; + fn schedule(s: u32, ) -> Weight; + fn cancel(s: u32, ) -> Weight; + fn schedule_named(s: u32, ) -> Weight; + fn cancel_named(s: u32, ) -> Weight; } /// Weights for pallet_scheduler using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_scheduler::WeightInfo for SubstrateWeight { - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight { - (9_185_000 as Weight) - // Standard Error: 18_000 - .saturating_add((28_060_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((4 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_named_resolved(s: u32, ) -> Weight { - (9_240_000 as Weight) - // Standard Error: 13_000 - .saturating_add((22_067_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - fn on_initialize_periodic_resolved(s: u32, ) -> Weight { - (9_681_000 as Weight) - // Standard Error: 15_000 - .saturating_add((24_305_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - fn on_initialize_resolved(s: u32, ) -> Weight { - (8_552_000 as Weight) - // Standard Error: 14_000 - .saturating_add((20_482_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:0) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_named_aborted(s: u32, ) -> Weight { - (7_228_000 as Weight) - // Standard Error: 9_000 - .saturating_add((9_300_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:0) - fn on_initialize_aborted(s: u32, ) -> Weight { - (8_419_000 as Weight) - // Standard Error: 6_000 - .saturating_add((5_806_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_periodic_named(s: u32, ) -> Weight { - (15_235_000 as Weight) - // Standard Error: 9_000 - .saturating_add((14_237_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - fn on_initialize_periodic(s: u32, ) -> Weight { - (13_143_000 as Weight) - // Standard Error: 6_000 - .saturating_add((10_693_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_named(s: u32, ) -> Weight { - (13_804_000 as Weight) - // Standard Error: 6_000 - .saturating_add((8_546_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - fn on_initialize(s: u32, ) -> Weight { - (13_081_000 as Weight) - // Standard Error: 5_000 - .saturating_add((7_162_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Scheduler Agenda (r:1 w:1) - fn schedule(s: u32, ) -> Weight { - (17_866_000 as Weight) - // Standard Error: 2_000 - .saturating_add((126_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn cancel(s: u32, ) -> Weight { - (17_953_000 as Weight) - // Standard Error: 3_000 - .saturating_add((1_336_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Scheduler Lookup (r:1 w:1) - // Storage: Scheduler Agenda (r:1 w:1) - fn schedule_named(s: u32, ) -> Weight { - (21_858_000 as Weight) - // Standard Error: 2_000 - .saturating_add((144_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Scheduler Lookup (r:1 w:1) - // Storage: Scheduler Agenda (r:1 w:1) - fn cancel_named(s: u32, ) -> Weight { - (20_520_000 as Weight) - // Standard Error: 3_000 - .saturating_add((1_347_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight { + (9_185_000 as Weight) + // Standard Error: 18_000 + .saturating_add((28_060_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((4 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_named_resolved(s: u32, ) -> Weight { + (9_240_000 as Weight) + // Standard Error: 13_000 + .saturating_add((22_067_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + fn on_initialize_periodic_resolved(s: u32, ) -> Weight { + (9_681_000 as Weight) + // Standard Error: 15_000 + .saturating_add((24_305_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + fn on_initialize_resolved(s: u32, ) -> Weight { + (8_552_000 as Weight) + // Standard Error: 14_000 + .saturating_add((20_482_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:0) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_named_aborted(s: u32, ) -> Weight { + (7_228_000 as Weight) + // Standard Error: 9_000 + .saturating_add((9_300_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:0) + fn on_initialize_aborted(s: u32, ) -> Weight { + (8_419_000 as Weight) + // Standard Error: 6_000 + .saturating_add((5_806_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_periodic_named(s: u32, ) -> Weight { + (15_235_000 as Weight) + // Standard Error: 9_000 + .saturating_add((14_237_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + fn on_initialize_periodic(s: u32, ) -> Weight { + (13_143_000 as Weight) + // Standard Error: 6_000 + .saturating_add((10_693_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_named(s: u32, ) -> Weight { + (13_804_000 as Weight) + // Standard Error: 6_000 + .saturating_add((8_546_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + fn on_initialize(s: u32, ) -> Weight { + (13_081_000 as Weight) + // Standard Error: 5_000 + .saturating_add((7_162_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Scheduler Agenda (r:1 w:1) + fn schedule(s: u32, ) -> Weight { + (17_866_000 as Weight) + // Standard Error: 2_000 + .saturating_add((126_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn cancel(s: u32, ) -> Weight { + (17_953_000 as Weight) + // Standard Error: 3_000 + .saturating_add((1_336_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Scheduler Lookup (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn schedule_named(s: u32, ) -> Weight { + (21_858_000 as Weight) + // Standard Error: 2_000 + .saturating_add((144_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Scheduler Lookup (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn cancel_named(s: u32, ) -> Weight { + (20_520_000 as Weight) + // Standard Error: 3_000 + .saturating_add((1_347_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight { - (9_185_000 as Weight) - // Standard Error: 18_000 - .saturating_add((28_060_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((4 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_named_resolved(s: u32, ) -> Weight { - (9_240_000 as Weight) - // Standard Error: 13_000 - .saturating_add((22_067_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - fn on_initialize_periodic_resolved(s: u32, ) -> Weight { - (9_681_000 as Weight) - // Standard Error: 15_000 - .saturating_add((24_305_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Preimage PreimageFor (r:1 w:1) - // Storage: Preimage StatusFor (r:1 w:1) - fn on_initialize_resolved(s: u32, ) -> Weight { - (8_552_000 as Weight) - // Standard Error: 14_000 - .saturating_add((20_482_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:0) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_named_aborted(s: u32, ) -> Weight { - (7_228_000 as Weight) - // Standard Error: 9_000 - .saturating_add((9_300_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Preimage PreimageFor (r:1 w:0) - fn on_initialize_aborted(s: u32, ) -> Weight { - (8_419_000 as Weight) - // Standard Error: 6_000 - .saturating_add((5_806_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Scheduler Agenda (r:2 w:2) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_periodic_named(s: u32, ) -> Weight { - (15_235_000 as Weight) - // Standard Error: 9_000 - .saturating_add((14_237_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:2 w:2) - fn on_initialize_periodic(s: u32, ) -> Weight { - (13_143_000 as Weight) - // Standard Error: 6_000 - .saturating_add((10_693_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn on_initialize_named(s: u32, ) -> Weight { - (13_804_000 as Weight) - // Standard Error: 6_000 - .saturating_add((8_546_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - // Storage: Scheduler Agenda (r:1 w:1) - fn on_initialize(s: u32, ) -> Weight { - (13_081_000 as Weight) - // Standard Error: 5_000 - .saturating_add((7_162_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Scheduler Agenda (r:1 w:1) - fn schedule(s: u32, ) -> Weight { - (17_866_000 as Weight) - // Standard Error: 2_000 - .saturating_add((126_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: Scheduler Agenda (r:1 w:1) - // Storage: Scheduler Lookup (r:0 w:1) - fn cancel(s: u32, ) -> Weight { - (17_953_000 as Weight) - // Standard Error: 3_000 - .saturating_add((1_336_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Scheduler Lookup (r:1 w:1) - // Storage: Scheduler Agenda (r:1 w:1) - fn schedule_named(s: u32, ) -> Weight { - (21_858_000 as Weight) - // Standard Error: 2_000 - .saturating_add((144_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Scheduler Lookup (r:1 w:1) - // Storage: Scheduler Agenda (r:1 w:1) - fn cancel_named(s: u32, ) -> Weight { - (20_520_000 as Weight) - // Standard Error: 3_000 - .saturating_add((1_347_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight { + (9_185_000 as Weight) + // Standard Error: 18_000 + .saturating_add((28_060_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((4 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_named_resolved(s: u32, ) -> Weight { + (9_240_000 as Weight) + // Standard Error: 13_000 + .saturating_add((22_067_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + fn on_initialize_periodic_resolved(s: u32, ) -> Weight { + (9_681_000 as Weight) + // Standard Error: 15_000 + .saturating_add((24_305_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Preimage PreimageFor (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + fn on_initialize_resolved(s: u32, ) -> Weight { + (8_552_000 as Weight) + // Standard Error: 14_000 + .saturating_add((20_482_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:0) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_named_aborted(s: u32, ) -> Weight { + (7_228_000 as Weight) + // Standard Error: 9_000 + .saturating_add((9_300_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Preimage PreimageFor (r:1 w:0) + fn on_initialize_aborted(s: u32, ) -> Weight { + (8_419_000 as Weight) + // Standard Error: 6_000 + .saturating_add((5_806_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_periodic_named(s: u32, ) -> Weight { + (15_235_000 as Weight) + // Standard Error: 9_000 + .saturating_add((14_237_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:2 w:2) + fn on_initialize_periodic(s: u32, ) -> Weight { + (13_143_000 as Weight) + // Standard Error: 6_000 + .saturating_add((10_693_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn on_initialize_named(s: u32, ) -> Weight { + (13_804_000 as Weight) + // Standard Error: 6_000 + .saturating_add((8_546_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) + } + // Storage: Scheduler Agenda (r:1 w:1) + fn on_initialize(s: u32, ) -> Weight { + (13_081_000 as Weight) + // Standard Error: 5_000 + .saturating_add((7_162_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Scheduler Agenda (r:1 w:1) + fn schedule(s: u32, ) -> Weight { + (17_866_000 as Weight) + // Standard Error: 2_000 + .saturating_add((126_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Scheduler Lookup (r:0 w:1) + fn cancel(s: u32, ) -> Weight { + (17_953_000 as Weight) + // Standard Error: 3_000 + .saturating_add((1_336_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Scheduler Lookup (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn schedule_named(s: u32, ) -> Weight { + (21_858_000 as Weight) + // Standard Error: 2_000 + .saturating_add((144_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Scheduler Lookup (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn cancel_named(s: u32, ) -> Weight { + (20_520_000 as Weight) + // Standard Error: 3_000 + .saturating_add((1_347_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } } diff --git a/runtime/manta/src/weights/pallet_session.rs b/runtime/manta/src/weights/pallet_session.rs index 11ea019dc..b2d0a934e 100644 --- a/runtime/manta/src/weights/pallet_session.rs +++ b/runtime/manta/src/weights/pallet_session.rs @@ -43,43 +43,43 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_session. pub trait WeightInfo { - fn set_keys() -> Weight; - fn purge_keys() -> Weight; + fn set_keys() -> Weight; + fn purge_keys() -> Weight; } /// Weights for pallet_session using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_session::WeightInfo for SubstrateWeight { - // Storage: Session NextKeys (r:1 w:1) - // Storage: Session KeyOwner (r:1 w:1) - fn set_keys() -> Weight { - (17_065_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - // Storage: Session NextKeys (r:1 w:1) - // Storage: Session KeyOwner (r:0 w:1) - fn purge_keys() -> Weight { - (12_878_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } + // Storage: Session NextKeys (r:1 w:1) + // Storage: Session KeyOwner (r:1 w:1) + fn set_keys() -> Weight { + (17_065_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Session NextKeys (r:1 w:1) + // Storage: Session KeyOwner (r:0 w:1) + fn purge_keys() -> Weight { + (12_878_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Session NextKeys (r:1 w:1) - // Storage: Session KeyOwner (r:1 w:1) - fn set_keys() -> Weight { - (17_065_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - // Storage: Session NextKeys (r:1 w:1) - // Storage: Session KeyOwner (r:0 w:1) - fn purge_keys() -> Weight { - (12_878_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } + // Storage: Session NextKeys (r:1 w:1) + // Storage: Session KeyOwner (r:1 w:1) + fn set_keys() -> Weight { + (17_065_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Session NextKeys (r:1 w:1) + // Storage: Session KeyOwner (r:0 w:1) + fn purge_keys() -> Weight { + (12_878_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } } diff --git a/runtime/manta/src/weights/pallet_timestamp.rs b/runtime/manta/src/weights/pallet_timestamp.rs index 91fc1cb8f..d840768d7 100644 --- a/runtime/manta/src/weights/pallet_timestamp.rs +++ b/runtime/manta/src/weights/pallet_timestamp.rs @@ -43,33 +43,33 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_timestamp. pub trait WeightInfo { - fn set() -> Weight; - fn on_finalize() -> Weight; + fn set() -> Weight; + fn on_finalize() -> Weight; } /// Weights for pallet_timestamp using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_timestamp::WeightInfo for SubstrateWeight { - // Storage: Timestamp Now (r:1 w:1) - fn set() -> Weight { - (4_978_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn on_finalize() -> Weight { - (3_034_000 as Weight) - } + // Storage: Timestamp Now (r:1 w:1) + fn set() -> Weight { + (4_978_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + fn on_finalize() -> Weight { + (3_034_000 as Weight) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Timestamp Now (r:1 w:1) - fn set() -> Weight { - (4_978_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - fn on_finalize() -> Weight { - (3_034_000 as Weight) - } + // Storage: Timestamp Now (r:1 w:1) + fn set() -> Weight { + (4_978_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + fn on_finalize() -> Weight { + (3_034_000 as Weight) + } } diff --git a/runtime/manta/src/weights/pallet_tx_pause.rs b/runtime/manta/src/weights/pallet_tx_pause.rs index 51c0fcdb6..29b051459 100644 --- a/runtime/manta/src/weights/pallet_tx_pause.rs +++ b/runtime/manta/src/weights/pallet_tx_pause.rs @@ -43,39 +43,39 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_tx_pause. pub trait WeightInfo { - fn pause_transaction() -> Weight; - fn unpause_transaction() -> Weight; + fn pause_transaction() -> Weight; + fn unpause_transaction() -> Weight; } /// Weights for pallet_tx_pause using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl pallet_tx_pause::WeightInfo for SubstrateWeight { - // Storage: TransactionPause PausedTransactions (r:1 w:1) - fn pause_transaction() -> Weight { - (12_947_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - // Storage: TransactionPause PausedTransactions (r:1 w:1) - fn unpause_transaction() -> Weight { - (14_530_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } + // Storage: TransactionPause PausedTransactions (r:1 w:1) + fn pause_transaction() -> Weight { + (12_947_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: TransactionPause PausedTransactions (r:1 w:1) + fn unpause_transaction() -> Weight { + (14_530_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: TransactionPause PausedTransactions (r:1 w:1) - fn pause_transaction() -> Weight { - (12_947_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - // Storage: TransactionPause PausedTransactions (r:1 w:1) - fn unpause_transaction() -> Weight { - (14_530_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } + // Storage: TransactionPause PausedTransactions (r:1 w:1) + fn pause_transaction() -> Weight { + (12_947_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: TransactionPause PausedTransactions (r:1 w:1) + fn unpause_transaction() -> Weight { + (14_530_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } }