From 6b9501a00c17da3b80543c7941e1a8d299c1bda8 Mon Sep 17 00:00:00 2001 From: MyronFanQiu Date: Tue, 25 Oct 2022 11:25:30 +0800 Subject: [PATCH] Bump to 0.9.29 bump to 0930 working switch to 0.9.29 compiled version --- crust-collator/Cargo.toml | 93 +- .../pallets/asset-manager/Cargo.toml | 22 +- .../pallets/asset-manager/src/lib.rs | 3 +- .../pallets/asset-manager/src/migrations.rs | 559 ------- .../pallets/asset-manager/src/weights.rs | 208 ++- crust-collator/pallets/benefits/Cargo.toml | 22 +- .../pallets/bridge-transfer/Cargo.toml | 22 +- .../pallets/bridge-transfer/src/lib.rs | 168 +- crust-collator/pallets/bridge/Cargo.toml | 18 +- .../pallets/bridge/src/benchmarking.rs | 27 + crust-collator/pallets/bridge/src/lib.rs | 1381 +++++++++-------- crust-collator/pallets/bridge/src/mock.rs | 269 ++-- crust-collator/pallets/bridge/src/tests.rs | 1096 +++++++------ crust-collator/pallets/bridge/src/types.rs | 103 ++ crust-collator/pallets/claims/Cargo.toml | 18 +- crust-collator/pallets/claims/src/lib.rs | 304 ++-- .../pallets/collator-selection/Cargo.toml | 36 +- .../pallets/collator-selection/src/lib.rs | 6 +- .../pallets/collator-selection/src/weights.rs | 110 +- crust-collator/pallets/market/Cargo.toml | 18 +- crust-collator/pallets/staking/Cargo.toml | 36 +- crust-collator/pallets/swork/Cargo.toml | 20 +- .../pallets/swork/benchmarking/Cargo.toml | 20 +- crust-collator/pallets/xstorage/Cargo.toml | 28 +- crust-collator/pallets/xstorage/src/lib.rs | 2 +- crust-collator/primitives/Cargo.toml | 18 +- crust-collator/primitives/src/lib.rs | 16 +- crust-collator/runtime/Cargo.toml | 100 +- crust-collator/runtime/src/lib.rs | 35 +- .../runtime/src/weights/block_weights.rs | 52 + .../src/weights/cumulus_pallet_xcmp_queue.rs | 61 + .../runtime/src/weights/extrinsic_weights.rs | 52 + .../runtime/src/weights/frame_system.rs | 90 ++ crust-collator/runtime/src/weights/mod.rs | 14 +- .../runtime/src/weights/pallet_assets.rs | 235 +++ .../runtime/src/weights/pallet_balances.rs | 86 +- .../src/weights/pallet_collator_selection.rs | 127 +- .../runtime/src/weights/pallet_multisig.rs | 187 ++- .../runtime/src/weights/pallet_proxy.rs | 106 -- .../runtime/src/weights/pallet_session.rs | 54 +- .../runtime/src/weights/pallet_timestamp.rs | 47 +- .../runtime/src/weights/pallet_utility.rs | 69 +- .../runtime/src/weights/paritydb_weights.rs | 63 + .../runtime/src/weights/rocksdb_weights.rs | 63 + .../weights/xcm/cumulus_pallet_xcmp_queue.rs | 63 + crust-collator/runtime/src/weights/xcm/mod.rs | 188 +++ .../xcm/pallet_xcm_benchmarks_fungible.rs | 107 ++ .../xcm/pallet_xcm_benchmarks_generic.rs | 137 ++ crust-collator/src/command.rs | 6 +- crust-collator/src/rpc.rs | 6 +- crust-collator/src/service.rs | 11 +- cumulus | 2 +- 52 files changed, 3885 insertions(+), 2699 deletions(-) delete mode 100644 crust-collator/pallets/asset-manager/src/migrations.rs create mode 100644 crust-collator/pallets/bridge/src/benchmarking.rs create mode 100644 crust-collator/pallets/bridge/src/types.rs create mode 100644 crust-collator/runtime/src/weights/block_weights.rs create mode 100644 crust-collator/runtime/src/weights/cumulus_pallet_xcmp_queue.rs create mode 100644 crust-collator/runtime/src/weights/extrinsic_weights.rs create mode 100644 crust-collator/runtime/src/weights/frame_system.rs create mode 100644 crust-collator/runtime/src/weights/pallet_assets.rs delete mode 100644 crust-collator/runtime/src/weights/pallet_proxy.rs create mode 100644 crust-collator/runtime/src/weights/paritydb_weights.rs create mode 100644 crust-collator/runtime/src/weights/rocksdb_weights.rs create mode 100644 crust-collator/runtime/src/weights/xcm/cumulus_pallet_xcmp_queue.rs create mode 100644 crust-collator/runtime/src/weights/xcm/mod.rs create mode 100644 crust-collator/runtime/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs create mode 100644 crust-collator/runtime/src/weights/xcm/pallet_xcm_benchmarks_generic.rs diff --git a/crust-collator/Cargo.toml b/crust-collator/Cargo.toml index f1c5ecc8..8f09b0e8 100644 --- a/crust-collator/Cargo.toml +++ b/crust-collator/Cargo.toml @@ -18,7 +18,7 @@ parking_lot = "0.12.0" trie-root = "0.15.2" codec = { package = "parity-scale-codec", version = "3.0.0" } structopt = "0.3.3" -serde = { version = "1.0.140", features = ["derive"] } +serde = { version = "1.0.144", features = ["derive"] } hex-literal = "0.3.4" clap = { version = "3.2.15", features = ["derive"] } @@ -27,41 +27,42 @@ parachain-runtime = { package = "crust-parachain-runtime", path = "runtime" } crust-parachain-primitives = { path = "primitives" } # Substrate dependencies -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-inherents = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-consensus = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-session = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sc-consensus = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sc-cli = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sc-client-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sc-executor = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sc-service = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sc-telemetry = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sc-transaction-pool = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-transaction-pool = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sc-network = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sc-basic-authorship = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-timestamp = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-block-builder = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-keystore = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-trie = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sc-finality-grandpa = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sc-chain-spec = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sc-rpc = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sc-tracing = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-offchain = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-consensus-aura = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -substrate-prometheus-endpoint = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-inherents = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-consensus = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-session = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sc-consensus = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sc-cli = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sc-client-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sc-executor = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sc-service = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sc-telemetry = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sc-transaction-pool = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-transaction-pool = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sc-network = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sc-network-common = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sc-basic-authorship = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-timestamp = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-block-builder = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-keystore = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-trie = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sc-finality-grandpa = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sc-chain-spec = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sc-rpc = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sc-tracing = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-offchain = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-consensus-aura = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +substrate-prometheus-endpoint = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } # RPC related dependencies -jsonrpsee = { version = "0.14.0", features = ["server"] } -sc-transaction-pool-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -frame-rpc-system = { package = "substrate-frame-rpc-system", git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -pallet-transaction-payment-rpc = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } +jsonrpsee = { version = "0.15.0", default-features = false, features = [ "macros", "server" ] } +sc-transaction-pool-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +frame-rpc-system = { package = "substrate-frame-rpc-system", git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +pallet-transaction-payment-rpc = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } # Cumulus dependencies cumulus-client-cli = { path = "../cumulus/client/cli" } @@ -78,13 +79,13 @@ cumulus-relay-chain-inprocess-interface = { path = "../cumulus/client/relay-chai cumulus-relay-chain-rpc-interface = { path = "../cumulus/client/relay-chain-rpc-interface" } # Polkadot dependencies -polkadot-primitives = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.27" } -polkadot-service = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.27" } -polkadot-cli = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.27" } -polkadot-parachain = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.27" } +polkadot-primitives = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.29" } +polkadot-service = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.29" } +polkadot-cli = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.29" } +polkadot-parachain = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.29" } [build-dependencies] -substrate-build-script-utils = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } +substrate-build-script-utils = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } [dev-dependencies] assert_cmd = "0.12" @@ -93,12 +94,12 @@ rand = "0.7.3" tokio = { version = "1.10", features = ["macros"] } # Polkadot dependencies -polkadot-primitives = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.27" } -polkadot-service = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.27" } -polkadot-cli = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.27" } -polkadot-parachain = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.27" } +polkadot-primitives = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.29" } +polkadot-service = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.29" } +polkadot-cli = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.29" } +polkadot-parachain = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.29" } # Substrate dependencies -pallet-sudo = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -substrate-test-client = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -substrate-test-runtime-client = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } +pallet-sudo = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +substrate-test-client = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +substrate-test-runtime-client = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } diff --git a/crust-collator/pallets/asset-manager/Cargo.toml b/crust-collator/pallets/asset-manager/Cargo.toml index e673a0c0..bf1c2152 100644 --- a/crust-collator/pallets/asset-manager/Cargo.toml +++ b/crust-collator/pallets/asset-manager/Cargo.toml @@ -8,29 +8,29 @@ version = "0.1.0" [dependencies] log = { version = "0.4.17", default-features = false } -serde = { version = "1.0.140", optional = true } +serde = { version = "1.0.144", optional = true } # Moonbeam primitives = { package = "crust-parachain-primitives", path = "../../primitives", default-features = false } # Substrate -frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } -frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } +frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } parity-scale-codec = { version = "3.0.0", default-features = false, features = [ "derive" ] } -scale-info = { version = "2.1.1", default-features = false, features = [ "derive" ] } -sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } -sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } -sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } +scale-info = { version = "2.2.0", default-features = false, features = [ "derive" ] } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } +sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } # Polkadot -xcm = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.27", default-features = false } +xcm = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.29", default-features = false } # Benchmarks -frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", optional = true, default-features = false } +frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", optional = true, default-features = false } [dev-dependencies] -pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } +pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } [features] default = [ "std" ] diff --git a/crust-collator/pallets/asset-manager/src/lib.rs b/crust-collator/pallets/asset-manager/src/lib.rs index 49946892..879954d4 100644 --- a/crust-collator/pallets/asset-manager/src/lib.rs +++ b/crust-collator/pallets/asset-manager/src/lib.rs @@ -38,7 +38,6 @@ use frame_support::pallet; pub use pallet::*; #[cfg(any(test, feature = "runtime-benchmarks"))] mod benchmarks; -pub mod migrations; #[cfg(test)] pub mod mock; #[cfg(test)] @@ -190,7 +189,7 @@ pub mod pallet { #[pallet::call] impl Pallet { /// Register new asset with the asset manager - #[pallet::weight(T::WeightInfo::register_asset())] + #[pallet::weight(T::WeightInfo::register_foreign_asset())] pub fn register_asset( origin: OriginFor, asset: T::AssetType, diff --git a/crust-collator/pallets/asset-manager/src/migrations.rs b/crust-collator/pallets/asset-manager/src/migrations.rs deleted file mode 100644 index 0ede9254..00000000 --- a/crust-collator/pallets/asset-manager/src/migrations.rs +++ /dev/null @@ -1,559 +0,0 @@ -// Copyright 2019-2021 PureStake Inc. -// This file is part of Moonbeam. - -// Moonbeam 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. - -// Moonbeam 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 Moonbeam. If not, see . - -use crate::{AssetIdType, AssetTypeId, AssetTypeUnitsPerSecond, Config, SupportedFeePaymentAssets}; -use frame_support::{ - pallet_prelude::PhantomData, - storage::migration::storage_key_iter, - traits::{Get, OnRuntimeUpgrade}, - weights::Weight, - Blake2_128Concat, -}; -use sp_std::convert::TryInto; -//TODO sometimes this is unused, sometimes its necessary -use sp_std::vec::Vec; -use xcm::latest::prelude::*; - -/// Migration that changes the mapping AssetId -> units_per_second to -/// a mapping of the form AssetType -> units_per_second -/// It does so by removing the AssetTypeUnitsPerSecond storage and -/// populating the new AssetTypeUnitsPerSecond -pub struct UnitsWithAssetType(PhantomData); -impl OnRuntimeUpgrade for UnitsWithAssetType { - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result<(), &'static str> { - use frame_support::traits::OnRuntimeUpgradeHelpersExt; - - let pallet_prefix: &[u8] = b"AssetManager"; - let storage_item_prefix: &[u8] = b"AssetIdUnitsPerSecond"; - - // We want to test that: - // There are no entries in the new storage beforehand - // The same number of mappings exist before and after - // As long as there are some mappings stored, one representative key maps to the - // same value after the migration. - // There are no entries in the old storage afterward - - // Assert new storage is empty - assert!(AssetTypeUnitsPerSecond::::iter().next().is_none()); - - // Check number of entries, and set it aside in temp storage - let stored_data: Vec<_> = storage_key_iter::( - pallet_prefix, - storage_item_prefix, - ) - .collect(); - let mapping_count = stored_data.len(); - Self::set_temp_storage(mapping_count as u32, "mapping_count"); - - // Read an example pair from old storage and set it aside in temp storage - if mapping_count > 0 { - let example_pair = stored_data - .iter() - .next() - .expect("We already confirmed that there was at least one item stored"); - - Self::set_temp_storage(example_pair, "example_pair"); - } - - Ok(()) - } - - fn on_runtime_upgrade() -> Weight { - log::info!(target: "UnitsWithAssetType", "actually running it"); - let pallet_prefix: &[u8] = b"AssetManager"; - let storage_item_prefix: &[u8] = b"AssetIdUnitsPerSecond"; - - // Read all the data into memory. - // https://crates.parity.io/frame_support/storage/migration/fn.storage_key_iter.html - let stored_data: Vec<_> = storage_key_iter::( - pallet_prefix, - storage_item_prefix, - ) - .drain() - .collect(); - - let migrated_count: Weight = stored_data - .len() - .try_into() - .expect("There are between 0 and 2**64 mappings stored."); - - log::info!(target: "UnitsWithAssetType", "Migrating {:?} elements", migrated_count); - - // Write to the new storage with removed and added fields - for (asset_id, units) in stored_data { - // Read the assetType for the assetId - if let Some(asset_type) = AssetIdType::::get(&asset_id) { - // Populate with assetType as key - AssetTypeUnitsPerSecond::::insert(&asset_type, units) - } - } - - log::info!(target: "UnitsWithAssetType", "almost done"); - - // Return the weight used. For each migrated mapping there is a read to get it into - // memory, a read to get assetType and - // a write to clear the old stored value, and a write to re-store it. - let db_weights = T::DbWeight::get(); - migrated_count.saturating_mul(2 * db_weights.write + 2 * db_weights.read) - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade() -> Result<(), &'static str> { - use frame_support::traits::OnRuntimeUpgradeHelpersExt; - - let pallet_prefix: &[u8] = b"AssetManager"; - let storage_item_prefix: &[u8] = b"AssetIdUnitsPerSecond"; - // Assert that old storage is empty - assert!(storage_key_iter::( - pallet_prefix, - storage_item_prefix - ) - .next() - .is_none()); - - // Check number of entries matches what was set aside in pre_upgrade - let old_mapping_count: u64 = Self::get_temp_storage("mapping_count") - .expect("We stored a mapping count; it should be there; qed"); - let new_mapping_count = AssetTypeUnitsPerSecond::::iter().count() as u64; - assert_eq!(old_mapping_count, new_mapping_count); - - // Check that our example pair is still well-mapped after the migration - if new_mapping_count > 0 { - let (asset_id, units): (T::AssetId, u128) = - Self::get_temp_storage("example_pair").expect("qed"); - - let asset_type = - AssetIdType::::get(asset_id).expect("AssetIdType should have the assetType"); - - let migrated_units = AssetTypeUnitsPerSecond::::get(asset_type).expect("qed"); - // Check units are identical - assert_eq!(migrated_units, units); - } - - Ok(()) - } -} - -/// Migration that reads data from the AssetIdType mapping (AssetId -> AssetType) -/// and populates the reverse mapping AssetTypeId (AssetType -> AssetId) -pub struct PopulateAssetTypeIdStorage(PhantomData); -impl OnRuntimeUpgrade for PopulateAssetTypeIdStorage { - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result<(), &'static str> { - use frame_support::traits::OnRuntimeUpgradeHelpersExt; - - let pallet_prefix: &[u8] = b"AssetManager"; - let storage_item_prefix: &[u8] = b"AssetIdType"; - - // We want to test that: - // The new storage item is empty - // The same number of mappings exist before and after - // As long as there are some mappings stored, - // there will exist the reserve mapping in the new storage - - // Assert new storage is empty - assert!(AssetTypeId::::iter().next().is_none()); - - // Check number of entries, and set it aside in temp storage - let stored_data: Vec<_> = storage_key_iter::( - pallet_prefix, - storage_item_prefix, - ) - .collect(); - let mapping_count = stored_data.len(); - Self::set_temp_storage(mapping_count as u32, "mapping_count"); - - // Read an example pair from old storage and set it aside in temp storage - if mapping_count > 0 { - let example_pair = stored_data - .iter() - .next() - .expect("We already confirmed that there was at least one item stored"); - - Self::set_temp_storage(example_pair, "example_pair"); - } - - Ok(()) - } - - fn on_runtime_upgrade() -> Weight { - log::info!(target: "PopulateAssetTypeIdStorage", "actually running it"); - let pallet_prefix: &[u8] = b"AssetManager"; - let storage_item_prefix: &[u8] = b"AssetIdType"; - - // Read all the data into memory. - // https://crates.parity.io/frame_support/storage/migration/fn.storage_key_iter.html - let stored_data: Vec<_> = storage_key_iter::( - pallet_prefix, - storage_item_prefix, - ) - .collect(); - - let migrated_count: Weight = stored_data - .len() - .try_into() - .expect("There are between 0 and 2**64 mappings stored."); - - log::info!( - target: "PopulateAssetTypeIdStorage", - "Migrating {:?} elements", - migrated_count - ); - - // Write to the new storage - for (asset_id, asset_type) in stored_data { - // Populate with assetType as key - AssetTypeId::::insert(&asset_type, asset_id) - } - - log::info!(target: "PopulateAssetTypeIdStorage", "almost done"); - - // Return the weight used. For each migrated mapping there is a read to get it into - // memory, and a write to populate the new storage. - let db_weights = T::DbWeight::get(); - migrated_count.saturating_mul(db_weights.write + db_weights.read) - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade() -> Result<(), &'static str> { - use frame_support::traits::OnRuntimeUpgradeHelpersExt; - - // Check number of entries matches what was set aside in pre_upgrade - let mapping_count: u64 = Self::get_temp_storage("mapping_count") - .expect("We stored a mapping count; it should be there; qed"); - let new_mapping_count = AssetTypeId::::iter().count() as u64; - assert_eq!(mapping_count, new_mapping_count); - - // Check that our example pair is still well-mapped after the migration - if new_mapping_count > 0 { - let (asset_id, asset_type): (T::AssetId, T::AssetType) = - Self::get_temp_storage("example_pair").expect("qed"); - - let stored_asset_id = - AssetTypeId::::get(asset_type).expect("AssetTypeId should have the assetId"); - - // Check assetIds are identical - assert_eq!(asset_id, stored_asset_id); - } - - Ok(()) - } -} - -/// Migration that reads the existing AssetTypes looking for old Statemine prefixes of -/// the form (Parachain, GeneralIndex) and changes them for the new prefix -/// (Parachain, PalletInstance, GeneralIndex) -pub struct ChangeStateminePrefixes( - PhantomData<(T, StatemineParaIdInfo, StatemineAssetsInstanceInfo)>, -); -impl OnRuntimeUpgrade - for ChangeStateminePrefixes -where - T: Config, - StatemineParaIdInfo: Get, - StatemineAssetsInstanceInfo: Get, - T::AssetType: Into> + From, -{ - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result<(), &'static str> { - use frame_support::traits::OnRuntimeUpgradeHelpersExt; - - let pallet_prefix: &[u8] = b"AssetManager"; - let storage_item_prefix: &[u8] = b"AssetIdType"; - - // We want to test that: - // If there exists an assetType matching the Statemine, it gets overwritten - - // Check number of entries, and set it aside in temp storage - let stored_data: Vec<_> = storage_key_iter::( - pallet_prefix, - storage_item_prefix, - ) - .collect(); - - let statemine_para_id = StatemineParaIdInfo::get(); - - let mut found = false; - - for (asset_id, asset_type) in stored_data { - let location: Option = asset_type.clone().into(); - match location { - Some(MultiLocation { - parents: 1, - interior: X2(Parachain(para_id), GeneralIndex(_)), - }) if para_id == statemine_para_id => { - // We are going to note that we found at least one entry matching - found = true; - // And we are going to record its data - Self::set_temp_storage((asset_id, asset_type), "example_pair"); - break; - } - _ => continue, - } - } - Self::set_temp_storage(found, "matching_type_found"); - - Ok(()) - } - - fn on_runtime_upgrade() -> Weight { - log::info!(target: "ChangeStateminePrefixes", "actually running it"); - let pallet_prefix: &[u8] = b"AssetManager"; - let storage_item_prefix: &[u8] = b"AssetIdType"; - - // Read all the data into memory. - // https://crates.parity.io/frame_support/storage/migration/fn.storage_key_iter.html - let stored_data: Vec<_> = storage_key_iter::( - pallet_prefix, - storage_item_prefix, - ) - .collect(); - - let read_count: Weight = stored_data - .len() - .try_into() - .expect("There are between 0 and 2**64 mappings stored."); - - log::info!(target: "ChangeStateminePrefixes", "Evaluating {:?} elements", read_count); - - let db_weights = T::DbWeight::get(); - - let mut used_weight = read_count.saturating_mul(db_weights.read); - let statemine_para_id = StatemineParaIdInfo::get(); - let statemine_assets_pallet = StatemineAssetsInstanceInfo::get(); - // Write to the new storage - for (asset_id, asset_type) in stored_data { - let location: Option = asset_type.clone().into(); - match location { - Some(MultiLocation { - parents: 1, - interior: X2(Parachain(para_id), GeneralIndex(index)), - }) if para_id == statemine_para_id => { - let new_location = MultiLocation { - parents: 1, - interior: X3( - Parachain(para_id), - PalletInstance(statemine_assets_pallet), - GeneralIndex(index), - ), - }; - let new_asset_type: T::AssetType = new_location.into(); - // Insert new asset type previous asset type - AssetIdType::::insert(&asset_id, &new_asset_type); - - // This is checked in case AssetManagerPopulateAssetTypeIdStorage runs first - if AssetTypeId::::get(&asset_type) == Some(asset_id) { - // We need to update AssetTypeId too - AssetTypeId::::remove(&asset_type); - AssetTypeId::::insert(&new_asset_type, asset_id); - - // Update weight due to this branch - used_weight = used_weight.saturating_add(2 * db_weights.write); - } - - // This is checked in case UnitsWithAssetType runs first - if let Some(units) = AssetTypeUnitsPerSecond::::take(&asset_type) { - // We need to update AssetTypeUnitsPerSecond too - AssetTypeUnitsPerSecond::::insert(&new_asset_type, units); - - // Update weight due to this branch - used_weight = used_weight.saturating_add(2 * db_weights.write); - } - - // Update used weight - used_weight = - used_weight.saturating_add(db_weights.write + 2 * db_weights.read); - } - _ => continue, - } - } - - log::info!(target: "ChangeStateminePrefixes", "almost done"); - - // Return the weight used. - used_weight - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade() -> Result<(), &'static str> { - use frame_support::traits::OnRuntimeUpgradeHelpersExt; - - // Check if we found a matching type - let found: bool = Self::get_temp_storage("matching_type_found") - .expect("We stored a matching_type_found and should be here; qed"); - - let statemine_para_id = StatemineParaIdInfo::get(); - let statemine_assets_pallet = StatemineAssetsInstanceInfo::get(); - - // Check that our example pair suffered the correct migration - if found { - let (asset_id, asset_type): (T::AssetId, T::AssetType) = - Self::get_temp_storage("example_pair").expect("qed"); - let location: Option = asset_type.into(); - - match location { - Some(MultiLocation { - parents: 1, - interior: X2(Parachain(para_id), GeneralIndex(index)), - }) if para_id == statemine_para_id => { - let stored_asset_type = - AssetIdType::::get(asset_id).expect("This entry should be updated"); - - let expected_new_asset_type: T::AssetType = MultiLocation { - parents: 1, - interior: X3( - Parachain(para_id), - PalletInstance(statemine_assets_pallet), - GeneralIndex(index), - ), - } - .into(); - - // Check assetTypes are identical - assert_eq!(stored_asset_type, expected_new_asset_type); - } - _ => panic!("This should never have entered this path"), - } - } - - Ok(()) - } -} - -pub struct PopulateSupportedFeePaymentAssets(PhantomData); -impl OnRuntimeUpgrade for PopulateSupportedFeePaymentAssets { - fn on_runtime_upgrade() -> Weight { - log::trace!( - target: "PopulateSupportedFeePaymentAssets", - "Running PopulateSupportedFeePaymentAssets migration" - ); - let pallet_prefix: &[u8] = b"AssetManager"; - let storage_item_prefix: &[u8] = b"AssetTypeUnitsPerSecond"; - - log::trace!( - target: "PopulateSupportedFeePaymentAssets", - "grabbing from AssetTypeUnitsPerSecond" - ); - - // Read all the data into memory. - // https://crates.parity.io/frame_support/storage/migration/fn.storage_key_iter.html - let stored_data: Vec<_> = storage_key_iter::( - pallet_prefix, - storage_item_prefix, - ) - .collect(); - - let migrated_count: Weight = stored_data - .len() - .try_into() - .expect("There are between 0 and 2**64 mappings stored."); - - log::trace!( - target: "PopulateSupportedFeePaymentAssets", - "PopulateSupportedFeePaymentAssets pushing {:?} elements to SupportedFeePaymentAssets", - migrated_count - ); - - // Collect in a vec - let mut supported_assets: Vec = Vec::new(); - for (asset_type, _) in stored_data { - supported_assets.push(asset_type); - } - - supported_assets.sort(); - - // Push value - SupportedFeePaymentAssets::::put(&supported_assets); - - log::trace!( - target: "PopulateSupportedFeePaymentAssets", - "SupportedFeePaymentAssets populated now having {:?} elements", - supported_assets.len() - ); - - // Return the weight used. For each migrated mapping there is a read to get it into - // memory - // A final one write makes it push to the new storage item - let db_weights = T::DbWeight::get(); - let weight = migrated_count.saturating_mul(db_weights.read); - weight.saturating_add(db_weights.write) - } - - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result<(), &'static str> { - use frame_support::traits::OnRuntimeUpgradeHelpersExt; - - let pallet_prefix: &[u8] = b"AssetManager"; - let storage_item_prefix: &[u8] = b"AssetTypeUnitsPerSecond"; - - // We want to test that: - // There are no entries in the new storage beforehand - // The same number of mappings exist before and after - // As long as there are some mappings stored, one representative key maps to the - // same value after the migration. - // There are no entries in the old storage afterward - - // Assert new storage is empty - // Because the pallet and item prefixes are the same, the old storage is still at this - // key. However, the values can't be decoded so the assertion passes. - assert!(SupportedFeePaymentAssets::::get().len() == 0); - - // Check number of entries, and set it aside in temp storage - let stored_data: Vec<_> = storage_key_iter::( - pallet_prefix, - storage_item_prefix, - ) - .collect(); - let mapping_count = stored_data.len(); - Self::set_temp_storage(mapping_count as u64, "mapping_count"); - - // Read an example pair from old storage and set it aside in temp storage - if mapping_count > 0 { - let example_key = stored_data - .iter() - .next() - .expect("We already confirmed that there was at least one item stored") - .clone() - .0; - - Self::set_temp_storage(example_key, "example_pair"); - } - - Ok(()) - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade() -> Result<(), &'static str> { - use frame_support::traits::OnRuntimeUpgradeHelpersExt; - - // Check number of entries matches what was set aside in pre_upgrade - let old_mapping_count: u64 = Self::get_temp_storage("mapping_count") - .expect("We stored a mapping count; it should be there; qed"); - let new_mapping_count = SupportedFeePaymentAssets::::get().len() as u64; - assert_eq!(old_mapping_count, new_mapping_count); - - // Check that our example pair is still well-mapped after the migration - if new_mapping_count > 0 { - let asset_type: T::AssetType = Self::get_temp_storage("example_pair").expect("qed"); - let migrated_info = SupportedFeePaymentAssets::::get(); - // Check that the asset_id exists in migrated_info - assert!(migrated_info.contains(&asset_type)); - } - - Ok(()) - } -} diff --git a/crust-collator/pallets/asset-manager/src/weights.rs b/crust-collator/pallets/asset-manager/src/weights.rs index 6bba6963..52857b5d 100644 --- a/crust-collator/pallets/asset-manager/src/weights.rs +++ b/crust-collator/pallets/asset-manager/src/weights.rs @@ -17,29 +17,28 @@ //! Autogenerated weights for pallet_asset_manager //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2022-02-22, STEPS: `32`, REPEAT: 64, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 +//! DATE: 2022-09-28, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024 // Executed Command: // ./target/release/moonbeam // benchmark -// --chain -// dev +// pallet // --execution=wasm // --wasm-execution=compiled // --pallet -// pallet_asset_manager +// * // --extrinsic // * // --steps -// 32 +// 50 // --repeat -// 64 -// --raw +// 20 // --template=./benchmarking/frame-weight-template.hbs +// --json-file +// raw.json // --output -// /tmp/ -// --record-proof +// ./tmp/ #![allow(unused_parens)] #![allow(unused_imports)] @@ -52,76 +51,157 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_asset_manager. pub trait WeightInfo { - fn register_asset() -> Weight; - fn set_asset_units_per_second(x: u32) -> Weight; - fn change_existing_asset_type(x: u32) -> Weight; - fn remove_supported_asset(x: u32) -> Weight; - fn remove_existing_asset_type(x: u32) -> Weight; + #[rustfmt::skip] + fn register_foreign_asset() -> Weight; + #[rustfmt::skip] + fn set_asset_units_per_second(x: u32, ) -> Weight; + #[rustfmt::skip] + fn change_existing_asset_type(x: u32, ) -> Weight; + #[rustfmt::skip] + fn remove_supported_asset(x: u32, ) -> Weight; + #[rustfmt::skip] + fn register_local_asset() -> Weight; + #[rustfmt::skip] + fn remove_existing_asset_type(x: u32, ) -> Weight; } /// Weights for pallet_asset_manager using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { - fn register_asset() -> Weight { - (52_375_000 as Weight) - .saturating_add(T::DbWeight::get().reads(7 as Weight)) - .saturating_add(T::DbWeight::get().writes(6 as Weight)) + // Storage: AssetManager AssetIdType (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:1) + // Storage: AssetManager AssetTypeId (r:0 w:1) + #[rustfmt::skip] + fn register_foreign_asset() -> Weight { + Weight::from_ref_time(57_298_000 as u64) + .saturating_add(T::DbWeight::get().reads(3 as u64)) + .saturating_add(T::DbWeight::get().writes(4 as u64)) + } + // Storage: AssetManager AssetTypeId (r:1 w:0) + // Storage: AssetManager SupportedFeePaymentAssets (r:1 w:1) + // Storage: AssetManager AssetTypeUnitsPerSecond (r:0 w:1) + #[rustfmt::skip] + fn set_asset_units_per_second(x: u32, ) -> Weight { + Weight::from_ref_time(40_775_000 as u64) + // Standard Error: 1_000 + .saturating_add(Weight::from_ref_time(523_000 as u64).saturating_mul(x as u64)) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) } - fn set_asset_units_per_second(x: u32) -> Weight { - (31_655_000 as Weight) // Standard Error: 4_000 - .saturating_add((1_258_000 as Weight).saturating_mul(x as Weight)) - .saturating_add(T::DbWeight::get().reads(6 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) + // Storage: AssetManager SupportedFeePaymentAssets (r:1 w:1) + // Storage: AssetManager AssetIdType (r:1 w:1) + // Storage: AssetManager AssetTypeUnitsPerSecond (r:1 w:2) + // Storage: AssetManager AssetTypeId (r:0 w:2) + #[rustfmt::skip] + fn change_existing_asset_type(x: u32, ) -> Weight { + Weight::from_ref_time(53_066_000 as u64) + // Standard Error: 2_000 + .saturating_add(Weight::from_ref_time(573_000 as u64).saturating_mul(x as u64)) + .saturating_add(T::DbWeight::get().reads(3 as u64)) + .saturating_add(T::DbWeight::get().writes(6 as u64)) } - fn change_existing_asset_type(x: u32) -> Weight { - (39_476_000 as Weight) // Standard Error: 4_000 - .saturating_add((1_338_000 as Weight).saturating_mul(x as Weight)) - .saturating_add(T::DbWeight::get().reads(7 as Weight)) - .saturating_add(T::DbWeight::get().writes(8 as Weight)) + // Storage: AssetManager SupportedFeePaymentAssets (r:1 w:1) + // Storage: AssetManager AssetTypeUnitsPerSecond (r:0 w:1) + #[rustfmt::skip] + fn remove_supported_asset(x: u32, ) -> Weight { + Weight::from_ref_time(35_386_000 as u64) + // Standard Error: 1_000 + .saturating_add(Weight::from_ref_time(491_000 as u64).saturating_mul(x as u64)) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) } - fn remove_supported_asset(x: u32) -> Weight { - (24_269_000 as Weight) // Standard Error: 4_000 - .saturating_add((1_148_000 as Weight).saturating_mul(x as Weight)) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) + // Storage: System Account (r:1 w:1) + // Storage: AssetManager LocalAssetCounter (r:1 w:1) + // Storage: LocalAssets Asset (r:1 w:1) + // Storage: EVM AccountCodes (r:0 w:1) + // Storage: AssetManager LocalAssetDeposit (r:0 w:1) + #[rustfmt::skip] + fn register_local_asset() -> Weight { + Weight::from_ref_time(68_261_000 as u64) + .saturating_add(T::DbWeight::get().reads(3 as u64)) + .saturating_add(T::DbWeight::get().writes(5 as u64)) } - fn remove_existing_asset_type(x: u32) -> Weight { - (30_428_000 as Weight) // Standard Error: 3_000 - .saturating_add((1_166_000 as Weight).saturating_mul(x as Weight)) - .saturating_add(T::DbWeight::get().reads(6 as Weight)) - .saturating_add(T::DbWeight::get().writes(6 as Weight)) + // Storage: AssetManager SupportedFeePaymentAssets (r:1 w:1) + // Storage: AssetManager AssetIdType (r:1 w:1) + // Storage: AssetManager AssetTypeUnitsPerSecond (r:0 w:1) + // Storage: AssetManager AssetTypeId (r:0 w:1) + #[rustfmt::skip] + fn remove_existing_asset_type(x: u32, ) -> Weight { + Weight::from_ref_time(42_478_000 as u64) + // Standard Error: 1_000 + .saturating_add(Weight::from_ref_time(497_000 as u64).saturating_mul(x as u64)) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(4 as u64)) } } // For backwards compatibility and tests impl WeightInfo for () { - fn register_asset() -> Weight { - (52_375_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(7 as Weight)) - .saturating_add(RocksDbWeight::get().writes(6 as Weight)) + // Storage: AssetManager AssetIdType (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:1) + // Storage: AssetManager AssetTypeId (r:0 w:1) + #[rustfmt::skip] + fn register_foreign_asset() -> Weight { + Weight::from_ref_time(57_298_000 as u64) + .saturating_add(RocksDbWeight::get().reads(3 as u64)) + .saturating_add(RocksDbWeight::get().writes(4 as u64)) } - fn set_asset_units_per_second(x: u32) -> Weight { - (31_655_000 as Weight) // Standard Error: 4_000 - .saturating_add((1_258_000 as Weight).saturating_mul(x as Weight)) - .saturating_add(RocksDbWeight::get().reads(6 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + // Storage: AssetManager AssetTypeId (r:1 w:0) + // Storage: AssetManager SupportedFeePaymentAssets (r:1 w:1) + // Storage: AssetManager AssetTypeUnitsPerSecond (r:0 w:1) + #[rustfmt::skip] + fn set_asset_units_per_second(x: u32, ) -> Weight { + Weight::from_ref_time(40_775_000 as u64) + // Standard Error: 1_000 + .saturating_add(Weight::from_ref_time(523_000 as u64).saturating_mul(x as u64)) + .saturating_add(RocksDbWeight::get().reads(2 as u64)) + .saturating_add(RocksDbWeight::get().writes(2 as u64)) } - fn change_existing_asset_type(x: u32) -> Weight { - (39_476_000 as Weight) // Standard Error: 4_000 - .saturating_add((1_338_000 as Weight).saturating_mul(x as Weight)) - .saturating_add(RocksDbWeight::get().reads(7 as Weight)) - .saturating_add(RocksDbWeight::get().writes(8 as Weight)) + // Storage: AssetManager SupportedFeePaymentAssets (r:1 w:1) + // Storage: AssetManager AssetIdType (r:1 w:1) + // Storage: AssetManager AssetTypeUnitsPerSecond (r:1 w:2) + // Storage: AssetManager AssetTypeId (r:0 w:2) + #[rustfmt::skip] + fn change_existing_asset_type(x: u32, ) -> Weight { + Weight::from_ref_time(53_066_000 as u64) + // Standard Error: 2_000 + .saturating_add(Weight::from_ref_time(573_000 as u64).saturating_mul(x as u64)) + .saturating_add(RocksDbWeight::get().reads(3 as u64)) + .saturating_add(RocksDbWeight::get().writes(6 as u64)) } - fn remove_supported_asset(x: u32) -> Weight { - (24_269_000 as Weight) // Standard Error: 4_000 - .saturating_add((1_148_000 as Weight).saturating_mul(x as Weight)) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + // Storage: AssetManager SupportedFeePaymentAssets (r:1 w:1) + // Storage: AssetManager AssetTypeUnitsPerSecond (r:0 w:1) + #[rustfmt::skip] + fn remove_supported_asset(x: u32, ) -> Weight { + Weight::from_ref_time(35_386_000 as u64) + // Standard Error: 1_000 + .saturating_add(Weight::from_ref_time(491_000 as u64).saturating_mul(x as u64)) + .saturating_add(RocksDbWeight::get().reads(1 as u64)) + .saturating_add(RocksDbWeight::get().writes(2 as u64)) } - fn remove_existing_asset_type(x: u32) -> Weight { - (30_428_000 as Weight) // Standard Error: 3_000 - .saturating_add((1_166_000 as Weight).saturating_mul(x as Weight)) - .saturating_add(RocksDbWeight::get().reads(6 as Weight)) - .saturating_add(RocksDbWeight::get().writes(6 as Weight)) + // Storage: System Account (r:1 w:1) + // Storage: AssetManager LocalAssetCounter (r:1 w:1) + // Storage: LocalAssets Asset (r:1 w:1) + // Storage: EVM AccountCodes (r:0 w:1) + // Storage: AssetManager LocalAssetDeposit (r:0 w:1) + #[rustfmt::skip] + fn register_local_asset() -> Weight { + Weight::from_ref_time(68_261_000 as u64) + .saturating_add(RocksDbWeight::get().reads(3 as u64)) + .saturating_add(RocksDbWeight::get().writes(5 as u64)) } -} + // Storage: AssetManager SupportedFeePaymentAssets (r:1 w:1) + // Storage: AssetManager AssetIdType (r:1 w:1) + // Storage: AssetManager AssetTypeUnitsPerSecond (r:0 w:1) + // Storage: AssetManager AssetTypeId (r:0 w:1) + #[rustfmt::skip] + fn remove_existing_asset_type(x: u32, ) -> Weight { + Weight::from_ref_time(42_478_000 as u64) + // Standard Error: 1_000 + .saturating_add(Weight::from_ref_time(497_000 as u64).saturating_mul(x as u64)) + .saturating_add(RocksDbWeight::get().reads(2 as u64)) + .saturating_add(RocksDbWeight::get().writes(4 as u64)) + } +} \ No newline at end of file diff --git a/crust-collator/pallets/benefits/Cargo.toml b/crust-collator/pallets/benefits/Cargo.toml index 54e4963a..0cca934f 100644 --- a/crust-collator/pallets/benefits/Cargo.toml +++ b/crust-collator/pallets/benefits/Cargo.toml @@ -8,28 +8,28 @@ homepage = "https://crust.network" repository = "https://github.com/paritytech/crust/" [dependencies] -serde = { default-features = false, version = "1.0.140" } +serde = { default-features = false, version = "1.0.144" } serde_derive = { optional = true, version = "1.0.102" } codec = { package = "parity-scale-codec", default-features = false, version = "3.0.0" } rustc-hex = { default-features = false, version = "2.0.1" } -scale-info = { version = "2.1.1", default-features = false, features = ["derive"] } +scale-info = { version = "2.2.0", default-features = false, features = ["derive"] } # substrate frame dependencies -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } +frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } primitives = { package = "crust-parachain-primitives", path = "../../primitives", default-features = false } -frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } +frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } [dev-dependencies] -balances = { package = 'pallet-balances', git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } +balances = { package = 'pallet-balances', git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } primitives = { package = "crust-parachain-primitives", path = "../../primitives", features = ["test"] } hex-literal = "0.3.4" -frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27"} +frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29"} [features] default = ["std"] diff --git a/crust-collator/pallets/bridge-transfer/Cargo.toml b/crust-collator/pallets/bridge-transfer/Cargo.toml index b75d51e5..f5f74925 100644 --- a/crust-collator/pallets/bridge-transfer/Cargo.toml +++ b/crust-collator/pallets/bridge-transfer/Cargo.toml @@ -10,19 +10,19 @@ repository = "https://github.com/paritytech/crust/" [dependencies] # third-party dependencies codec = { default-features = false, package = "parity-scale-codec", features = ["derive"], version = "3.0.0" } -serde = { optional = true, version = "1.0.140" } -scale-info = { version = "2.1.1", default-features = false, features = ["derive"] } +serde = { optional = true, version = "1.0.144" } +scale-info = { version = "2.2.0", default-features = false, features = ["derive"] } # primitives -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-arithmetic = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } +sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-arithmetic = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } # frame dependencies -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } +frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } cstrml-bridge = { path = "../bridge" , default-features = false } hex = { version = "0.4", default-features = false } @@ -30,8 +30,8 @@ hex = { version = "0.4", default-features = false } [dev-dependencies] blake2-rfc = { version = "0.2.18", default-features = false } hex-literal = "0.3.4" -balances = { package = 'pallet-balances', git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -pallet-timestamp = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27"} +balances = { package = 'pallet-balances', git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +pallet-timestamp = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29"} [features] default = ["std"] diff --git a/crust-collator/pallets/bridge-transfer/src/lib.rs b/crust-collator/pallets/bridge-transfer/src/lib.rs index 17f916a4..b81377cc 100644 --- a/crust-collator/pallets/bridge-transfer/src/lib.rs +++ b/crust-collator/pallets/bridge-transfer/src/lib.rs @@ -1,94 +1,119 @@ -// Copyright 2020 ChainSafe Systems -// SPDX-License-Identifier: LGPL-3.0-only - -// Ensure we're `no_std` when compiling for Wasm. +#![deny(warnings)] #![cfg_attr(not(feature = "std"), no_std)] -use frame_support::traits::{Currency, EnsureOrigin, ExistenceRequirement::AllowDeath, Get}; -use frame_support::{ - decl_error, decl_event, decl_module, decl_storage, dispatch::DispatchResult, ensure, +pub use pallet::{ + Call, + Config, + Error, + Event, + Pallet, + *, }; -use frame_system::{self as system, ensure_root, ensure_signed}; -use cstrml_bridge as bridge; -use sp_arithmetic::traits::SaturatedConversion; -use sp_core::U256; -use sp_std::prelude::*; -use sp_runtime::traits::Saturating; -use sp_std::convert::TryInto; #[cfg(test)] mod mock; + #[cfg(test)] mod tests; +mod types { + use crate::pallet::Config; + use frame_support::traits::Currency; -type BalanceOf = - <::Currency as Currency<::AccountId>>::Balance; - -pub trait Config: system::Config + bridge::Config { - type Event: From> + Into<::Event>; - - /// Specifies the origin check provided by the bridge for calls that can only be called by the bridge pallet - type BridgeOrigin: EnsureOrigin; - - /// The currency mechanism. - type Currency: Currency; - - type BridgeTokenId: Get<[u8; 32]>; -} - -decl_storage! { - trait Store for Module as BridgeTransfer { - BridgeFee get(fn bridge_fee): map hasher(opaque_blake2_256) u8 => (BalanceOf, u32); - } + pub type BalanceOf = <::Currency as Currency< + ::AccountId, + >>::Balance; } -decl_event! { - pub enum Event - where - Balance = BalanceOf, - { - /// [chainId, min_fee, fee_scale] - FeeUpdated(u8, Balance, u32), - } -} - -decl_error! { - pub enum Error for Module{ - InvalidTransfer, +#[frame_support::pallet] +pub mod pallet { + use crate::types::{ + BalanceOf, + }; + use frame_support::{ + pallet_prelude::*, + traits::{ + Currency, + ExistenceRequirement::AllowDeath, + }, + }; + use frame_system::pallet_prelude::*; + use frame_support::sp_runtime::traits::Saturating; + use frame_support::sp_runtime::SaturatedConversion; + use sp_core::U256; + use sp_std::convert::TryInto; + use sp_std::vec::Vec; + use cstrml_bridge as bridge; + + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(_); + + /// Tracks current relayer set + #[pallet::storage] + #[pallet::getter(fn bridge_fee)] + pub type BridgeFee = + StorageMap<_, Blake2_256, u8, (BalanceOf, u32), ValueQuery>; + + /// Configure the pallet by specifying the parameters and types on which it depends. + #[pallet::config] + pub trait Config: + frame_system::Config + + bridge::Config + { + /// Because this pallet emits events, it depends on the runtime's definition of an event. + type Event: From> + + IsType<::Event>; + + /// Specifies the origin check provided by the bridge for calls that can only be called by + /// the bridge pallet + type BridgeOrigin: EnsureOrigin; + + /// The currency mechanism + type Currency: Currency; + + /// Ids can be defined by the runtime and passed in, perhaps from blake2b_128 hashes. + type BridgeTokenId: Get<[u8; 32]>; + } + + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { + FeeUpdated(u8, BalanceOf, u32), + } + + // Errors inform users that something went wrong. + #[pallet::error] + pub enum Error { + InvalidTransfer, InvalidCommand, InvalidPayload, InvalidFeeOption, FeeOptionsMissiing, - LessThanFee, - } -} - -decl_module! { - pub struct Module for enum Call where origin: T::Origin { - type Error = Error; - // - // Initiation calls. These start a bridge transfer. - // - - fn deposit_event() = default; - - /// Change extra bridge transfer fee that user should pay - #[weight = 195_000_000] - pub fn sudo_change_fee(origin, min_fee: BalanceOf, fee_scale: u32, dest_id: u8) -> DispatchResult { + LessThanFee + } + + // Dispatchable functions allows users to interact with the pallet and invoke state changes. + // These functions materialize as "extrinsics", which are often compared to transactions. + // Dispatchable functions must be annotated with a weight and must return a DispatchResult. + #[pallet::call] + impl Pallet { + /// Change extra bridge transfer fee that user should pay + #[pallet::weight(195_000_000)] + pub fn sudo_change_fee(origin: OriginFor, min_fee: BalanceOf, fee_scale: u32, dest_id: u8) -> DispatchResult { ensure_root(origin)?; ensure!(fee_scale <= 1000u32, Error::::InvalidFeeOption); BridgeFee::::insert(dest_id, (min_fee, fee_scale)); - Self::deposit_event(RawEvent::FeeUpdated(dest_id, min_fee, fee_scale)); + Self::deposit_event(Event::FeeUpdated(dest_id, min_fee, fee_scale)); Ok(()) } /// Transfers some amount of the native token to some recipient on a (whitelisted) destination chain. - #[weight = 195_000_000] - pub fn transfer_native(origin, amount: BalanceOf, recipient: Vec, dest_id: u8) -> DispatchResult { + #[pallet::weight(195_000_000)] + pub fn transfer_native(origin: OriginFor, amount: BalanceOf, recipient: Vec, dest_id: u8) -> DispatchResult { let source = ensure_signed(origin)?; - ensure!(>::chain_whitelisted(dest_id), Error::::InvalidTransfer); - let bridge_id = >::account_id(); + ensure!(>::chain_whitelisted(dest_id), Error::::InvalidTransfer); + let bridge_id = >::account_id(); ensure!(BridgeFee::::contains_key(&dest_id), Error::::FeeOptionsMissiing); let (min_fee, fee_scale) = Self::bridge_fee(dest_id); let fee_estimated = amount * fee_scale.into() / 1000u32.into(); @@ -100,7 +125,7 @@ decl_module! { ensure!(amount > fee, Error::::LessThanFee); T::Currency::transfer(&source, &bridge_id, amount.into(), AllowDeath)?; - >::transfer_fungible(dest_id, T::BridgeTokenId::get(), recipient, U256::from(amount.saturating_sub(fee).saturated_into::())) + >::transfer_fungible(dest_id, T::BridgeTokenId::get(), recipient, U256::from(amount.saturating_sub(fee).saturated_into::())) } // @@ -108,11 +133,12 @@ decl_module! { // /// Executes a simple currency transfer using the bridge account as the source - #[weight = 195_000_000] - pub fn transfer(origin, to: T::AccountId, amount: BalanceOf, _rid: [u8; 32]) -> DispatchResult { + #[pallet::weight(195_000_000)] + pub fn transfer(origin: OriginFor, to: T::AccountId, amount: BalanceOf, _rid: [u8; 32]) -> DispatchResult { let source = T::BridgeOrigin::ensure_origin(origin)?; ::Currency::transfer(&source, &to, amount.into(), AllowDeath)?; Ok(()) } - } + + } } diff --git a/crust-collator/pallets/bridge/Cargo.toml b/crust-collator/pallets/bridge/Cargo.toml index 3e2737db..f3b353e2 100644 --- a/crust-collator/pallets/bridge/Cargo.toml +++ b/crust-collator/pallets/bridge/Cargo.toml @@ -10,21 +10,21 @@ repository = "https://github.com/paritytech/crust/" [dependencies] # third-party dependencies codec = { default-features = false, package = "parity-scale-codec", features = ["derive"], version = "3.0.0" } -serde = { optional = true, version = "1.0.140" } -scale-info = { version = "2.1.1", default-features = false, features = ["derive"] } +serde = { optional = true, version = "1.0.144" } +scale-info = { version = "2.2.0", default-features = false, features = ["derive"] } # primitives -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } +sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } # frame dependencies -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } +frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } [dev-dependencies] -balances = { package = 'pallet-balances', git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } +balances = { package = 'pallet-balances', git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } [features] default = ["std"] diff --git a/crust-collator/pallets/bridge/src/benchmarking.rs b/crust-collator/pallets/bridge/src/benchmarking.rs new file mode 100644 index 00000000..51405e3e --- /dev/null +++ b/crust-collator/pallets/bridge/src/benchmarking.rs @@ -0,0 +1,27 @@ +// Copyright 2021 ChainSafe Systems +// SPDX-License-Identifier: GPL-3.0-only + +//! Benchmarking setup for pallet-template + +use super::*; + +#[allow(unused)] +use crate::Pallet as ChainBridge; + +use frame_benchmarking::{ + benchmarks, + whitelisted_caller, +}; +use frame_system::RawOrigin; + +benchmarks! { + set_threshold { + let s in 0 .. 100; + let caller: T::AccountId = whitelisted_caller(); + }: _(RawOrigin::Signed(caller), s) + verify { + assert_eq!(RelayerCount::::get(), s); + } + + impl_benchmark_test_suite!(ChainBridge, crate::mock::new_test_ext(), crate::mock::MockRuntime); +} diff --git a/crust-collator/pallets/bridge/src/lib.rs b/crust-collator/pallets/bridge/src/lib.rs index 1cdb6599..8a3e9f33 100644 --- a/crust-collator/pallets/bridge/src/lib.rs +++ b/crust-collator/pallets/bridge/src/lib.rs @@ -1,659 +1,762 @@ -// Copyright 2020 ChainSafe Systems -// SPDX-License-Identifier: LGPL-3.0-only - -// Ensure we're `no_std` when compiling for Wasm. +// Copyright 2021 ChainSafe Systems +// SPDX-License-Identifier: GPL-3.0-only + +//! # Filecoin Governance Pallet +//! +//! This pallet uses a set of AccountIds to identify who +//! can vote on proposals. Relayers may be added, removed. +//! There is no bound on how many members may exist in the committee. +//! +//! For each block addition proposal, relayers can vote on them. +//! The pallet will lazily resolve all the proposals. +//! Admin could also resolve manually. +//! +#![deny(warnings)] #![cfg_attr(not(feature = "std"), no_std)] use frame_support::{ - decl_error, decl_event, decl_module, decl_storage, - dispatch::DispatchResult, - ensure, - traits::{EnsureOrigin, Get}, - weights::{GetDispatchInfo, Pays}, - Parameter, PalletId + pallet_prelude::EnsureOrigin, + traits::Get, }; - -use frame_system::{self as system, ensure_signed}; -use sp_core::U256; -use sp_runtime::traits::{AccountIdConversion, Dispatchable}; -use sp_runtime::{RuntimeDebug}; -use sp_std::prelude::*; -use sp_std::vec; -use sp_std::convert::TryInto; -use frame_support::pallet_prelude::Weight; - -use codec::{Decode, Encode, EncodeLike}; +use sp_runtime::traits::AccountIdConversion; +pub use pallet::{ + Config, + Error, + Event, + Pallet, + RelayerThreshold, + *, +}; +pub use types::{ + ResourceId, +}; +pub mod types; #[cfg(test)] mod mock; + #[cfg(test)] mod tests; -const DEFAULT_RELAYER_THRESHOLD: u32 = 1; - +#[cfg(feature = "runtime-benchmarks")] +mod benchmarking; + +#[frame_support::pallet] +pub mod pallet { + use crate::types::{ + ProposalStatus, + ProposalVotes, + ResourceId, + BridgeEvent, + }; + use codec::EncodeLike; + use frame_support::{ + dispatch::Dispatchable, + pallet_prelude::*, + weights::GetDispatchInfo, + PalletId, + }; + use frame_system::pallet_prelude::*; + use scale_info::prelude::boxed::Box; + use sp_runtime::traits::AccountIdConversion; + use sp_core::U256; + use sp_std::vec::Vec; + use sp_std::convert::TryInto; + + #[pallet::config] + pub trait Config: frame_system::Config { + type Event: From> + + IsType<::Event>; + /// Origin used to administer the pallet + type BridgeCommitteeOrigin: EnsureOrigin; + /// Proposed dispatchable call + type Proposal: Parameter + + Dispatchable + + EncodeLike + + GetDispatchInfo; + /// The identifier for this chain. + /// This must be unique and must not collide with existing IDs within a set of bridged + /// chains. + #[pallet::constant] + type BridgeChainId: Get; + + #[pallet::constant] + type ProposalLifetime: Get; + + /// Constant configuration parameter to store the module identifier for the pallet. + /// + /// The module identifier may be of the form ```PalletId(*b"chnbrdge")``` and set + /// using the [`parameter_types`](https://substrate.dev/docs/en/knowledgebase/runtime/macros#parameter_types) + // macro in the [`runtime/lib.rs`] file. + #[pallet::constant] + type PalletId: Get; + } + + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + #[pallet::without_storage_info] + pub struct Pallet(_); + + /// If there is not default relayer threshold set yet, return the value of 1 + #[pallet::type_value] + pub fn DefaultRelayerThreshold() -> u32 { + 1 + } + + #[pallet::storage] + #[pallet::getter(fn relayer_threshold)] + /// Number of votes required for a proposal to execute + pub type RelayerThreshold = + StorageValue<_, u32, ValueQuery, DefaultRelayerThreshold>; + + /// Utilized by the bridge software to map resource IDs to actual methods + #[pallet::storage] + #[pallet::getter(fn resources)] + pub type Resources = + StorageMap<_, Blake2_256, [u8; 32], Vec, OptionQuery>; + + /// All whitelisted chains and their respective transaction counts + #[pallet::storage] + #[pallet::getter(fn chains)] + pub type ChainNonces = + StorageMap<_, Blake2_256, u8, Option, ValueQuery>; + + /// Tracks current relayer set + #[pallet::storage] + #[pallet::getter(fn relayers)] + pub type Relayers = + StorageMap<_, Blake2_256, T::AccountId, (), OptionQuery>; + + #[pallet::storage] + #[pallet::getter(fn relayer_count)] + pub type RelayerCount = StorageValue<_, u32, ValueQuery>; + + /// All known proposals. + /// The key is the hash of the call and the deposit ID, to ensure it's unique. + #[pallet::storage] + #[pallet::getter(fn get_votes)] + pub(super) type Votes = StorageDoubleMap< + _, + Blake2_256, + u8, + Blake2_256, + (u64, T::Proposal), + ProposalVotes, + OptionQuery, + >; + + /// All whitelisted chains and their respective transaction counts + #[pallet::storage] + #[pallet::getter(fn bridge_events)] + pub type BridgeEvents = + StorageValue<_, Vec, ValueQuery>; + + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { + /// Vote threshold has changed (new_threshold) + RelayerThresholdChanged(u32), + /// Chain now available for transfers (chain_id) + ChainWhitelisted(u8), + /// Relayer added to set + RelayerAdded(T::AccountId), + /// Relayer removed from set + RelayerRemoved(T::AccountId), + /// FunglibleTransfer is for relaying fungibles (dest_id, nonce, resource_id, amount, recipient, metadata) + FungibleTransfer(u8, u64, ResourceId, U256, Vec), + /// NonFungibleTransfer is for relaying NFTS (dest_id, nonce, resource_id, token_id, recipient, metadata) + NonFungibleTransfer( + u8, + u64, + ResourceId, + Vec, + Vec, + Vec, + ), + /// GenericTransfer is for a generic data payload (dest_id, nonce, resource_id, metadata) + GenericTransfer(u8, u64, ResourceId, Vec), + /// Vote submitted in favour of proposal + VoteFor(u8, u64, T::AccountId), + /// Vot submitted against proposal + VoteAgainst(u8, u64, T::AccountId), + /// Voting successful for a proposal + ProposalApproved(u8, u64), + /// Voting rejected a proposal + ProposalRejected(u8, u64), + /// Execution of call succeeded + ProposalSucceeded(u8, u64), + /// Execution of call failed + ProposalFailed(u8, u64), + } + + #[pallet::error] + pub enum Error { + /// Relayer threshold not set + ThresholdNotSet, + /// Provided chain Id is not valid + InvalidChainId, + /// Relayer threshold cannot be 0 + InvalidThreshold, + /// Interactions with this chain is not permitted + ChainNotWhitelisted, + /// Chain has already been enabled + ChainAlreadyWhitelisted, + /// Resource ID provided isn't mapped to anything + ResourceDoesNotExist, + /// Relayer already in set + RelayerAlreadyExists, + /// Provided accountId is not a relayer + RelayerInvalid, + /// Protected operation, must be performed by relayer + MustBeRelayer, + /// Relayer has already submitted some vote for this proposal + RelayerAlreadyVoted, + /// A proposal with these parameters has already been submitted + ProposalAlreadyExists, + /// No proposal with the ID was found + ProposalDoesNotExist, + /// Cannot complete proposal, needs more votes + ProposalNotComplete, + /// Proposal has either failed or succeeded + ProposalAlreadyComplete, + /// Lifetime of proposal has been exceeded + ProposalExpired, + } + + #[pallet::call] + impl Pallet { + /// Sets the vote threshold for proposals. + /// + /// This threshold is used to determine how many votes are required + /// before a proposal is executed. + /// + /// # + /// - O(1) lookup and insert + /// # + #[pallet::weight(10_000)] + pub fn set_threshold( + origin: OriginFor, + threshold: u32, + ) -> DispatchResult { + Self::ensure_admin(origin)?; + Self::set_relayer_threshold(threshold)?; + Ok(()) + } + + /// Stores a method name on chain under an associated resource ID. + /// + /// # + /// - O(1) write + /// # + #[pallet::weight(10_000)] + pub fn set_resource( + origin: OriginFor, + id: [u8; 32], + method: Vec, + ) -> DispatchResult { + Self::ensure_admin(origin)?; + Self::register_resource(id, method)?; + Ok(()) + } + + /// Removes a resource ID from the resource mapping. + /// + /// After this call, bridge transfers with the associated resource ID will + /// be rejected. + /// + /// # + /// - O(1) removeal + /// # + #[pallet::weight(10_000)] + pub fn remove_resource( + origin: OriginFor, + id: [u8; 32], + ) -> DispatchResult { + Self::ensure_admin(origin)?; + Self::unregister_resource(id)?; + Ok(()) + } + + /// Adds a new relayer to the relayer set. + /// + /// # + /// - O(1) lookup and insert + /// # + #[pallet::weight(10_000)] + pub fn whitelist_chain( + origin: OriginFor, + id: u8, + ) -> DispatchResult { + Self::ensure_admin(origin)?; + Self::whitelist(id)?; + Ok(()) + } + + /// Adds a new relayer to the relayer set. + /// + /// # + /// - O(1) lookup and removal + /// # + #[pallet::weight(10_000)] + pub fn add_relayer( + origin: OriginFor, + v: T::AccountId, + ) -> DispatchResult { + Self::ensure_admin(origin)?; + Self::register_relayer(v)?; + Ok(()) + } + + /// Removes an existing relaye to the set. + /// + /// # + /// - O(1) lookup and removal + /// # + #[pallet::weight(10_000)] + pub fn remove_relayer( + origin: OriginFor, + v: T::AccountId, + ) -> DispatchResult { + Self::ensure_admin(origin)?; + Self::unregister_relayer(v)?; + Ok(()) + } + + /// Commits a vote in favour of the provided proposal. + /// + /// If a proposal with the given nonce and source chain ID does not already exist, + /// it will be created with an initial vote in favour from the caller. + /// + /// # + /// - weight of proposed call, regardless of whether execution is performed + /// # + #[pallet::weight(10_000)] + pub fn acknowledge_proposal( + origin: OriginFor, + nonce: u64, + src_id: u8, + r_id: [u8; 32], + call: Box<::Proposal>, + ) -> DispatchResult { + let who = ensure_signed(origin)?; + ensure!(Self::is_relayer(&who), Error::::MustBeRelayer); + ensure!( + Self::chain_whitelisted(src_id), + Error::::ChainNotWhitelisted + ); + ensure!( + Self::resource_exists(r_id), + Error::::ResourceDoesNotExist + ); + + Self::vote_for(who, nonce, src_id, call) + } + + /// Commits a vote against a provided proposal. + /// + /// # + /// - Fixed, since execution of proposal should not be included + /// # + #[pallet::weight(10_000)] + pub fn reject_proposal( + origin: OriginFor, + nonce: u64, + src_id: u8, + r_id: [u8; 32], + call: Box<::Proposal>, + ) -> DispatchResult { + let who = ensure_signed(origin)?; + ensure!(Self::is_relayer(&who), Error::::MustBeRelayer); + ensure!( + Self::chain_whitelisted(src_id), + Error::::ChainNotWhitelisted + ); + ensure!( + Self::resource_exists(r_id), + Error::::ResourceDoesNotExist + ); + Self::vote_against(who, nonce, src_id, call) + } + + /// Evaluate the state of a proposal given the current vote threshold. + /// + /// A proposal with enough votes will be either executed or cancelled, and the status + /// will be updated accordingly. + /// + /// # + /// - weight of proposed call, regardless of whether execution is performed + /// # + #[pallet::weight(10_000)] + pub fn eval_vote_state( + origin: OriginFor, + nonce: u64, + src_id: u8, + prop: Box<::Proposal>, + ) -> DispatchResult { + ensure_signed(origin)?; + + Self::try_resolve_proposal(nonce, src_id, prop) + } + } + + impl Pallet { + // ** Utility methods *** + + pub fn ensure_admin(origin: OriginFor) -> DispatchResult { + T::BridgeCommitteeOrigin::try_origin(origin) + .map(|_| ()) + .or_else(ensure_root)?; + Ok(()) + } + + /// Checks if who is a relayer + pub fn is_relayer(who: &T::AccountId) -> bool { + >::contains_key(who) + } + + /// Provides an AccountId for the pallet. + /// This is used both as an origin check and deposit/withdrawal account. + pub fn account_id() -> T::AccountId { + T::PalletId::get().into_account_truncating() + } + + /// Asserts if a resource is registered + pub fn resource_exists(id: [u8; 32]) -> bool { + Self::resources(id) != None + } + + /// Checks if a chain exists as a whitelisted destination + pub fn chain_whitelisted(id: u8) -> bool { + Self::chains(id) != None + } + + /// Increments the deposit nonce for the specified chain ID + fn bump_nonce(id: u8) -> u64 { + let nonce = Self::chains(id).unwrap_or_default().saturating_add(1); + >::insert(id, Some(nonce)); + nonce + } + + // *** Admin methods **** + + /// Set a new voting threshold + pub fn set_relayer_threshold(threshold: u32) -> DispatchResult { + ensure!(threshold > 0, Error::::InvalidThreshold); + >::put(threshold); + Self::deposit_event(Event::RelayerThresholdChanged(threshold)); + Ok(()) + } + + /// Register a method for a resource Id, enabling associated transfer + pub fn register_resource( + id: [u8; 32], + method: Vec, + ) -> DispatchResult { + >::insert(id, method); + Ok(()) + } + + /// Removes a resource ID, disabling associated transfer + pub fn unregister_resource(id: [u8; 32]) -> DispatchResult { + >::remove(id); + Ok(()) + } + + /// Whitelist a chain ID for transfer + pub fn whitelist(id: u8) -> DispatchResult { + // Cannot whitelist this chain + ensure!(id != T::BridgeChainId::get(), Error::::InvalidChainId); + // Cannot whitelist with an existing entry + ensure!( + !Self::chain_whitelisted(id), + Error::::ChainAlreadyWhitelisted + ); + >::insert(&id, Some(0)); + Self::deposit_event(Event::ChainWhitelisted(id)); + Ok(()) + } + + /// Adds a new relayer to the set + pub fn register_relayer(relayer: T::AccountId) -> DispatchResult { + ensure!( + !Self::is_relayer(&relayer), + Error::::RelayerAlreadyExists + ); + >::insert(&relayer, ()); + >::mutate(|i| *i = i.saturating_add(1)); + Self::deposit_event(Event::RelayerAdded(relayer)); + Ok(()) + } + + /// Removes a relayer from the set + pub fn unregister_relayer(relayer: T::AccountId) -> DispatchResult { + ensure!(Self::is_relayer(&relayer), Error::::RelayerInvalid); + >::remove(&relayer); + >::mutate(|i| *i = i.saturating_sub(1)); + Self::deposit_event(Event::RelayerRemoved(relayer)); + Ok(()) + } + + // *** Proposal voting and execution methods *** + + /// Commits a vote for a proposal. If the proposal doesn't exist it will be created. + fn commit_vote( + who: T::AccountId, + nonce: u64, + src_id: u8, + prop: Box, + in_favour: bool, + ) -> DispatchResult { + let now = >::block_number(); + let mut votes = match >::get(src_id, (nonce, prop.clone())) + { + Some(v) => v, + None => { + let mut v = ProposalVotes::default(); + v.expiry = now + T::ProposalLifetime::get(); + v + } + }; + + // Ensure the proposal isn't complete, proposal is not expired and relayer hasn't already votes + ensure!(!votes.is_complete(), Error::::ProposalAlreadyComplete); + ensure!(!votes.is_expired(now), Error::::ProposalExpired); + ensure!(!votes.has_voted(&who), Error::::RelayerAlreadyVoted); + + if in_favour { + votes.votes_for.push(who.clone()); + Self::deposit_event(Event::VoteFor(src_id, nonce, who.clone())); + } else { + votes.votes_against.push(who.clone()); + Self::deposit_event(Event::VoteAgainst( + src_id, + nonce, + who.clone(), + )); + } + + >::insert(src_id, (nonce, prop.clone()), votes.clone()); + + Ok(()) + } + + /// Attempts to finalize or cancel the proposal if the vote count allows. + fn try_resolve_proposal( + nonce: u64, + src_id: u8, + prop: Box, + ) -> DispatchResult { + if let Some(mut votes) = + >::get(src_id, (nonce, prop.clone())) + { + let now = >::block_number(); + ensure!( + !votes.is_complete(), + Error::::ProposalAlreadyComplete + ); + ensure!(!votes.is_expired(now), Error::::ProposalExpired); + + let status = votes.try_to_complete( + >::get(), + >::get(), + ); + >::insert( + src_id, + (nonce, prop.clone()), + votes.clone(), + ); + + match status { + ProposalStatus::Approved => { + Self::finalize_execution(src_id, nonce, prop) + } + ProposalStatus::Rejected => { + Self::cancel_execution(src_id, nonce) + } + _ => Ok(()), + } + } else { + Err(Error::::ProposalDoesNotExist)? + } + } + + /// Commits a vote in favour of the proposal and executes it if the vote threshold is met. + fn vote_for( + who: T::AccountId, + nonce: u64, + src_id: u8, + prop: Box, + ) -> DispatchResult { + Self::commit_vote(who, nonce, src_id, prop.clone(), true)?; + Self::try_resolve_proposal(nonce, src_id, prop) + } + + /// Commits a vote against the proposal and cancels it if more than + /// (relayers.len() - threshold) votes against exist. + fn vote_against( + who: T::AccountId, + nonce: u64, + src_id: u8, + prop: Box, + ) -> DispatchResult { + Self::commit_vote(who, nonce, src_id, prop.clone(), false)?; + Self::try_resolve_proposal(nonce, src_id, prop) + } + + /// Execute the proposal and signals the result as an event + fn finalize_execution( + src_id: u8, + nonce: u64, + call: Box, + ) -> DispatchResult { + Self::deposit_event(Event::ProposalApproved(src_id, nonce)); + call.dispatch( + frame_system::RawOrigin::Signed(Self::account_id()).into(), + ) + .map(|_| ()) + .map_err(|e| e.error)?; + Self::deposit_event(Event::ProposalSucceeded(src_id, nonce)); + Ok(()) + } + + /// Cancels a proposal. + fn cancel_execution( + src_id: u8, + nonce: u64, + ) -> DispatchResult { + Self::deposit_event(Event::ProposalRejected(src_id, nonce)); + Ok(()) + } + + /// Initiates a transfer of a fungible asset out of the chain. This should be called by + /// another pallet + pub fn transfer_fungible( + dest_id: u8, + resource_id: [u8; 32], + to: Vec, + amount: U256, + ) -> DispatchResult { + ensure!( + Self::chain_whitelisted(dest_id), + Error::::ChainNotWhitelisted + ); + let nonce = Self::bump_nonce(dest_id); + >::append(BridgeEvent::FungibleTransfer( + dest_id, + nonce, + resource_id, + amount, + to.clone(), + )); + Self::deposit_event(Event::FungibleTransfer( + dest_id, + nonce, + resource_id, + amount, + to, + )); + Ok(()) + } + + /// Initiates a transfer of a nunfungible asset out of the chain. This should be called by + /// another pallet + pub fn transfer_nonfungible( + dest_id: u8, + resource_id: [u8; 32], + token_id: Vec, + to: Vec, + metadata: Vec, + ) -> DispatchResult { + ensure!( + Self::chain_whitelisted(dest_id), + Error::::ChainNotWhitelisted + ); + let nonce = Self::bump_nonce(dest_id); + >::append(BridgeEvent::NonFungibleTransfer( + dest_id, + nonce, + resource_id, + token_id.clone(), + to.clone(), + metadata.clone(), + )); + Self::deposit_event(Event::NonFungibleTransfer( + dest_id, + nonce, + resource_id, + token_id, + to, + metadata, + )); + Ok(()) + } + + /// Initiates a transfer of generic data out of the chain. This should be called by + /// another pallet. + pub fn transfer_generic( + dest_id: u8, + resource_id: [u8; 32], + metadata: Vec, + ) -> DispatchResult { + ensure!( + Self::chain_whitelisted(dest_id), + Error::::ChainNotWhitelisted + ); + let nonce = Self::bump_nonce(dest_id); + >::append(BridgeEvent::GenericTransfer( + dest_id, + nonce, + resource_id, + metadata.clone(), + )); + Self::deposit_event(Event::GenericTransfer( + dest_id, + nonce, + resource_id, + metadata, + )); + Ok(()) + } + } +} /// Helper function to concatenate a chain ID and some bytes to produce a resource ID. /// The common format is (31 bytes unique ID + 1 byte chain ID). pub fn derive_resource_id(chain: u8, id: &[u8]) -> [u8; 32] { - let mut r_id: [u8; 32] = [0; 32]; - r_id[31] = chain; // last byte is chain id - let range = if id.len() > 31 { 31 } else { id.len() }; // Use at most 31 bytes - for i in 0..range { - r_id[30 - i] = id[range - 1 - i]; // Ensure left padding for eth compatibility - } - return r_id; -} - -#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, scale_info::TypeInfo)] -pub enum ProposalStatus { - Initiated, - Approved, - Rejected, -} - -#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, scale_info::TypeInfo)] -pub struct ProposalVotes { - pub votes_for: Vec, - pub votes_against: Vec, - pub status: ProposalStatus, - pub expiry: BlockNumber, -} - -impl ProposalVotes { - /// Attempts to mark the proposal as approve or rejected. - /// Returns true if the status changes from active. - fn try_to_complete(&mut self, threshold: u32, total: u32) -> ProposalStatus { - if self.votes_for.len() >= threshold as usize { - self.status = ProposalStatus::Approved; - ProposalStatus::Approved - } else if total >= threshold && self.votes_against.len() as u32 + threshold > total { - self.status = ProposalStatus::Rejected; - ProposalStatus::Rejected - } else { - ProposalStatus::Initiated - } - } - - /// Returns true if the proposal has been rejected or approved, otherwise false. - fn is_complete(&self) -> bool { - self.status != ProposalStatus::Initiated - } - - /// Returns true if `who` has voted for or against the proposal - fn has_voted(&self, who: &A) -> bool { - self.votes_for.contains(&who) || self.votes_against.contains(&who) - } - - /// Return true if the expiry time has been reached - fn is_expired(&self, now: B) -> bool { - self.expiry <= now - } -} - -impl Default for ProposalVotes { - fn default() -> Self { - Self { - votes_for: vec![], - votes_against: vec![], - status: ProposalStatus::Initiated, - expiry: BlockNumber::default(), - } - } -} - -pub trait Config: system::Config { - /// The bridge's module id, used for deriving its sovereign account ID. - type PalletId: Get; - type Event: From> + Into<::Event>; - /// Origin used to administer the pallet - type BridgeCommitteeOrigin: EnsureOrigin; - /// Proposed dispatchable call - type Proposal: Parameter + Dispatchable + EncodeLike + GetDispatchInfo; - /// The identifier for this chain. - /// This must be unique and must not collide with existing IDs within a set of bridged chains. - type BridgeChainId: Get; - - type ProposalLifetime: Get; -} - -decl_event! { - pub enum Event where ::AccountId, ResourceId = [u8; 32] { - /// Vote threshold has changed (new_threshold) - RelayerThresholdChanged(u32), - /// Chain now available for transfers (chain_id) - ChainWhitelisted(u8), - /// Relayer added to set - RelayerAdded(AccountId), - /// Relayer removed from set - RelayerRemoved(AccountId), - /// FunglibleTransfer is for relaying fungibles (dest_id, nonce, resource_id, amount, recipient, metadata) - FungibleTransfer(u8, u64, ResourceId, U256, Vec), - /// NonFungibleTransfer is for relaying NFTS (dest_id, nonce, resource_id, token_id, recipient, metadata) - NonFungibleTransfer(u8, u64, ResourceId, Vec, Vec, Vec), - /// GenericTransfer is for a generic data payload (dest_id, nonce, resource_id, metadata) - GenericTransfer(u8, u64, ResourceId, Vec), - /// Vote submitted in favour of proposal - VoteFor(u8, u64, AccountId), - /// Vot submitted against proposal - VoteAgainst(u8, u64, AccountId), - /// Voting successful for a proposal - ProposalApproved(u8, u64), - /// Voting rejected a proposal - ProposalRejected(u8, u64), - /// Execution of call succeeded - ProposalSucceeded(u8, u64), - /// Execution of call failed - ProposalFailed(u8, u64), - } -} - -decl_error! { - pub enum Error for Module { - /// Relayer threshold not set - ThresholdNotSet, - /// Provided chain Id is not valid - InvalidChainId, - /// Relayer threshold cannot be 0 - InvalidThreshold, - /// Interactions with this chain is not permitted - ChainNotWhitelisted, - /// Chain has already been enabled - ChainAlreadyWhitelisted, - /// Resource ID provided isn't mapped to anything - ResourceDoesNotExist, - /// Relayer already in set - RelayerAlreadyExists, - /// Provided accountId is not a relayer - RelayerInvalid, - /// Protected operation, must be performed by relayer - MustBeRelayer, - /// Relayer has already submitted some vote for this proposal - RelayerAlreadyVoted, - /// A proposal with these parameters has already been submitted - ProposalAlreadyExists, - /// No proposal with the ID was found - ProposalDoesNotExist, - /// Cannot complete proposal, needs more votes - ProposalNotComplete, - /// Proposal has either failed or succeeded - ProposalAlreadyComplete, - /// Lifetime of proposal has been exceeded - ProposalExpired, - } -} - -#[derive(PartialEq, Eq, Clone, Encode, Decode, scale_info::TypeInfo, RuntimeDebug)] -pub enum BridgeEvent { - FungibleTransfer(u8, u64, [u8; 32], U256, Vec), - NonFungibleTransfer( - u8, - u64, - [u8; 32], - Vec, - Vec, - Vec, - ), - GenericTransfer(u8, u64, [u8; 32], Vec), -} - -decl_storage! { - trait Store for Module as ChainBridge { - /// All whitelisted chains and their respective transaction counts - ChainNonces get(fn chains): map hasher(opaque_blake2_256) u8 => Option; - - /// Number of votes required for a proposal to execute - RelayerThreshold get(fn relayer_threshold): u32 = DEFAULT_RELAYER_THRESHOLD; - - /// Tracks current relayer set - pub Relayers get(fn relayers): map hasher(opaque_blake2_256) T::AccountId => bool; - - /// Number of relayers in set - pub RelayerCount get(fn relayer_count): u32; - - /// All known proposals. - /// The key is the hash of the call and the deposit ID, to ensure it's unique. - pub Votes get(fn votes): - double_map hasher(opaque_blake2_256) u8, hasher(opaque_blake2_256) (u64, T::Proposal) - => Option>; - - /// Utilized by the bridge software to map resource IDs to actual methods - pub Resources get(fn resources): - map hasher(opaque_blake2_256) [u8; 32] => Option>; - - pub BridgeEvents get(fn bridge_events): Vec; - } -} - -decl_module! { - pub struct Module for enum Call where origin: T::Origin { - type Error = Error; - - const ChainIdentity: u8 = T::BridgeChainId::get(); - const ProposalLifetime: T::BlockNumber = T::ProposalLifetime::get(); - const BridgeAccountId: T::AccountId = T::PalletId::get().into_account_truncating(); - - fn deposit_event() = default; - - fn on_initialize(_n: T::BlockNumber) -> Weight { - // Clear all bridge transfer data - BridgeEvents::kill(); - 0 - } - - /// Sets the vote threshold for proposals. - /// - /// This threshold is used to determine how many votes are required - /// before a proposal is executed. - /// - /// # - /// - O(1) lookup and insert - /// # - #[weight = 195_000_000] - pub fn set_threshold(origin, threshold: u32) -> DispatchResult { - T::BridgeCommitteeOrigin::ensure_origin(origin)?; - Self::set_relayer_threshold(threshold) - } - - /// Stores a method name on chain under an associated resource ID. - /// - /// # - /// - O(1) write - /// # - #[weight = 195_000_000] - pub fn set_resource(origin, id: [u8; 32], method: Vec) -> DispatchResult { - T::BridgeCommitteeOrigin::ensure_origin(origin)?; - Self::register_resource(id, method) - } - - /// Removes a resource ID from the resource mapping. - /// - /// After this call, bridge transfers with the associated resource ID will - /// be rejected. - /// - /// # - /// - O(1) removal - /// # - #[weight = 195_000_000] - pub fn remove_resource(origin, id: [u8; 32]) -> DispatchResult { - T::BridgeCommitteeOrigin::ensure_origin(origin)?; - Self::unregister_resource(id) - } - - /// Enables a chain ID as a source or destination for a bridge transfer. - /// - /// # - /// - O(1) lookup and insert - /// # - #[weight = 195_000_000] - pub fn whitelist_chain(origin, id: u8) -> DispatchResult { - T::BridgeCommitteeOrigin::ensure_origin(origin)?; - Self::whitelist(id) - } - - /// Adds a new relayer to the relayer set. - /// - /// # - /// - O(1) lookup and insert - /// # - #[weight = 195_000_000] - pub fn add_relayer(origin, v: T::AccountId) -> DispatchResult { - T::BridgeCommitteeOrigin::ensure_origin(origin)?; - Self::register_relayer(v) - } - - /// Removes an existing relayer from the set. - /// - /// # - /// - O(1) lookup and removal - /// # - #[weight = 195_000_000] - pub fn remove_relayer(origin, v: T::AccountId) -> DispatchResult { - T::BridgeCommitteeOrigin::ensure_origin(origin)?; - Self::unregister_relayer(v) - } - - /// Commits a vote in favour of the provided proposal. - /// - /// If a proposal with the given nonce and source chain ID does not already exist, it will - /// be created with an initial vote in favour from the caller. - /// - /// # - /// - weight of proposed call, regardless of whether execution is performed - /// # - #[weight = (call.get_dispatch_info().weight + 195_000_000, call.get_dispatch_info().class, Pays::Yes)] - pub fn acknowledge_proposal(origin, nonce: u64, src_id: u8, r_id: [u8; 32], call: Box<::Proposal>) -> DispatchResult { - let who = ensure_signed(origin)?; - ensure!(Self::is_relayer(&who), Error::::MustBeRelayer); - ensure!(Self::chain_whitelisted(src_id), Error::::ChainNotWhitelisted); - ensure!(Self::resource_exists(r_id), Error::::ResourceDoesNotExist); - - Self::vote_for(who, nonce, src_id, call) - } - - /// Commits a vote against a provided proposal. - /// - /// # - /// - Fixed, since execution of proposal should not be included - /// # - #[weight = 195_000_000] - pub fn reject_proposal(origin, nonce: u64, src_id: u8, r_id: [u8; 32], call: Box<::Proposal>) -> DispatchResult { - let who = ensure_signed(origin)?; - ensure!(Self::is_relayer(&who), Error::::MustBeRelayer); - ensure!(Self::chain_whitelisted(src_id), Error::::ChainNotWhitelisted); - ensure!(Self::resource_exists(r_id), Error::::ResourceDoesNotExist); - - Self::vote_against(who, nonce, src_id, call) - } - - /// Evaluate the state of a proposal given the current vote threshold. - /// - /// A proposal with enough votes will be either executed or cancelled, and the status - /// will be updated accordingly. - /// - /// # - /// - weight of proposed call, regardless of whether execution is performed - /// # - #[weight = (prop.get_dispatch_info().weight + 195_000_000, prop.get_dispatch_info().class, Pays::Yes)] - pub fn eval_vote_state(origin, nonce: u64, src_id: u8, prop: Box<::Proposal>) -> DispatchResult { - ensure_signed(origin)?; - - Self::try_resolve_proposal(nonce, src_id, prop) - } - } -} - -impl Module { - // *** Utility methods *** - - /// Checks if who is a relayer - pub fn is_relayer(who: &T::AccountId) -> bool { - Self::relayers(who) - } - - /// Provides an AccountId for the pallet. - /// This is used both as an origin check and deposit/withdrawal account. - pub fn account_id() -> T::AccountId { - T::PalletId::get().into_account_truncating() - } - - /// Asserts if a resource is registered - pub fn resource_exists(id: [u8; 32]) -> bool { - return Self::resources(id) != None; - } - - /// Checks if a chain exists as a whitelisted destination - pub fn chain_whitelisted(id: u8) -> bool { - return Self::chains(id) != None; - } - - /// Increments the deposit nonce for the specified chain ID - fn bump_nonce(id: u8) -> u64 { - let nonce = Self::chains(id).unwrap_or_default() + 1; - ::insert(id, nonce); - nonce - } - - // *** Admin methods *** - - /// Set a new voting threshold - pub fn set_relayer_threshold(threshold: u32) -> DispatchResult { - ensure!(threshold > 0, Error::::InvalidThreshold); - ::put(threshold); - Self::deposit_event(RawEvent::RelayerThresholdChanged(threshold)); - Ok(()) - } - - /// Register a method for a resource Id, enabling associated transfers - pub fn register_resource(id: [u8; 32], method: Vec) -> DispatchResult { - ::insert(id, method); - Ok(()) - } - - /// Removes a resource ID, disabling associated transfer - pub fn unregister_resource(id: [u8; 32]) -> DispatchResult { - ::remove(id); - Ok(()) - } - - /// Whitelist a chain ID for transfer - pub fn whitelist(id: u8) -> DispatchResult { - // Cannot whitelist this chain - ensure!(id != T::BridgeChainId::get(), Error::::InvalidChainId); - // Cannot whitelist with an existing entry - ensure!( - !Self::chain_whitelisted(id), - Error::::ChainAlreadyWhitelisted - ); - ::insert(&id, 0); - Self::deposit_event(RawEvent::ChainWhitelisted(id)); - Ok(()) - } - - /// Adds a new relayer to the set - pub fn register_relayer(relayer: T::AccountId) -> DispatchResult { - ensure!( - !Self::is_relayer(&relayer), - Error::::RelayerAlreadyExists - ); - >::insert(&relayer, true); - ::mutate(|i| *i += 1); - - Self::deposit_event(RawEvent::RelayerAdded(relayer)); - Ok(()) - } - - /// Removes a relayer from the set - pub fn unregister_relayer(relayer: T::AccountId) -> DispatchResult { - ensure!(Self::is_relayer(&relayer), Error::::RelayerInvalid); - >::remove(&relayer); - ::mutate(|i| *i -= 1); - Self::deposit_event(RawEvent::RelayerRemoved(relayer)); - Ok(()) - } - - // *** Proposal voting and execution methods *** - - /// Commits a vote for a proposal. If the proposal doesn't exist it will be created. - fn commit_vote( - who: T::AccountId, - nonce: u64, - src_id: u8, - prop: Box, - in_favour: bool, - ) -> DispatchResult { - let now = >::block_number(); - let mut votes = match >::get(src_id, (nonce, prop.clone())) { - Some(v) => v, - None => { - let mut v = ProposalVotes::default(); - v.expiry = now + T::ProposalLifetime::get(); - v - } - }; - - // Ensure the proposal isn't complete and relayer hasn't already voted - ensure!(!votes.is_complete(), Error::::ProposalAlreadyComplete); - ensure!(!votes.is_expired(now), Error::::ProposalExpired); - ensure!(!votes.has_voted(&who), Error::::RelayerAlreadyVoted); - - if in_favour { - votes.votes_for.push(who.clone()); - Self::deposit_event(RawEvent::VoteFor(src_id, nonce, who.clone())); - } else { - votes.votes_against.push(who.clone()); - Self::deposit_event(RawEvent::VoteAgainst(src_id, nonce, who.clone())); - } - - >::insert(src_id, (nonce, prop.clone()), votes.clone()); - - Ok(()) - } - - /// Attempts to finalize or cancel the proposal if the vote count allows. - fn try_resolve_proposal( - nonce: u64, - src_id: u8, - prop: Box, - ) -> DispatchResult { - if let Some(mut votes) = >::get(src_id, (nonce, prop.clone())) { - let now = >::block_number(); - ensure!(!votes.is_complete(), Error::::ProposalAlreadyComplete); - ensure!(!votes.is_expired(now), Error::::ProposalExpired); - - let status = votes.try_to_complete(::get(), ::get()); - >::insert(src_id, (nonce, prop.clone()), votes.clone()); - - match status { - ProposalStatus::Approved => Self::finalize_execution(src_id, nonce, prop), - ProposalStatus::Rejected => Self::cancel_execution(src_id, nonce), - _ => Ok(()), - } - } else { - Err(Error::::ProposalDoesNotExist)? - } - } - - /// Commits a vote in favour of the proposal and executes it if the vote threshold is met. - fn vote_for( - who: T::AccountId, - nonce: u64, - src_id: u8, - prop: Box, - ) -> DispatchResult { - Self::commit_vote(who, nonce, src_id, prop.clone(), true)?; - Self::try_resolve_proposal(nonce, src_id, prop) - } - - /// Commits a vote against the proposal and cancels it if more than (relayers.len() - threshold) - /// votes against exist. - fn vote_against( - who: T::AccountId, - nonce: u64, - src_id: u8, - prop: Box, - ) -> DispatchResult { - Self::commit_vote(who, nonce, src_id, prop.clone(), false)?; - Self::try_resolve_proposal(nonce, src_id, prop) - } - - /// Execute the proposal and signals the result as an event - fn finalize_execution( - src_id: u8, - nonce: u64, - call: Box, - ) -> DispatchResult { - Self::deposit_event(RawEvent::ProposalApproved(src_id, nonce)); - call.dispatch(frame_system::RawOrigin::Signed(Self::account_id()).into()) - .map(|_| ()) - .map_err(|e| e.error)?; - Self::deposit_event(RawEvent::ProposalSucceeded(src_id, nonce)); - Ok(()) - } - - /// Cancels a proposal. - fn cancel_execution(src_id: u8, nonce: u64) -> DispatchResult { - Self::deposit_event(RawEvent::ProposalRejected(src_id, nonce)); - Ok(()) - } - - /// Initiates a transfer of a fungible asset out of the chain. This should be called by another pallet. - pub fn transfer_fungible( - dest_id: u8, - resource_id: [u8; 32], - to: Vec, - amount: U256, - ) -> DispatchResult { - ensure!( - Self::chain_whitelisted(dest_id), - Error::::ChainNotWhitelisted - ); - let nonce = Self::bump_nonce(dest_id); - - BridgeEvents::append(BridgeEvent::FungibleTransfer( - dest_id, - nonce, - resource_id, - amount, - to.clone(), - )); - Self::deposit_event(RawEvent::FungibleTransfer( - dest_id, - nonce, - resource_id, - amount, - to, - )); - Ok(()) - } - - /// Initiates a transfer of a nonfungible asset out of the chain. This should be called by another pallet. - pub fn transfer_nonfungible( - dest_id: u8, - resource_id: [u8; 32], - token_id: Vec, - to: Vec, - metadata: Vec, - ) -> DispatchResult { - ensure!( - Self::chain_whitelisted(dest_id), - Error::::ChainNotWhitelisted - ); - let nonce = Self::bump_nonce(dest_id); - BridgeEvents::append(BridgeEvent::NonFungibleTransfer( - dest_id, - nonce, - resource_id, - token_id.clone(), - to.clone(), - metadata.clone(), - )); - Self::deposit_event(RawEvent::NonFungibleTransfer( - dest_id, - nonce, - resource_id, - token_id, - to, - metadata, - )); - Ok(()) - } - - /// Initiates a transfer of generic data out of the chain. This should be called by another pallet. - pub fn transfer_generic( - dest_id: u8, - resource_id: [u8; 32], - metadata: Vec, - ) -> DispatchResult { - ensure!( - Self::chain_whitelisted(dest_id), - Error::::ChainNotWhitelisted - ); - let nonce = Self::bump_nonce(dest_id); - BridgeEvents::append(BridgeEvent::GenericTransfer( - dest_id, - nonce, - resource_id, - metadata.clone(), - )); - Self::deposit_event(RawEvent::GenericTransfer( - dest_id, - nonce, - resource_id, - metadata, - )); - Ok(()) - } + let mut r_id: [u8; 32] = [0; 32]; + r_id[31] = chain; // last byte is chain id + let range = if id.len() > 31 { 31 } else { id.len() }; // Use at most 31 bytes + for i in 0..range { + r_id[30 - i] = id[range - 1 - i]; // Ensure left padding for eth compatibility + } + r_id } /// Simple ensure origin for the bridge account pub struct EnsureBridge(sp_std::marker::PhantomData); + impl EnsureOrigin for EnsureBridge { - type Success = T::AccountId; - fn try_origin(o: T::Origin) -> Result { - let bridge_id = T::PalletId::get().into_account_truncating(); - o.into().and_then(|o| match o { - system::RawOrigin::Signed(who) if who == bridge_id => Ok(bridge_id), - r => Err(T::Origin::from(r)), - }) - } + type Success = T::AccountId; + + fn try_origin(o: T::Origin) -> Result { + let bridge_id = T::PalletId::get().into_account_truncating(); + o.into().and_then(|o| { + match o { + frame_system::RawOrigin::Signed(who) if who == bridge_id => { + Ok(bridge_id) + } + r => Err(T::Origin::from(r)), + } + }) + } + + /* + /// Returns an outer origin capable of passing `try_origin` check. + /// + /// ** Should be used for benchmarking only!!! ** + #[cfg(feature = "runtime-benchmarks")] + fn successful_origin() -> T::Origin { + T::Origin::from(frame_system::Origin::Signed(>::account_id())) + } + */ } diff --git a/crust-collator/pallets/bridge/src/mock.rs b/crust-collator/pallets/bridge/src/mock.rs index 2ac6fbc4..85ec3cb6 100644 --- a/crust-collator/pallets/bridge/src/mock.rs +++ b/crust-collator/pallets/bridge/src/mock.rs @@ -1,161 +1,182 @@ -// Copyright 2020 ChainSafe Systems -// SPDX-License-Identifier: LGPL-3.0-only - -#![cfg(test)] - -use super::*; - -use frame_support::{assert_ok, ord_parameter_types, parameter_types, weights::Weight}; -use frame_system::{self as system}; +// Copyright 2021 ChainSafe Systems +// SPDX-License-Identifier: GPL-3.0-only + +#![deny(warnings)] +use crate as pallet_chainbridge; +use frame_support::{ + assert_ok, + parameter_types, + traits::SortedMembers, + PalletId, +}; +use frame_system::EnsureSignedBy; +use pallet_chainbridge::{ + types::ChainId, + ResourceId, +}; use sp_core::H256; use sp_runtime::{ - testing::Header, - traits::{AccountIdConversion, BlakeTwo256, IdentityLookup}, - Perbill, + testing::Header, + traits::{ + BlakeTwo256, + IdentityLookup, + }, }; -use crate::{self as bridge, Config}; -pub use balances; +type Balance = u64; +type UncheckedExtrinsic = + frame_system::mocking::MockUncheckedExtrinsic; +type Block = frame_system::mocking::MockBlock; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; -type Block = frame_system::mocking::MockBlock; +// Constants definition +pub(crate) const RELAYER_A: u64 = 0x2; +pub(crate) const RELAYER_B: u64 = 0x3; +pub(crate) const RELAYER_C: u64 = 0x4; +pub(crate) const ENDOWED_BALANCE: u64 = 100_000_000; +pub(crate) const TEST_THRESHOLD: u32 = 2; // 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}, - Balances: balances::{Pallet, Call, Storage, Config, Event}, - Bridge: bridge::{Pallet, Call, Storage, Event}, - } + pub enum MockRuntime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + + System: frame_system::{Pallet, Call, Config, Storage, Event}, + Bridge: pallet_chainbridge::{Pallet, Call, Storage, Event}, + Balances: pallet_balances::{Pallet, Call, Config, Storage, Event}, + } ); parameter_types! { - pub const BlockHashCount: u64 = 250; - pub const MaximumBlockWeight: Weight = 1024; - pub const MaximumBlockLength: u32 = 2 * 1024; - pub const AvailableBlockRatio: Perbill = Perbill::one(); - pub const MaxLocks: u32 = 100; + pub const BlockHashCount: u64 = 250; + pub const SS58Prefix: u8 = 42; } -impl frame_system::Config for Test { - type BaseCallFilter = (); - 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 = BlockHashCount; - type DbWeight = (); - type Version = (); - type AccountData = balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type PalletInfo = PalletInfo; - type BlockWeights = (); - type BlockLength = (); - type SS58Prefix = (); +// Implement FRAME balances pallet configuration trait for the mock runtime +impl pallet_balances::Config for MockRuntime { + type AccountStore = System; + type Balance = Balance; + type DustRemoval = (); + type Event = Event; + type ExistentialDeposit = ExistentialDeposit; + type MaxLocks = (); + type MaxReserves = (); + type ReserveIdentifier = (); + type WeightInfo = (); } -parameter_types! { - pub const ExistentialDeposit: u64 = 1; +impl frame_system::Config for MockRuntime { + type AccountData = pallet_balances::AccountData; + type AccountId = u64; + type BaseCallFilter = frame_support::traits::Everything; + type BlockHashCount = BlockHashCount; + type BlockLength = (); + type BlockNumber = u64; + 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 = SS58Prefix; + type SystemWeightInfo = (); + type Version = (); } -ord_parameter_types! { - pub const One: u64 = 1; +// Parameterize default test user identifier (with id 1) +parameter_types! { + pub const TestUserId: u64 = 1; + pub const TestChainId: ChainId = 5; + pub const ProposalLifetime: u64 = 50; + pub const ChainBridgePalletId: PalletId = PalletId(*b"chnbrdge"); } -impl balances::Config for Test { - type Balance = u64; - type DustRemoval = (); - type Event = Event; - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; - type WeightInfo = (); - type MaxLocks = (); +impl SortedMembers for TestUserId { + fn sorted_members() -> Vec { + vec![1] + } } +// Parameterize FRAME balances pallet parameter_types! { - pub const TestChainId: u8 = 5; - pub const ProposalLifetime: u64 = 50; - pub const BridgeClaimsPalletId: PalletId = PalletId(*b"crclaims"); + pub const ExistentialDeposit: u64 = 1; } -impl Config for Test { - type PalletId = BridgeClaimsPalletId; - type Event = Event; - type BridgeCommitteeOrigin = frame_system::EnsureRoot; - type Proposal = Call; - type BridgeChainId = TestChainId; - type ProposalLifetime = ProposalLifetime; +impl pallet_chainbridge::Config for MockRuntime { + type BridgeCommitteeOrigin = EnsureSignedBy; + type BridgeChainId = TestChainId; + type Event = Event; + type PalletId = ChainBridgePalletId; + type Proposal = Call; + type ProposalLifetime = ProposalLifetime; } -// pub const BRIDGE_ID: u64 = -pub const RELAYER_A: u64 = 0x2; -pub const RELAYER_B: u64 = 0x3; -pub const RELAYER_C: u64 = 0x4; -pub const ENDOWED_BALANCE: u64 = 100_000_000; -pub const TEST_THRESHOLD: u32 = 2; - pub fn new_test_ext() -> sp_io::TestExternalities { - let bridge_id = PalletId(*b"crust/bg").into_account_truncating(); - let mut t = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); - balances::GenesisConfig:: { - balances: vec![(bridge_id, ENDOWED_BALANCE)], - } - .assimilate_storage(&mut t) - .unwrap(); - let mut ext = sp_io::TestExternalities::new(t); - ext.execute_with(|| System::set_block_number(1)); - ext + let bridge_id = Bridge::account_id(); + let mut t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); + pallet_balances::GenesisConfig:: { + balances: vec![(bridge_id, ENDOWED_BALANCE)], + } + .assimilate_storage(&mut t) + .unwrap(); + let mut ext = sp_io::TestExternalities::new(t); + // Note: when block_number is not set, the events will not be stored + ext.execute_with(|| System::set_block_number(1)); + ext } pub fn new_test_ext_initialized( - src_id: u8, - r_id: [u8; 32], - resource: Vec, + src_id: ChainId, + r_id: ResourceId, + resource: Vec, ) -> sp_io::TestExternalities { - let mut t = new_test_ext(); - t.execute_with(|| { - // Set and check threshold - assert_ok!(Bridge::set_threshold(Origin::root(), TEST_THRESHOLD)); - assert_eq!(Bridge::relayer_threshold(), TEST_THRESHOLD); - // Add relayers - assert_ok!(Bridge::add_relayer(Origin::root(), RELAYER_A)); - assert_ok!(Bridge::add_relayer(Origin::root(), RELAYER_B)); - assert_ok!(Bridge::add_relayer(Origin::root(), RELAYER_C)); - // Whitelist chain - assert_ok!(Bridge::whitelist_chain(Origin::root(), src_id)); - // Set and check resource ID mapped to some junk data - assert_ok!(Bridge::set_resource(Origin::root(), r_id, resource)); - assert_eq!(Bridge::resource_exists(r_id), true); - }); - t + let mut t = new_test_ext(); + t.execute_with(|| { + // Set and check threshold + assert_ok!(Bridge::set_threshold( + crate::mock::Origin::root(), + TEST_THRESHOLD + )); + assert_eq!(Bridge::relayer_threshold(), TEST_THRESHOLD); + // Add relayers + assert_ok!(Bridge::add_relayer(Origin::root(), RELAYER_A)); + assert_ok!(Bridge::add_relayer(Origin::root(), RELAYER_B)); + assert_ok!(Bridge::add_relayer(Origin::root(), RELAYER_C)); + // Whitelist chain + assert_ok!(Bridge::whitelist_chain(Origin::root(), src_id)); + // Set and check resource ID mapped to some junk data + assert_ok!(Bridge::set_resource(Origin::root(), r_id, resource)); + assert_eq!(Bridge::resource_exists(r_id), true); + }); + t } // Checks events against the latest. A contiguous set of events must be provided. They must // include the most recent event, but do not have to include every past event. pub fn assert_events(mut expected: Vec) { - let mut actual: Vec = system::Pallet::::events() - .iter() - .map(|e| e.event.clone()) - .collect(); - - expected.reverse(); - - for evt in expected { - let next = actual.pop().expect("event expected"); - assert_eq!(next, evt.into(), "Events don't match (actual,expected)"); - } + let mut actual: Vec = frame_system::Pallet::::events() + .iter() + .map(|e| e.event.clone()) + .collect(); + dbg!(&actual); + + expected.reverse(); + + for evt in expected { + dbg!(&evt); + let next = actual.pop().expect("event expected"); + assert_eq!(next, evt.into(), "Events don't match (actual,expected)"); + } } diff --git a/crust-collator/pallets/bridge/src/tests.rs b/crust-collator/pallets/bridge/src/tests.rs index 24c7e435..8d175d3e 100644 --- a/crust-collator/pallets/bridge/src/tests.rs +++ b/crust-collator/pallets/bridge/src/tests.rs @@ -1,537 +1,685 @@ -// Copyright 2020 ChainSafe Systems -// SPDX-License-Identifier: LGPL-3.0-only - -#![cfg(test)] - -use super::mock::{ - assert_events, new_test_ext, Balances, Bridge, Call, Event, Origin, ProposalLifetime, System, - Test, TestChainId, ENDOWED_BALANCE, RELAYER_A, RELAYER_B, RELAYER_C, TEST_THRESHOLD, +// Copyright 2021 ChainSafe Systems +// SPDX-License-Identifier: GPL-3.0-only + +#![deny(warnings)] +use crate as pallet_chainbridge; +use frame_support::{ + assert_noop, + assert_ok, }; -use super::*; -use crate::mock::new_test_ext_initialized; -use frame_support::{assert_noop, assert_ok}; +use pallet_chainbridge::{ + derive_resource_id, + mock, + mock::{ + assert_events, + new_test_ext, + new_test_ext_initialized, + Bridge, + MockRuntime, + Origin, + ProposalLifetime, + TestChainId, + ENDOWED_BALANCE, + RELAYER_A, + RELAYER_B, + RELAYER_C, + TEST_THRESHOLD, + }, + types::{ + ProposalStatus, + ProposalVotes, + }, + Error, + RelayerThreshold, + ResourceId, +}; +use sp_core::U256; #[test] fn derive_ids() { - let chain = 1; - let id = [ - 0x21, 0x60, 0x5f, 0x71, 0x84, 0x5f, 0x37, 0x2a, 0x9e, 0xd8, 0x42, 0x53, 0xd2, 0xd0, 0x24, - 0xb7, 0xb1, 0x09, 0x99, 0xf4, - ]; - let r_id = derive_resource_id(chain, &id); - let expected = [ - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x21, 0x60, 0x5f, 0x71, 0x84, 0x5f, - 0x37, 0x2a, 0x9e, 0xd8, 0x42, 0x53, 0xd2, 0xd0, 0x24, 0xb7, 0xb1, 0x09, 0x99, 0xf4, chain, - ]; - assert_eq!(r_id, expected); + let chain = 1; + let id = [ + 0x21, 0x60, 0x5f, 0x71, 0x84, 0x5f, 0x37, 0x2a, 0x9e, 0xd8, 0x42, 0x53, + 0xd2, 0xd0, 0x24, 0xb7, 0xb1, 0x09, 0x99, 0xf4, + ]; + let r_id = derive_resource_id(chain, &id); + let expected = [ + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x21, 0x60, + 0x5f, 0x71, 0x84, 0x5f, 0x37, 0x2a, 0x9e, 0xd8, 0x42, 0x53, 0xd2, 0xd0, + 0x24, 0xb7, 0xb1, 0x09, 0x99, 0xf4, chain, + ]; + assert_eq!(r_id, expected); } #[test] fn complete_proposal_approved() { - let mut prop = ProposalVotes { - votes_for: vec![1, 2], - votes_against: vec![3], - status: ProposalStatus::Initiated, - expiry: ProposalLifetime::get(), - }; - - prop.try_to_complete(2, 3); - assert_eq!(prop.status, ProposalStatus::Approved); + let mut prop = ProposalVotes { + votes_for: vec![1, 2], + votes_against: vec![3], + status: ProposalStatus::Initiated, + expiry: ProposalLifetime::get(), + }; + + prop.try_to_complete(2, 3); + assert_eq!(prop.status, ProposalStatus::Approved); } #[test] fn complete_proposal_rejected() { - let mut prop = ProposalVotes { - votes_for: vec![1], - votes_against: vec![2, 3], - status: ProposalStatus::Initiated, - expiry: ProposalLifetime::get(), - }; - - prop.try_to_complete(2, 3); - assert_eq!(prop.status, ProposalStatus::Rejected); + let mut prop = ProposalVotes { + votes_for: vec![1], + votes_against: vec![2, 3], + status: ProposalStatus::Initiated, + expiry: ProposalLifetime::get(), + }; + + prop.try_to_complete(2, 3); + assert_eq!(prop.status, ProposalStatus::Rejected); } #[test] fn complete_proposal_bad_threshold() { - let mut prop = ProposalVotes { - votes_for: vec![1, 2], - votes_against: vec![], - status: ProposalStatus::Initiated, - expiry: ProposalLifetime::get(), - }; - - prop.try_to_complete(3, 2); - assert_eq!(prop.status, ProposalStatus::Initiated); - - let mut prop = ProposalVotes { - votes_for: vec![], - votes_against: vec![1, 2], - status: ProposalStatus::Initiated, - expiry: ProposalLifetime::get(), - }; - - prop.try_to_complete(3, 2); - assert_eq!(prop.status, ProposalStatus::Initiated); + let mut prop = ProposalVotes { + votes_for: vec![1, 2], + votes_against: vec![], + status: ProposalStatus::Initiated, + expiry: ProposalLifetime::get(), + }; + + prop.try_to_complete(3, 2); + assert_eq!(prop.status, ProposalStatus::Initiated); + + let mut prop = ProposalVotes { + votes_for: vec![], + votes_against: vec![1, 2], + status: ProposalStatus::Initiated, + expiry: ProposalLifetime::get(), + }; + + prop.try_to_complete(3, 2); + assert_eq!(prop.status, ProposalStatus::Initiated); } #[test] fn setup_resources() { - new_test_ext().execute_with(|| { - let id: [u8; 32] = [1; 32]; - let method = "Pallet.do_something".as_bytes().to_vec(); - let method2 = "Pallet.do_somethingElse".as_bytes().to_vec(); + new_test_ext().execute_with(|| { + let id: ResourceId = [1; 32]; + let method = "Pallet.do_something".as_bytes().to_vec(); + let method2 = "Pallet.do_somethingElse".as_bytes().to_vec(); - assert_ok!(Bridge::set_resource(Origin::root(), id, method.clone())); - assert_eq!(Bridge::resources(id), Some(method)); + assert_ok!(Bridge::set_resource(Origin::root(), id, method.clone())); + assert_eq!(Bridge::resources(id), Some(method)); - assert_ok!(Bridge::set_resource(Origin::root(), id, method2.clone())); - assert_eq!(Bridge::resources(id), Some(method2)); + assert_ok!(Bridge::set_resource(Origin::root(), id, method2.clone())); + assert_eq!(Bridge::resources(id), Some(method2)); - assert_ok!(Bridge::remove_resource(Origin::root(), id)); - assert_eq!(Bridge::resources(id), None); - }) + assert_ok!(Bridge::remove_resource(Origin::root(), id)); + assert_eq!(Bridge::resources(id), None); + }) } #[test] fn whitelist_chain() { - new_test_ext().execute_with(|| { - assert!(!Bridge::chain_whitelisted(0)); - - assert_ok!(Bridge::whitelist_chain(Origin::root(), 0)); - assert_noop!( - Bridge::whitelist_chain(Origin::root(), TestChainId::get()), - Error::::InvalidChainId - ); - - assert_events(vec![Event::bridge(RawEvent::ChainWhitelisted(0))]); - }) + new_test_ext().execute_with(|| { + assert!(!Bridge::chain_whitelisted(0)); + + assert_ok!(Bridge::whitelist_chain(Origin::root(), 0)); + assert_noop!( + Bridge::whitelist_chain(Origin::root(), TestChainId::get()), + Error::::InvalidChainId + ); + + assert_events(vec![mock::Event::Bridge(pallet_chainbridge::Event::< + MockRuntime, + >::ChainWhitelisted(0))]); + }) } #[test] fn set_get_threshold() { - new_test_ext().execute_with(|| { - assert_eq!(::get(), 1); - - assert_ok!(Bridge::set_threshold(Origin::root(), TEST_THRESHOLD)); - assert_eq!(::get(), TEST_THRESHOLD); - - assert_ok!(Bridge::set_threshold(Origin::root(), 5)); - assert_eq!(::get(), 5); - - assert_events(vec![ - Event::bridge(RawEvent::RelayerThresholdChanged(TEST_THRESHOLD)), - Event::bridge(RawEvent::RelayerThresholdChanged(5)), - ]); - }) + new_test_ext().execute_with(|| { + assert_eq!(>::get(), 1); + + assert_ok!(Bridge::set_threshold(Origin::root(), TEST_THRESHOLD)); + assert_eq!(>::get(), TEST_THRESHOLD); + + assert_ok!(Bridge::set_threshold(Origin::root(), 5)); + assert_eq!(>::get(), 5); + + assert_events(vec![ + mock::Event::Bridge( + pallet_chainbridge::Event::::RelayerThresholdChanged( + TEST_THRESHOLD, + ), + ), + mock::Event::Bridge( + pallet_chainbridge::Event::::RelayerThresholdChanged(5), + ), + ]); + }) } #[test] fn asset_transfer_success() { - new_test_ext().execute_with(|| { - let dest_id = 2; - let to = vec![2]; - let resource_id = [1; 32]; - let metadata = vec![]; - let amount = 100; - let token_id = vec![1, 2, 3, 4]; - - assert_ok!(Bridge::set_threshold(Origin::root(), TEST_THRESHOLD,)); - - assert_ok!(Bridge::whitelist_chain(Origin::root(), dest_id.clone())); - assert_ok!(Bridge::transfer_fungible( - dest_id.clone(), - resource_id.clone(), - to.clone(), - amount.into() - )); - assert_events(vec![ - Event::bridge(RawEvent::ChainWhitelisted(dest_id.clone())), - Event::bridge(RawEvent::FungibleTransfer( - dest_id.clone(), - 1, - resource_id.clone(), - amount.into(), - to.clone(), - )), - ]); - - assert_ok!(Bridge::transfer_nonfungible( - dest_id.clone(), - resource_id.clone(), - token_id.clone(), - to.clone(), - metadata.clone() - )); - assert_events(vec![Event::bridge(RawEvent::NonFungibleTransfer( - dest_id.clone(), - 2, - resource_id.clone(), - token_id, - to.clone(), - metadata.clone(), - ))]); - - assert_ok!(Bridge::transfer_generic( - dest_id.clone(), - resource_id.clone(), - metadata.clone() - )); - assert_events(vec![Event::bridge(RawEvent::GenericTransfer( - dest_id.clone(), - 3, - resource_id, - metadata, - ))]); - }) + new_test_ext().execute_with(|| { + let dest_id = 2; + let to = vec![2]; + let resource_id = [1; 32]; + let metadata = vec![]; + let amount = 100; + let token_id = vec![1, 2, 3, 4]; + + assert_ok!(Bridge::set_threshold(Origin::root(), TEST_THRESHOLD,)); + + assert_ok!(Bridge::whitelist_chain(Origin::root(), dest_id.clone())); + assert_ok!(Bridge::transfer_fungible( + dest_id.clone(), + resource_id.clone(), + to.clone(), + amount.into() + )); + assert_events(vec![ + mock::Event::Bridge( + pallet_chainbridge::Event::::ChainWhitelisted( + dest_id.clone(), + ), + ), + mock::Event::Bridge( + pallet_chainbridge::Event::::FungibleTransfer( + dest_id.clone(), + 1, + resource_id.clone(), + amount.into(), + to.clone(), + ), + ), + ]); + + assert_ok!(Bridge::transfer_nonfungible( + dest_id.clone(), + resource_id.clone(), + token_id.clone(), + to.clone(), + metadata.clone() + )); + assert_events(vec![mock::Event::Bridge(pallet_chainbridge::Event::< + MockRuntime, + >::NonFungibleTransfer( + dest_id.clone(), + 2, + resource_id.clone(), + token_id, + to.clone(), + metadata.clone(), + ))]); + + assert_ok!(Bridge::transfer_generic( + dest_id.clone(), + resource_id.clone(), + metadata.clone() + )); + assert_events(vec![mock::Event::Bridge(pallet_chainbridge::Event::< + MockRuntime, + >::GenericTransfer( + dest_id.clone(), + 3, + resource_id, + metadata, + ))]); + }) } #[test] fn asset_transfer_invalid_chain() { - new_test_ext().execute_with(|| { - let chain_id = 2; - let bad_dest_id = 3; - let resource_id = [4; 32]; - - assert_ok!(Bridge::whitelist_chain(Origin::root(), chain_id.clone())); - assert_events(vec![Event::bridge(RawEvent::ChainWhitelisted( - chain_id.clone(), - ))]); - - assert_noop!( - Bridge::transfer_fungible(bad_dest_id, resource_id.clone(), vec![], U256::zero()), - Error::::ChainNotWhitelisted - ); - - assert_noop!( - Bridge::transfer_nonfungible(bad_dest_id, resource_id.clone(), vec![], vec![], vec![]), - Error::::ChainNotWhitelisted - ); - - assert_noop!( - Bridge::transfer_generic(bad_dest_id, resource_id.clone(), vec![]), - Error::::ChainNotWhitelisted - ); - }) + new_test_ext().execute_with(|| { + let chain_id = 2; + let bad_dest_id = 3; + let resource_id = [4; 32]; + + assert_ok!(Bridge::whitelist_chain(Origin::root(), chain_id.clone())); + assert_events(vec![mock::Event::Bridge(pallet_chainbridge::Event::< + MockRuntime, + >::ChainWhitelisted( + chain_id.clone() + ))]); + + assert_noop!( + Bridge::transfer_fungible( + bad_dest_id, + resource_id.clone(), + vec![], + U256::zero() + ), + Error::::ChainNotWhitelisted + ); + + assert_noop!( + Bridge::transfer_nonfungible( + bad_dest_id, + resource_id.clone(), + vec![], + vec![], + vec![] + ), + Error::::ChainNotWhitelisted + ); + + assert_noop!( + Bridge::transfer_generic(bad_dest_id, resource_id.clone(), vec![]), + Error::::ChainNotWhitelisted + ); + }) } #[test] fn add_remove_relayer() { - new_test_ext().execute_with(|| { - assert_ok!(Bridge::set_threshold(Origin::root(), TEST_THRESHOLD,)); - assert_eq!(Bridge::relayer_count(), 0); - - assert_ok!(Bridge::add_relayer(Origin::root(), RELAYER_A)); - assert_ok!(Bridge::add_relayer(Origin::root(), RELAYER_B)); - assert_ok!(Bridge::add_relayer(Origin::root(), RELAYER_C)); - assert_eq!(Bridge::relayer_count(), 3); - - // Already exists - assert_noop!( - Bridge::add_relayer(Origin::root(), RELAYER_A), - Error::::RelayerAlreadyExists - ); - - // Confirm removal - assert_ok!(Bridge::remove_relayer(Origin::root(), RELAYER_B)); - assert_eq!(Bridge::relayer_count(), 2); - assert_noop!( - Bridge::remove_relayer(Origin::root(), RELAYER_B), - Error::::RelayerInvalid - ); - assert_eq!(Bridge::relayer_count(), 2); - - assert_events(vec![ - Event::bridge(RawEvent::RelayerAdded(RELAYER_A)), - Event::bridge(RawEvent::RelayerAdded(RELAYER_B)), - Event::bridge(RawEvent::RelayerAdded(RELAYER_C)), - Event::bridge(RawEvent::RelayerRemoved(RELAYER_B)), - ]); - }) + new_test_ext().execute_with(|| { + assert_ok!(Bridge::set_threshold(Origin::root(), TEST_THRESHOLD,)); + assert_eq!(Bridge::relayer_count(), 0); + + assert_ok!(Bridge::add_relayer(Origin::root(), RELAYER_A)); + assert_ok!(Bridge::add_relayer(Origin::root(), RELAYER_B)); + assert_ok!(Bridge::add_relayer(Origin::root(), RELAYER_C)); + assert_eq!(Bridge::relayer_count(), 3); + + // Already exists + assert_noop!( + Bridge::add_relayer(Origin::root(), RELAYER_A), + Error::::RelayerAlreadyExists + ); + + // Confirm removal + assert_ok!(Bridge::remove_relayer(Origin::root(), RELAYER_B)); + assert_eq!(Bridge::relayer_count(), 2); + assert_noop!( + Bridge::remove_relayer(Origin::root(), RELAYER_B), + Error::::RelayerInvalid + ); + assert_eq!(Bridge::relayer_count(), 2); + + assert_events(vec![ + mock::Event::Bridge( + pallet_chainbridge::Event::::RelayerAdded( + RELAYER_A, + ), + ), + mock::Event::Bridge( + pallet_chainbridge::Event::::RelayerAdded( + RELAYER_B, + ), + ), + mock::Event::Bridge( + pallet_chainbridge::Event::::RelayerAdded( + RELAYER_C, + ), + ), + mock::Event::Bridge( + pallet_chainbridge::Event::::RelayerRemoved( + RELAYER_B, + ), + ), + ]); + }) } fn make_proposal(r: Vec) -> mock::Call { - Call::System(system::Call::remark(r)) + mock::Call::System(frame_system::Call::remark { remark: r }) } #[test] fn create_sucessful_proposal() { - let src_id = 1; - let r_id = derive_resource_id(src_id, b"remark"); - - new_test_ext_initialized(src_id, r_id, b"System.remark".to_vec()).execute_with(|| { - let prop_id = 1; - let proposal = make_proposal(vec![10]); - - // Create proposal (& vote) - assert_ok!(Bridge::acknowledge_proposal( - Origin::signed(RELAYER_A), - prop_id, - src_id, - r_id, - Box::new(proposal.clone()) - )); - let prop = Bridge::votes(src_id, (prop_id.clone(), proposal.clone())).unwrap(); - let expected = ProposalVotes { - votes_for: vec![RELAYER_A], - votes_against: vec![], - status: ProposalStatus::Initiated, - expiry: ProposalLifetime::get() + 1, - }; - assert_eq!(prop, expected); - - // Second relayer votes against - assert_ok!(Bridge::reject_proposal( - Origin::signed(RELAYER_B), - prop_id, - src_id, - r_id, - Box::new(proposal.clone()) - )); - let prop = Bridge::votes(src_id, (prop_id.clone(), proposal.clone())).unwrap(); - let expected = ProposalVotes { - votes_for: vec![RELAYER_A], - votes_against: vec![RELAYER_B], - status: ProposalStatus::Initiated, - expiry: ProposalLifetime::get() + 1, - }; - assert_eq!(prop, expected); - - // Third relayer votes in favour - assert_ok!(Bridge::acknowledge_proposal( - Origin::signed(RELAYER_C), - prop_id, - src_id, - r_id, - Box::new(proposal.clone()) - )); - let prop = Bridge::votes(src_id, (prop_id.clone(), proposal.clone())).unwrap(); - let expected = ProposalVotes { - votes_for: vec![RELAYER_A, RELAYER_C], - votes_against: vec![RELAYER_B], - status: ProposalStatus::Approved, - expiry: ProposalLifetime::get() + 1, - }; - assert_eq!(prop, expected); - - assert_events(vec![ - Event::bridge(RawEvent::VoteFor(src_id, prop_id, RELAYER_A)), - Event::bridge(RawEvent::VoteAgainst(src_id, prop_id, RELAYER_B)), - Event::bridge(RawEvent::VoteFor(src_id, prop_id, RELAYER_C)), - Event::bridge(RawEvent::ProposalApproved(src_id, prop_id)), - Event::bridge(RawEvent::ProposalSucceeded(src_id, prop_id)), - ]); - }) + let src_id = 1; + let r_id = derive_resource_id(src_id, b"remark"); + + new_test_ext_initialized(src_id, r_id, b"System.remark".to_vec()) + .execute_with(|| { + let prop_id = 1; + let proposal = make_proposal(vec![10]); + + // Create proposal (& vote) + assert_ok!(Bridge::acknowledge_proposal( + Origin::signed(RELAYER_A), + prop_id, + src_id, + r_id, + Box::new(proposal.clone()) + )); + let prop = + Bridge::get_votes(src_id, (prop_id.clone(), proposal.clone())) + .unwrap(); + let expected = ProposalVotes { + votes_for: vec![RELAYER_A], + votes_against: vec![], + status: ProposalStatus::Initiated, + expiry: ProposalLifetime::get() + 1, + }; + assert_eq!(prop, expected); + + // Second relayer votes against + assert_ok!(Bridge::reject_proposal( + Origin::signed(RELAYER_B), + prop_id, + src_id, + r_id, + Box::new(proposal.clone()) + )); + let prop = + Bridge::get_votes(src_id, (prop_id.clone(), proposal.clone())) + .unwrap(); + let expected = ProposalVotes { + votes_for: vec![RELAYER_A], + votes_against: vec![RELAYER_B], + status: ProposalStatus::Initiated, + expiry: ProposalLifetime::get() + 1, + }; + assert_eq!(prop, expected); + + // Third relayer votes in favour + assert_ok!(Bridge::acknowledge_proposal( + Origin::signed(RELAYER_C), + prop_id, + src_id, + r_id, + Box::new(proposal.clone()) + )); + let prop = + Bridge::get_votes(src_id, (prop_id.clone(), proposal.clone())) + .unwrap(); + let expected = ProposalVotes { + votes_for: vec![RELAYER_A, RELAYER_C], + votes_against: vec![RELAYER_B], + status: ProposalStatus::Approved, + expiry: ProposalLifetime::get() + 1, + }; + assert_eq!(prop, expected); + + assert_events(vec![ + mock::Event::Bridge( + pallet_chainbridge::Event::::VoteFor( + src_id, prop_id, RELAYER_A, + ), + ), + mock::Event::Bridge( + pallet_chainbridge::Event::::VoteAgainst( + src_id, prop_id, RELAYER_B, + ), + ), + mock::Event::Bridge( + pallet_chainbridge::Event::::VoteFor( + src_id, prop_id, RELAYER_C, + ), + ), + mock::Event::Bridge( + pallet_chainbridge::Event::::ProposalApproved( + src_id, prop_id, + ), + ), + mock::Event::Bridge( + pallet_chainbridge::Event::::ProposalSucceeded( + src_id, prop_id, + ), + ), + ]); + }) } #[test] fn create_unsucessful_proposal() { - let src_id = 1; - let r_id = derive_resource_id(src_id, b"transfer"); - - new_test_ext_initialized(src_id, r_id, b"System.remark".to_vec()).execute_with(|| { - let prop_id = 1; - let proposal = make_proposal(vec![11]); - - // Create proposal (& vote) - assert_ok!(Bridge::acknowledge_proposal( - Origin::signed(RELAYER_A), - prop_id, - src_id, - r_id, - Box::new(proposal.clone()) - )); - let prop = Bridge::votes(src_id, (prop_id.clone(), proposal.clone())).unwrap(); - let expected = ProposalVotes { - votes_for: vec![RELAYER_A], - votes_against: vec![], - status: ProposalStatus::Initiated, - expiry: ProposalLifetime::get() + 1, - }; - assert_eq!(prop, expected); - - // Second relayer votes against - assert_ok!(Bridge::reject_proposal( - Origin::signed(RELAYER_B), - prop_id, - src_id, - r_id, - Box::new(proposal.clone()) - )); - let prop = Bridge::votes(src_id, (prop_id.clone(), proposal.clone())).unwrap(); - let expected = ProposalVotes { - votes_for: vec![RELAYER_A], - votes_against: vec![RELAYER_B], - status: ProposalStatus::Initiated, - expiry: ProposalLifetime::get() + 1, - }; - assert_eq!(prop, expected); - - // Third relayer votes against - assert_ok!(Bridge::reject_proposal( - Origin::signed(RELAYER_C), - prop_id, - src_id, - r_id, - Box::new(proposal.clone()) - )); - let prop = Bridge::votes(src_id, (prop_id.clone(), proposal.clone())).unwrap(); - let expected = ProposalVotes { - votes_for: vec![RELAYER_A], - votes_against: vec![RELAYER_B, RELAYER_C], - status: ProposalStatus::Rejected, - expiry: ProposalLifetime::get() + 1, - }; - assert_eq!(prop, expected); - - assert_eq!(Balances::free_balance(RELAYER_B), 0); - assert_eq!( - Balances::free_balance(Bridge::account_id()), - ENDOWED_BALANCE - ); - - assert_events(vec![ - Event::bridge(RawEvent::VoteFor(src_id, prop_id, RELAYER_A)), - Event::bridge(RawEvent::VoteAgainst(src_id, prop_id, RELAYER_B)), - Event::bridge(RawEvent::VoteAgainst(src_id, prop_id, RELAYER_C)), - Event::bridge(RawEvent::ProposalRejected(src_id, prop_id)), - ]); - }) + let src_id = 1; + let r_id = derive_resource_id(src_id, b"transfer"); + + new_test_ext_initialized(src_id, r_id, b"System.remark".to_vec()) + .execute_with(|| { + let prop_id = 1; + let proposal = make_proposal(vec![11]); + + // Create proposal (& vote) + assert_ok!(Bridge::acknowledge_proposal( + Origin::signed(RELAYER_A), + prop_id, + src_id, + r_id, + Box::new(proposal.clone()) + )); + let prop = + Bridge::get_votes(src_id, (prop_id.clone(), proposal.clone())) + .unwrap(); + let expected = ProposalVotes { + votes_for: vec![RELAYER_A], + votes_against: vec![], + status: ProposalStatus::Initiated, + expiry: ProposalLifetime::get() + 1, + }; + assert_eq!(prop, expected); + + // Second relayer votes against + assert_ok!(Bridge::reject_proposal( + Origin::signed(RELAYER_B), + prop_id, + src_id, + r_id, + Box::new(proposal.clone()) + )); + let prop = + Bridge::get_votes(src_id, (prop_id.clone(), proposal.clone())) + .unwrap(); + let expected = ProposalVotes { + votes_for: vec![RELAYER_A], + votes_against: vec![RELAYER_B], + status: ProposalStatus::Initiated, + expiry: ProposalLifetime::get() + 1, + }; + assert_eq!(prop, expected); + + // Third relayer votes against + assert_ok!(Bridge::reject_proposal( + Origin::signed(RELAYER_C), + prop_id, + src_id, + r_id, + Box::new(proposal.clone()) + )); + let prop = + Bridge::get_votes(src_id, (prop_id.clone(), proposal.clone())) + .unwrap(); + let expected = ProposalVotes { + votes_for: vec![RELAYER_A], + votes_against: vec![RELAYER_B, RELAYER_C], + status: ProposalStatus::Rejected, + expiry: ProposalLifetime::get() + 1, + }; + assert_eq!(prop, expected); + + assert_eq!(mock::Balances::free_balance(RELAYER_B), 0); + assert_eq!( + mock::Balances::free_balance(Bridge::account_id()), + ENDOWED_BALANCE + ); + + assert_events(vec![ + mock::Event::Bridge( + pallet_chainbridge::Event::::VoteFor( + src_id, prop_id, RELAYER_A, + ), + ), + mock::Event::Bridge( + pallet_chainbridge::Event::::VoteAgainst( + src_id, prop_id, RELAYER_B, + ), + ), + mock::Event::Bridge( + pallet_chainbridge::Event::::VoteAgainst( + src_id, prop_id, RELAYER_C, + ), + ), + mock::Event::Bridge( + pallet_chainbridge::Event::::ProposalRejected( + src_id, prop_id, + ), + ), + ]); + }) } #[test] fn execute_after_threshold_change() { - let src_id = 1; - let r_id = derive_resource_id(src_id, b"transfer"); - - new_test_ext_initialized(src_id, r_id, b"System.remark".to_vec()).execute_with(|| { - let prop_id = 1; - let proposal = make_proposal(vec![11]); - - // Create proposal (& vote) - assert_ok!(Bridge::acknowledge_proposal( - Origin::signed(RELAYER_A), - prop_id, - src_id, - r_id, - Box::new(proposal.clone()) - )); - let prop = Bridge::votes(src_id, (prop_id.clone(), proposal.clone())).unwrap(); - let expected = ProposalVotes { - votes_for: vec![RELAYER_A], - votes_against: vec![], - status: ProposalStatus::Initiated, - expiry: ProposalLifetime::get() + 1, - }; - assert_eq!(prop, expected); - - // Change threshold - assert_ok!(Bridge::set_threshold(Origin::root(), 1)); - - // Attempt to execute - assert_ok!(Bridge::eval_vote_state( - Origin::signed(RELAYER_A), - prop_id, - src_id, - Box::new(proposal.clone()) - )); - - let prop = Bridge::votes(src_id, (prop_id.clone(), proposal.clone())).unwrap(); - let expected = ProposalVotes { - votes_for: vec![RELAYER_A], - votes_against: vec![], - status: ProposalStatus::Approved, - expiry: ProposalLifetime::get() + 1, - }; - assert_eq!(prop, expected); - - assert_eq!(Balances::free_balance(RELAYER_B), 0); - assert_eq!( - Balances::free_balance(Bridge::account_id()), - ENDOWED_BALANCE - ); - - assert_events(vec![ - Event::bridge(RawEvent::VoteFor(src_id, prop_id, RELAYER_A)), - Event::bridge(RawEvent::RelayerThresholdChanged(1)), - Event::bridge(RawEvent::ProposalApproved(src_id, prop_id)), - Event::bridge(RawEvent::ProposalSucceeded(src_id, prop_id)), - ]); - }) + let src_id = 1; + let r_id = derive_resource_id(src_id, b"transfer"); + + new_test_ext_initialized(src_id, r_id, b"System.remark".to_vec()) + .execute_with(|| { + let prop_id = 1; + let proposal = make_proposal(vec![11]); + + // Create proposal (& vote) + assert_ok!(Bridge::acknowledge_proposal( + Origin::signed(RELAYER_A), + prop_id, + src_id, + r_id, + Box::new(proposal.clone()) + )); + let prop = + Bridge::get_votes(src_id, (prop_id.clone(), proposal.clone())) + .unwrap(); + let expected = ProposalVotes { + votes_for: vec![RELAYER_A], + votes_against: vec![], + status: ProposalStatus::Initiated, + expiry: ProposalLifetime::get() + 1, + }; + assert_eq!(prop, expected); + + // Change threshold + assert_ok!(Bridge::set_threshold(Origin::root(), 1)); + + // Attempt to execute + assert_ok!(Bridge::eval_vote_state( + Origin::signed(RELAYER_A), + prop_id, + src_id, + Box::new(proposal.clone()) + )); + + let prop = + Bridge::get_votes(src_id, (prop_id.clone(), proposal.clone())) + .unwrap(); + let expected = ProposalVotes { + votes_for: vec![RELAYER_A], + votes_against: vec![], + status: ProposalStatus::Approved, + expiry: ProposalLifetime::get() + 1, + }; + assert_eq!(prop, expected); + + assert_eq!(mock::Balances::free_balance(RELAYER_B), 0); + assert_eq!( + mock::Balances::free_balance(Bridge::account_id()), + ENDOWED_BALANCE + ); + + assert_events(vec![ + mock::Event::Bridge(pallet_chainbridge::Event::::VoteFor( + src_id, prop_id, RELAYER_A, + )), + mock::Event::Bridge( + pallet_chainbridge::Event::::RelayerThresholdChanged(1), + ), + mock::Event::Bridge( + pallet_chainbridge::Event::::ProposalApproved( + src_id, prop_id, + ), + ), + mock::Event::Bridge( + pallet_chainbridge::Event::::ProposalSucceeded( + src_id, prop_id, + ), + ), + ]); + }) } #[test] fn proposal_expires() { - let src_id = 1; - let r_id = derive_resource_id(src_id, b"remark"); - - new_test_ext_initialized(src_id, r_id, b"System.remark".to_vec()).execute_with(|| { - let prop_id = 1; - let proposal = make_proposal(vec![10]); - - // Create proposal (& vote) - assert_ok!(Bridge::acknowledge_proposal( - Origin::signed(RELAYER_A), - prop_id, - src_id, - r_id, - Box::new(proposal.clone()) - )); - let prop = Bridge::votes(src_id, (prop_id.clone(), proposal.clone())).unwrap(); - let expected = ProposalVotes { - votes_for: vec![RELAYER_A], - votes_against: vec![], - status: ProposalStatus::Initiated, - expiry: ProposalLifetime::get() + 1, - }; - assert_eq!(prop, expected); - - // Increment enough blocks such that now == expiry - System::set_block_number(ProposalLifetime::get() + 1); - - // Attempt to submit a vote should fail - assert_noop!( - Bridge::reject_proposal( - Origin::signed(RELAYER_B), - prop_id, - src_id, - r_id, - Box::new(proposal.clone()) - ), - Error::::ProposalExpired - ); - - // Proposal state should remain unchanged - let prop = Bridge::votes(src_id, (prop_id.clone(), proposal.clone())).unwrap(); - let expected = ProposalVotes { - votes_for: vec![RELAYER_A], - votes_against: vec![], - status: ProposalStatus::Initiated, - expiry: ProposalLifetime::get() + 1, - }; - assert_eq!(prop, expected); - - // eval_vote_state should have no effect - assert_noop!( - Bridge::eval_vote_state( - Origin::signed(RELAYER_C), - prop_id, - src_id, - Box::new(proposal.clone()) - ), - Error::::ProposalExpired - ); - let prop = Bridge::votes(src_id, (prop_id.clone(), proposal.clone())).unwrap(); - let expected = ProposalVotes { - votes_for: vec![RELAYER_A], - votes_against: vec![], - status: ProposalStatus::Initiated, - expiry: ProposalLifetime::get() + 1, - }; - assert_eq!(prop, expected); - - assert_events(vec![Event::bridge(RawEvent::VoteFor( - src_id, prop_id, RELAYER_A, - ))]); - }) + let src_id = 1; + let r_id = derive_resource_id(src_id, b"remark"); + + new_test_ext_initialized(src_id, r_id, b"System.remark".to_vec()) + .execute_with(|| { + let prop_id = 1; + let proposal = make_proposal(vec![10]); + + // Create proposal (& vote) + assert_ok!(Bridge::acknowledge_proposal( + Origin::signed(RELAYER_A), + prop_id, + src_id, + r_id, + Box::new(proposal.clone()) + )); + let prop = + Bridge::get_votes(src_id, (prop_id.clone(), proposal.clone())) + .unwrap(); + let expected = ProposalVotes { + votes_for: vec![RELAYER_A], + votes_against: vec![], + status: ProposalStatus::Initiated, + expiry: ProposalLifetime::get() + 1, + }; + assert_eq!(prop, expected); + + // Increment enough blocks such that now == expiry + mock::System::set_block_number(ProposalLifetime::get() + 1); + + // Attempt to submit a vote should fail + assert_noop!( + Bridge::reject_proposal( + Origin::signed(RELAYER_B), + prop_id, + src_id, + r_id, + Box::new(proposal.clone()) + ), + Error::::ProposalExpired + ); + + // Proposal state should remain unchanged + let prop = + Bridge::get_votes(src_id, (prop_id.clone(), proposal.clone())) + .unwrap(); + let expected = ProposalVotes { + votes_for: vec![RELAYER_A], + votes_against: vec![], + status: ProposalStatus::Initiated, + expiry: ProposalLifetime::get() + 1, + }; + assert_eq!(prop, expected); + + // eval_vote_state should have no effect + assert_noop!( + Bridge::eval_vote_state( + Origin::signed(RELAYER_C), + prop_id, + src_id, + Box::new(proposal.clone()) + ), + Error::::ProposalExpired + ); + let prop = + Bridge::get_votes(src_id, (prop_id.clone(), proposal.clone())) + .unwrap(); + let expected = ProposalVotes { + votes_for: vec![RELAYER_A], + votes_against: vec![], + status: ProposalStatus::Initiated, + expiry: ProposalLifetime::get() + 1, + }; + assert_eq!(prop, expected); + + assert_events(vec![mock::Event::Bridge( + pallet_chainbridge::Event::::VoteFor( + src_id, prop_id, RELAYER_A, + ), + )]); + }) } diff --git a/crust-collator/pallets/bridge/src/types.rs b/crust-collator/pallets/bridge/src/types.rs new file mode 100644 index 00000000..fc0483d6 --- /dev/null +++ b/crust-collator/pallets/bridge/src/types.rs @@ -0,0 +1,103 @@ +// Copyright 2021 ChainSafe Systems +// SPDX-License-Identifier: GPL-3.0-only + +#![deny(warnings)] + +use codec::{ + Decode, + Encode, + MaxEncodedLen, +}; +use frame_support::pallet_prelude::*; +use scale_info::TypeInfo; +use sp_std::prelude::*; +use sp_core::U256; + +pub type ChainId = u8; +pub type DepositNonce = u64; +pub type ResourceId = [u8; 32]; + +#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub enum ProposalStatus { + Initiated, + Approved, + Rejected, +} + +#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub struct ProposalVotes { + pub votes_for: Vec, + pub votes_against: Vec, + pub status: ProposalStatus, + pub expiry: BlockNumber, +} + +#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)] +pub enum BridgeEvent { + FungibleTransfer(u8, u64, [u8; 32], U256, Vec), + NonFungibleTransfer( + u8, + u64, + [u8; 32], + Vec, + Vec, + Vec, + ), + GenericTransfer(u8, u64, [u8; 32], Vec), +} + +impl Default for ProposalVotes +where + BlockNumber: Default, +{ + fn default() -> Self { + Self { + votes_for: vec![], + votes_against: vec![], + status: ProposalStatus::Initiated, + expiry: BlockNumber::default(), + } + } +} + +impl ProposalVotes +where + AccountId: PartialEq, + BlockNumber: PartialOrd, +{ + /// Attempts to mark the proposal as approve or rejected. + /// Returns true if the status changes from active. + pub(crate) fn try_to_complete( + &mut self, + threshold: u32, + total: u32, + ) -> ProposalStatus { + if self.votes_for.len() >= threshold as usize { + self.status = ProposalStatus::Approved; + ProposalStatus::Approved + } else if total >= threshold + && (self.votes_against.len() as u32).saturating_add(threshold) + > total + { + self.status = ProposalStatus::Rejected; + ProposalStatus::Rejected + } else { + ProposalStatus::Initiated + } + } + + /// Returns true if the proposal has been rejected or approved, otherwise false. + pub(crate) fn is_complete(&self) -> bool { + self.status != ProposalStatus::Initiated + } + + /// Returns true if the `who` has voted for or against the proposal + pub(crate) fn has_voted(&self, who: &AccountId) -> bool { + self.votes_for.contains(&who) || self.votes_against.contains(&who) + } + + /// Returns true if the expiry time has been reached + pub(crate) fn is_expired(&self, now: BlockNumber) -> bool { + self.expiry <= now + } +} diff --git a/crust-collator/pallets/claims/Cargo.toml b/crust-collator/pallets/claims/Cargo.toml index 576d3383..544b3c45 100644 --- a/crust-collator/pallets/claims/Cargo.toml +++ b/crust-collator/pallets/claims/Cargo.toml @@ -8,22 +8,22 @@ homepage = "https://crust.network" repository = "https://github.com/paritytech/crust/" [dependencies] -serde = { default-features = false, version = "1.0.140" } +serde = { default-features = false, version = "1.0.144" } serde_derive = { optional = true, version = "1.0.102" } codec = { package = "parity-scale-codec", default-features = false, version = "3.0.0" } rustc-hex = { default-features = false, version = "2.0.1" } -scale-info = { version = "2.1.1", default-features = false, features = ["derive"] } +scale-info = { version = "2.2.0", default-features = false, features = ["derive"] } # substrate frame dependencies -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } +frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } [dev-dependencies] -balances = { package = 'pallet-balances', git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } +balances = { package = 'pallet-balances', git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } hex-literal = "0.3.4" [features] diff --git a/crust-collator/pallets/claims/src/lib.rs b/crust-collator/pallets/claims/src/lib.rs index 13659656..3e383450 100644 --- a/crust-collator/pallets/claims/src/lib.rs +++ b/crust-collator/pallets/claims/src/lib.rs @@ -4,26 +4,19 @@ //! Module to process claims from Ethereum addresses. #![cfg_attr(not(feature = "std"), no_std)] use sp_std::prelude::*; -use sp_io::{hashing::keccak_256, crypto::secp256k1_ecdsa_recover}; -use frame_support::{ - decl_event, decl_storage, decl_module, decl_error, ensure, PalletId, - traits::{Currency, Get, ExistenceRequirement::AllowDeath} -}; -use frame_system::{ensure_signed, ensure_root, ensure_none}; use codec::{Encode, Decode}; #[cfg(feature = "std")] use serde::{self, Serialize, Deserialize, Serializer, Deserializer}; -use sp_std::convert::TryInto; - -use sp_runtime::{ - RuntimeDebug, DispatchResult, - transaction_validity::{ - TransactionLongevity, TransactionValidity, ValidTransaction, InvalidTransaction, TransactionSource, - }, - traits::{ - Zero, StaticLookup, Saturating, AccountIdConversion - }, -}; + +use sp_runtime::{RuntimeDebug}; +use frame_support::ensure; +use sp_io::{hashing::keccak_256, crypto::secp256k1_ecdsa_recover}; +pub use pallet::*; +use frame_support::traits::ExistenceRequirement::AllowDeath; +use sp_runtime::traits::Get; +use frame_support::traits::Currency; +use sp_runtime::DispatchResult; +use sp_runtime::traits::AccountIdConversion; #[cfg(test)] mod mock; @@ -31,23 +24,6 @@ mod mock; #[cfg(test)] mod tests; -/// The balance type of this module. -pub type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; - -pub trait Config: frame_system::Config { - /// The claim's module id, used for deriving its sovereign account ID. - type PalletId: Get; - - /// The overarching event type. - type Event: From> + Into<::Event>; - - /// The payment balance. - type Currency: Currency; - - /// The constant used for ethereum signature. - type Prefix: Get<&'static [u8]>; -} - /// An Ethereum address (i.e. 20 bytes, used to represent an Ethereum account). /// /// This gets serialized to the 0x-prefixed hex representation. @@ -131,30 +107,77 @@ impl<'de> Deserialize<'de> for EthereumTxHash { } } -decl_event!( - pub enum Event where - Balance = BalanceOf, - AccountId = ::AccountId - { +#[frame_support::pallet] +pub mod pallet { + use crate::{ + EthereumTxHash, + EcdsaSignature, to_ascii_hex, + EthereumAddress, + ValidityError}; + use sp_std::prelude::*; + use sp_std::convert::TryInto; + use frame_support::{pallet_prelude::*, PalletId}; + use frame_system::pallet_prelude::*; + use sp_runtime::{ + transaction_validity::{ + TransactionLongevity, TransactionValidity, ValidTransaction, InvalidTransaction, TransactionSource, + }, + traits::{ + StaticLookup, Saturating + }, + }; + use frame_support::{ + traits::{Currency, Get} + }; + + /// The balance type of this module. + pub type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; + + + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + #[pallet::without_storage_info] + pub struct Pallet(_); + + /// Configuration trait. + #[pallet::config] + pub trait Config: frame_system::Config { + /// The claim's module id, used for deriving its sovereign account ID. + #[pallet::constant] + type PalletId: Get; + + /// The overarching event type. + type Event: From> + IsType<::Event>; + + /// The payment balance. + type Currency: Currency; + + /// The constant used for ethereum signature. + #[pallet::constant] + type Prefix: Get<&'static [u8]>; + } + + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { /// Init pot success - InitPot(AccountId, Balance), + InitPot(T::AccountId, BalanceOf), /// Someone be the new superior - SuperiorChanged(AccountId), + SuperiorChanged(T::AccountId), /// Someone be the new miner - MinerChanged(AccountId), + MinerChanged(T::AccountId), /// Set limit successfully - SetLimitSuccess(Balance), + SetLimitSuccess(BalanceOf), /// Mint claims successfully - MintSuccess(EthereumTxHash, EthereumAddress, Balance), + MintSuccess(EthereumTxHash, EthereumAddress, BalanceOf), /// Someone claimed some CRUs. [who, ethereum_address, amount] - Claimed(AccountId, EthereumAddress, Balance), + Claimed(T::AccountId, EthereumAddress, BalanceOf), /// Ethereum address was bonded to account. [who, ethereum_address] - BondEthSuccess(AccountId, EthereumAddress), + BondEthSuccess(T::AccountId, EthereumAddress), } -); -decl_error! { - pub enum Error for Module { + #[pallet::error] + pub enum Error { /// Superior not exist, should set it first IllegalSuperior, /// Miner is not exist, should set it first @@ -173,58 +196,46 @@ decl_error! { SignatureNotMatch, /// Exceed claim limitation ExceedClaimLimit, - } -} - -decl_storage! { - // A macro for the Storage config, and its implementation, for this module. - // This allows for type-safe usage of the Substrate storage database, so you can - // keep things around between blocks. - trait Store for Module as Claims { - /// Claim limit determinate how many CRUs can be claimed - ClaimLimit get(fn claim_limit): BalanceOf = Zero::zero(); - - /// The claim transaction mapping relationship in ethereum - Claims get(fn claims): map hasher(identity) EthereumTxHash => Option<(EthereumAddress, BalanceOf)>; + } - /// Mark if the claim transaction has already been claimed - Claimed get(fn claimed): map hasher(identity) EthereumTxHash => bool; + #[pallet::storage] + #[pallet::getter(fn claim_limit)] + pub(super) type ClaimLimit = StorageValue<_, BalanceOf, ValueQuery>; - /// [who] can set the claim limit - Superior get(fn superior): Option; + #[pallet::storage] + #[pallet::getter(fn claims)] + pub(super) type Claims = StorageMap<_, Identity, EthereumTxHash, (EthereumAddress, BalanceOf), OptionQuery>; - /// [who] can mint the claims - Miner get(fn miner): Option; - } -} - -decl_module! { - pub struct Module for enum Call where origin: T::Origin { - type Error = Error; + #[pallet::storage] + #[pallet::getter(fn claimed)] + pub(super) type Claimed = StorageMap<_, Identity, EthereumTxHash, bool, ValueQuery>; - fn deposit_event() = default; + #[pallet::storage] + #[pallet::getter(fn superior)] + pub(super) type Superior = StorageValue<_, T::AccountId, OptionQuery>; - /// The Prefix that is used in signed Ethereum messages for this network - const Prefix: &[u8] = T::Prefix::get(); + #[pallet::storage] + #[pallet::getter(fn miner)] + pub(super) type Miner = StorageValue<_, T::AccountId, OptionQuery>; - /// The claim's module id, used for deriving its sovereign account ID. - const PalletId: PalletId = T::PalletId::get(); + #[pallet::call] + impl Pallet { /// Change superior /// /// The dispatch origin for this call must be _Root_. /// /// Parameter: /// - `new_superior`: The new superior's address - #[weight = 1000] - fn change_superior(origin, new_superior: ::Source) -> DispatchResult { + #[pallet::weight(1000)] + pub fn change_superior(origin: OriginFor, new_superior: ::Source) -> DispatchResult { ensure_root(origin)?; let new_superior = T::Lookup::lookup(new_superior)?; Superior::::put(new_superior.clone()); - Self::deposit_event(RawEvent::SuperiorChanged(new_superior)); + Self::deposit_event(Event::SuperiorChanged(new_superior)); Ok(()) } @@ -235,15 +246,15 @@ decl_module! { /// /// Parameters: /// - `new_miner`: The new miner's address - #[weight = 1000] - fn change_miner(origin, new_miner: ::Source) -> DispatchResult { + #[pallet::weight(1000)] + pub fn change_miner(origin: OriginFor, new_miner: ::Source) -> DispatchResult { ensure_root(origin)?; let new_miner = T::Lookup::lookup(new_miner)?; Miner::::put(new_miner.clone()); - Self::deposit_event(RawEvent::MinerChanged(new_miner)); + Self::deposit_event(Event::MinerChanged(new_miner)); Ok(()) } @@ -253,8 +264,8 @@ decl_module! { /// /// Parameters: /// - `limit`: The claim CRUs limit - #[weight = 1000] - fn set_claim_limit(origin, limit: BalanceOf) -> DispatchResult { + #[pallet::weight(1000)] + pub fn set_claim_limit(origin: OriginFor, limit: BalanceOf) -> DispatchResult { let signer = ensure_signed(origin)?; let maybe_superior = Self::superior(); @@ -267,7 +278,7 @@ decl_module! { // 3. Set claim limit ClaimLimit::::put(limit); - Self::deposit_event(RawEvent::SetLimitSuccess(limit)); + Self::deposit_event(Event::SetLimitSuccess(limit)); Ok(()) } @@ -279,8 +290,8 @@ decl_module! { /// - `tx`: The claim ethereum tx hash /// - `who`: The claimer ethereum address /// - `value`: The amount of this tx, should be less than claim_limit - #[weight = 1000] - fn mint_claim(origin, tx: EthereumTxHash, who: EthereumAddress, value: BalanceOf) -> DispatchResult { + #[pallet::weight(1000)] + pub fn mint_claim(origin: OriginFor, tx: EthereumTxHash, who: EthereumAddress, value: BalanceOf) -> DispatchResult { let signer = ensure_signed(origin)?; let maybe_miner = Self::miner(); @@ -298,17 +309,17 @@ decl_module! { // 5. Save into claims Claims::::insert(tx.clone(), (who.clone(), value.clone())); - Claimed::insert(tx, false); + Claimed::::insert(tx, false); // 6. Reduce claim limit ClaimLimit::::mutate(|l| *l = l.saturating_sub(value)); - Self::deposit_event(RawEvent::MintSuccess(tx, who, value)); + Self::deposit_event(Event::MintSuccess(tx, who, value)); Ok(()) } - #[weight = 0] - fn claim(origin, dest: T::AccountId, tx: EthereumTxHash, sig: EcdsaSignature) -> DispatchResult { + #[pallet::weight(0)] + pub fn claim(origin: OriginFor, dest: T::AccountId, tx: EthereumTxHash, sig: EcdsaSignature) -> DispatchResult { let _ = ensure_none(origin)?; // 1. Check the tx already be mint and not be claimed @@ -324,20 +335,50 @@ decl_module! { Self::process_claim(tx, signer, dest) } } -} -/// Converts the given binary data into ASCII-encoded hex. It will be twice the length. -fn to_ascii_hex(data: &[u8]) -> Vec { - let mut r = Vec::with_capacity(data.len() * 2); - let mut push_nibble = |n| r.push(if n < 10 { b'0' + n } else { b'a' - 10 + n }); - for &b in data.iter() { - push_nibble(b / 16); - push_nibble(b % 16); + #[pallet::validate_unsigned] + impl ValidateUnsigned for Pallet { + type Call = Call; + + fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity { + const PRIORITY: u64 = 100; + + let (maybe_signer, tx) = match call { + Call::claim {dest, tx, sig} => { + let data = dest.using_encoded(to_ascii_hex); + let tx_data = tx.using_encoded(to_ascii_hex); + (Self::eth_recover(&sig, &data, &tx_data), tx) + } + _ => return Err(InvalidTransaction::Call.into()), + }; + + let signer = maybe_signer + .ok_or(InvalidTransaction::Custom(ValidityError::InvalidEthereumSignature.into()))?; + + let e = InvalidTransaction::Custom(ValidityError::SignerHasNoClaim.into()); + ensure!(>::contains_key(&tx), e); + + let e = InvalidTransaction::Custom(ValidityError::SignatureNotMatch.into()); + let (claimer, _) = Self::claims(&tx).unwrap(); + ensure!(claimer == signer, e); + + let e = InvalidTransaction::Custom(ValidityError::AlreadyBeClaimed.into()); + ensure!(!Self::claimed(&tx), e); + + Ok(ValidTransaction { + priority: PRIORITY, + requires: vec![], + provides: vec![("claims", signer).encode()], + longevity: TransactionLongevity::max_value(), + propagate: true, + }) + } + } - r } -impl Module { + +impl Pallet { // The claim pot account pub fn claim_pot() -> T::AccountId { // "modl" ++ "crclaims" ++ "clai" is 16 bytes @@ -379,10 +420,10 @@ impl Module { T::Currency::transfer(&Self::claim_pot(), &dest, amount, AllowDeath)?; // 3. Mark it be claimed - Claimed::insert(tx, true); + Claimed::::insert(tx, true); // Let's deposit an event to let the outside world know who claimed money - Self::deposit_event(RawEvent::Claimed(dest, signer, amount)); + Self::deposit_event(Event::Claimed(dest, signer, amount)); Ok(()) } else { @@ -391,6 +432,17 @@ impl Module { } } +/// Converts the given binary data into ASCII-encoded hex. It will be twice the length. +fn to_ascii_hex(data: &[u8]) -> Vec { + let mut r = Vec::with_capacity(data.len() * 2); + let mut push_nibble = |n| r.push(if n < 10 { b'0' + n } else { b'a' - 10 + n }); + for &b in data.iter() { + push_nibble(b / 16); + push_nibble(b % 16); + } + r +} + /// Custom validity errors used in Polkadot while validating transactions. #[repr(u8)] pub enum ValidityError { @@ -408,42 +460,4 @@ impl From for u8 { fn from(err: ValidityError) -> Self { err as u8 } -} - -impl sp_runtime::traits::ValidateUnsigned for Module { - type Call = Call; - - fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity { - const PRIORITY: u64 = 100; - - let (maybe_signer, tx) = match call { - Call::claim {dest, tx, sig} => { - let data = dest.using_encoded(to_ascii_hex); - let tx_data = tx.using_encoded(to_ascii_hex); - (Self::eth_recover(&sig, &data, &tx_data), tx) - } - _ => return Err(InvalidTransaction::Call.into()), - }; - - let signer = maybe_signer - .ok_or(InvalidTransaction::Custom(ValidityError::InvalidEthereumSignature.into()))?; - - let e = InvalidTransaction::Custom(ValidityError::SignerHasNoClaim.into()); - ensure!(>::contains_key(&tx), e); - - let e = InvalidTransaction::Custom(ValidityError::SignatureNotMatch.into()); - let (claimer, _) = Self::claims(&tx).unwrap(); - ensure!(claimer == signer, e); - - let e = InvalidTransaction::Custom(ValidityError::AlreadyBeClaimed.into()); - ensure!(!Self::claimed(&tx), e); - - Ok(ValidTransaction { - priority: PRIORITY, - requires: vec![], - provides: vec![("claims", signer).encode()], - longevity: TransactionLongevity::max_value(), - propagate: true, - }) - } -} +} \ No newline at end of file diff --git a/crust-collator/pallets/collator-selection/Cargo.toml b/crust-collator/pallets/collator-selection/Cargo.toml index 564efda9..d41d3044 100644 --- a/crust-collator/pallets/collator-selection/Cargo.toml +++ b/crust-collator/pallets/collator-selection/Cargo.toml @@ -15,28 +15,28 @@ targets = ['x86_64-unknown-linux-gnu'] [dependencies] log = { version = "0.4.17", default-features = false } codec = { default-features = false, features = ['derive'], package = 'parity-scale-codec', version = '3.0.0' } -scale-info = { version = "2.1.1", default-features = false, features = ["derive"] } -serde = { version = "1.0.140", default-features = false } -sp-std = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.27" } -sp-runtime = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.27" } -sp-staking = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.27" } -frame-support = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.27" } -frame-system = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.27" } -pallet-authorship = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.27" } -pallet-session = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.27" } +scale-info = { version = "2.2.0", default-features = false, features = ["derive"] } +serde = { version = "1.0.144", default-features = false } +sp-std = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.29" } +sp-runtime = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.29" } +sp-staking = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.29" } +frame-support = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.29" } +frame-system = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.29" } +pallet-authorship = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.29" } +pallet-session = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.29" } -frame-benchmarking = { default-features = false, optional = true, git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.27" } +frame-benchmarking = { default-features = false, optional = true, git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.29" } [dev-dependencies] -sp-core = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.27" } -sp-io = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.27" } -sp-tracing = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.27" } -sp-runtime = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.27" } -pallet-timestamp = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.27" } -sp-consensus-aura = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.27" } -pallet-balances = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.27" } -pallet-aura = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.27" } +sp-core = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.29" } +sp-io = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.29" } +sp-tracing = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.29" } +sp-runtime = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.29" } +pallet-timestamp = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.29" } +sp-consensus-aura = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.29" } +pallet-balances = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.29" } +pallet-aura = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.29" } [features] default = ['std'] diff --git a/crust-collator/pallets/collator-selection/src/lib.rs b/crust-collator/pallets/collator-selection/src/lib.rs index 0257276a..747d3b75 100644 --- a/crust-collator/pallets/collator-selection/src/lib.rs +++ b/crust-collator/pallets/collator-selection/src/lib.rs @@ -72,7 +72,8 @@ pub mod weights; #[frame_support::pallet] pub mod pallet { use frame_support::{ - dispatch::DispatchResultWithPostInfo, + weights::DispatchClass, + dispatch::{DispatchResultWithPostInfo}, pallet_prelude::*, inherent::Vec, traits::{ @@ -86,8 +87,7 @@ pub mod pallet { sp_runtime::{ RuntimeDebug, traits::{AccountIdConversion, CheckedSub, Zero, Saturating}, - }, - weights::DispatchClass, + } }; use core::ops::Div; use pallet_session::SessionManager; diff --git a/crust-collator/pallets/collator-selection/src/weights.rs b/crust-collator/pallets/collator-selection/src/weights.rs index a9f3a889..dd7a988c 100644 --- a/crust-collator/pallets/collator-selection/src/weights.rs +++ b/crust-collator/pallets/collator-selection/src/weights.rs @@ -36,48 +36,43 @@ pub trait WeightInfo { pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { fn set_invulnerables(b: u32, ) -> Weight { - (18_563_000 as Weight) - // Standard Error: 0 - .saturating_add((68_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) + Weight::from_ref_time(18_563_000 as u64) + .saturating_add(Weight::from_ref_time(68_000 as u64).saturating_mul(b as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) } fn set_desired_candidates() -> Weight { - (16_363_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) + Weight::from_ref_time(16_363_000 as u64) + .saturating_add(T::DbWeight::get().writes(1 as u64)) } fn set_candidacy_bond() -> Weight { - (16_840_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) + Weight::from_ref_time(16_840_000 as u64) + .saturating_add(T::DbWeight::get().writes(1 as u64)) } fn register_as_candidate(c: u32, ) -> Weight { - (71_196_000 as Weight) - // Standard Error: 0 - .saturating_add((198_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) + Weight::from_ref_time(71_196_000 as u64) + .saturating_add(Weight::from_ref_time(198_000 as u64).saturating_mul(c as u64)) + .saturating_add(T::DbWeight::get().reads(4 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) } fn leave_intent(c: u32, ) -> Weight { - (55_336_000 as Weight) - // Standard Error: 0 - .saturating_add((151_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) + Weight::from_ref_time(55_336_000 as u64) + .saturating_add(Weight::from_ref_time(151_000 as u64).saturating_mul(c as u64)) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) } fn note_author() -> Weight { - (71_461_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) + Weight::from_ref_time(71_461_000 as u64) + .saturating_add(T::DbWeight::get().reads(3 as u64)) + .saturating_add(T::DbWeight::get().writes(4 as u64)) } fn new_session(r: u32, c: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 1_010_000 - .saturating_add((109_961_000 as Weight).saturating_mul(r as Weight)) - // Standard Error: 1_010_000 - .saturating_add((151_952_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r 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_mul(r as Weight))) - .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) + Weight::from_ref_time(0 as u64) + .saturating_add(Weight::from_ref_time(109_961_000 as u64).saturating_mul(r as u64)) + .saturating_add(Weight::from_ref_time(151_952_000 as u64).saturating_mul(c as u64)) + .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(r as u64))) + .saturating_add(T::DbWeight::get().reads((2 as u64).saturating_mul(c as u64))) + .saturating_add(T::DbWeight::get().writes((2 as u64).saturating_mul(r as u64))) + .saturating_add(T::DbWeight::get().writes((2 as u64).saturating_mul(c as u64))) } } @@ -85,47 +80,42 @@ impl WeightInfo for SubstrateWeight { // For backwards compatibility and tests impl WeightInfo for () { fn set_invulnerables(b: u32, ) -> Weight { - (18_563_000 as Weight) - // Standard Error: 0 - .saturating_add((68_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + Weight::from_ref_time(18_563_000 as u64) + .saturating_add(Weight::from_ref_time(68_000 as u64).saturating_mul(b as u64)) + .saturating_add(RocksDbWeight::get().writes(1 as u64)) } fn set_desired_candidates() -> Weight { - (16_363_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + Weight::from_ref_time(16_363_000 as u64) + .saturating_add(RocksDbWeight::get().writes(1 as u64)) } fn set_candidacy_bond() -> Weight { - (16_840_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + Weight::from_ref_time(16_840_000 as u64) + .saturating_add(RocksDbWeight::get().writes(1 as u64)) } fn register_as_candidate(c: u32, ) -> Weight { - (71_196_000 as Weight) - // Standard Error: 0 - .saturating_add((198_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + Weight::from_ref_time(71_196_000 as u64) + .saturating_add(Weight::from_ref_time(198_000 as u64).saturating_mul(c as u64)) + .saturating_add(RocksDbWeight::get().reads(4 as u64)) + .saturating_add(RocksDbWeight::get().writes(2 as u64)) } fn leave_intent(c: u32, ) -> Weight { - (55_336_000 as Weight) - // Standard Error: 0 - .saturating_add((151_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + Weight::from_ref_time(55_336_000 as u64) + .saturating_add(Weight::from_ref_time(151_000 as u64).saturating_mul(c as u64)) + .saturating_add(RocksDbWeight::get().reads(1 as u64)) + .saturating_add(RocksDbWeight::get().writes(2 as u64)) } fn note_author() -> Weight { - (71_461_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + Weight::from_ref_time(71_461_000 as u64) + .saturating_add(RocksDbWeight::get().reads(3 as u64)) + .saturating_add(RocksDbWeight::get().writes(4 as u64)) } fn new_session(r: u32, c: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 1_010_000 - .saturating_add((109_961_000 as Weight).saturating_mul(r as Weight)) - // Standard Error: 1_010_000 - .saturating_add((151_952_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) - .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(r as Weight))) - .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) + Weight::from_ref_time(0 as u64) + .saturating_add(Weight::from_ref_time(109_961_000 as u64).saturating_mul(r as u64)) + .saturating_add(Weight::from_ref_time(151_952_000 as u64).saturating_mul(c as u64)) + .saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(r as u64))) + .saturating_add(RocksDbWeight::get().reads((2 as u64).saturating_mul(c as u64))) + .saturating_add(RocksDbWeight::get().writes((2 as u64).saturating_mul(r as u64))) + .saturating_add(RocksDbWeight::get().writes((2 as u64).saturating_mul(c as u64))) } } diff --git a/crust-collator/pallets/market/Cargo.toml b/crust-collator/pallets/market/Cargo.toml index defa11fd..8ea50795 100644 --- a/crust-collator/pallets/market/Cargo.toml +++ b/crust-collator/pallets/market/Cargo.toml @@ -10,18 +10,18 @@ repository = "https://github.com/paritytech/crust/" [dependencies] # third party dependencies codec = { default-features = false, package = "parity-scale-codec", features = ["derive"], version = "3.0.0" } -serde = { optional = true, version = "1.0.140" } +serde = { optional = true, version = "1.0.144" } serde_json = "1.0.51" # substrate frames -frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } -frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } +frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } # substrate primitives -sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } -sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } -sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } +sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } # crust runtime modules primitives = { package = "crust-parachain-primitives", path = "../../primitives", default-features = false } @@ -46,6 +46,6 @@ runtime-benchmarks = [ [dev-dependencies] hex = "0.4.2" swork = { package = "cstrml-swork", path = "../swork" } -balances = { package = 'pallet-balances', git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } +balances = { package = 'pallet-balances', git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } primitives = { package = "crust-parachain-primitives", path = "../../primitives", features = ["test"] } -frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27"} +frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29"} diff --git a/crust-collator/pallets/staking/Cargo.toml b/crust-collator/pallets/staking/Cargo.toml index a62b3920..ff3665c3 100644 --- a/crust-collator/pallets/staking/Cargo.toml +++ b/crust-collator/pallets/staking/Cargo.toml @@ -9,25 +9,25 @@ repository = "https://github.com/paritytech/crust/" [dependencies] # third party dependencies -serde = { optional = true, version = "1.0.140" } +serde = { optional = true, version = "1.0.144" } safe-mix = { default-features = false, version = "1.0.0" } codec = { package = "parity-scale-codec", default-features = false, features = ["derive"], version = "3.0.0" } -scale-info = { version = "2.1.1", default-features = false, features = ["derive"] } +scale-info = { version = "2.2.0", default-features = false, features = ["derive"] } # substrate frame dependencies -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -pallet-session = { features = ["historical"], default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -pallet-authorship = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } +frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +pallet-session = { features = ["historical"], default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +pallet-authorship = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } # substrate primitives -sp-keyring = { optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-io ={ default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-staking = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-consensus-aura = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } +sp-keyring = { optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-io ={ default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-staking = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-consensus-aura = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } rand_chacha = { default-features = false, version = "0.2" } # crust runtime modules @@ -35,14 +35,14 @@ swork = { package = "cstrml-swork", path = "../swork", default-features = false primitives = { package = "crust-parachain-primitives", path = "../../primitives", default-features = false } [dev-dependencies] -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27"} -balances = { package = 'pallet-balances', git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29"} +balances = { package = 'pallet-balances', git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } primitives = { package = "crust-parachain-primitives", path = "../../primitives", features = ["test"] } -pallet-timestamp = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27"} -frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27"} +pallet-timestamp = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29"} +frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29"} # private crate inside substrate -substrate-test-utils = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27"} +substrate-test-utils = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29"} [features] equalize = [] diff --git a/crust-collator/pallets/swork/Cargo.toml b/crust-collator/pallets/swork/Cargo.toml index 0936013b..26e49de8 100644 --- a/crust-collator/pallets/swork/Cargo.toml +++ b/crust-collator/pallets/swork/Cargo.toml @@ -10,20 +10,20 @@ repository = "https://github.com/paritytech/crust/" [dependencies] # third party dependencies codec = { default-features = false, package = "parity-scale-codec", version = "3.0.0" } -serde = { optional = true, version = "1.0.140" } +serde = { optional = true, version = "1.0.144" } base64 = { default-features = false, features = ["alloc"], version = "0.12.2" } p256 = { default-features = false, features = ["ecdsa"], version = "0.5.1" } -scale-info = { version = "2.1.1", default-features = false, features = ["derive"] } +scale-info = { version = "2.2.0", default-features = false, features = ["derive"] } # substrate frame dependencies -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } +frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } # substrate primitives -sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } +sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } # crust runtime modules primitives = { package = "crust-parachain-primitives", path = "../../primitives", default-features = false } @@ -31,8 +31,8 @@ webpki = { package = "webpki", path = "../../../utils/webpki", default-features serde_json = { package = "serde_json_no_std", path = "../../../utils/serde_json_no_std", default-features = false, features = ["alloc"] } [dev-dependencies] -keyring = { package = "sp-keyring", git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -balances = { package = 'pallet-balances', git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } +keyring = { package = "sp-keyring", git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +balances = { package = 'pallet-balances', git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } primitives = { package = "crust-parachain-primitives", path = "../../primitives", features = ["test"] } hex = "0.4.2" diff --git a/crust-collator/pallets/swork/benchmarking/Cargo.toml b/crust-collator/pallets/swork/benchmarking/Cargo.toml index 6d06b928..3b1d7ae1 100644 --- a/crust-collator/pallets/swork/benchmarking/Cargo.toml +++ b/crust-collator/pallets/swork/benchmarking/Cargo.toml @@ -10,25 +10,25 @@ repository = "https://github.com/paritytech/crust/" [dependencies] # third party dependencies codec = { default-features = false, package = "parity-scale-codec", features = ["derive"], version = "3.0.0" } -serde = { optional = true, version = "1.0.140" } +serde = { optional = true, version = "1.0.144" } # substrate frame dependencies -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } +frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } # substrate primitives -sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } +sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } -frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } +frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } # crust runtime modules primitives = { package = "crust-parachain-primitives", path = "../../../primitives", default-features = false } market = { package = "cstrml-market", path = "../../market", default-features = false } swork = { package = "cstrml-swork", path = "../../swork", default-features = false } -balances = { package = 'pallet-balances', git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } +balances = { package = 'pallet-balances', git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } [features] default = ["std"] @@ -50,5 +50,5 @@ std = [ [dev-dependencies] hex = "0.4.2" -keyring = { package = "sp-keyring", git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } +keyring = { package = "sp-keyring", git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } primitives = { package = "crust-parachain-primitives", path = "../../../primitives", features = ["test"] } diff --git a/crust-collator/pallets/xstorage/Cargo.toml b/crust-collator/pallets/xstorage/Cargo.toml index 038d711f..ef435c5c 100644 --- a/crust-collator/pallets/xstorage/Cargo.toml +++ b/crust-collator/pallets/xstorage/Cargo.toml @@ -8,27 +8,27 @@ authors = ["Crust Developers"] edition = "2018" [dependencies] -serde = { version = "1.0.140", optional = true } +serde = { version = "1.0.144", optional = true } codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } -sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } -sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } -sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } +sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } -frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } -frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } -scale-info = { version = "2.1.1", default-features = false, features = ["derive"] } +frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } +scale-info = { version = "2.2.0", default-features = false, features = ["derive"] } cumulus-primitives-core = { path = "../../../cumulus/primitives/core", default-features = false } -xcm = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.27", default-features = false } -xcm-executor = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.27", default-features = false } -polkadot-primitives = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.27", default-features = false } +xcm = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.29", default-features = false } +xcm-executor = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.29", default-features = false } +polkadot-primitives = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.29", default-features = false } [dev-dependencies] -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } -polkadot-core-primitives = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.27" } -xcm-builder = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.27" } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } +polkadot-core-primitives = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.29" } +xcm-builder = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.29" } crust-parachain-primitives = { path = "../../primitives", default-features = false } hex = "0.4.2" hex-literal = "0.3.4" diff --git a/crust-collator/pallets/xstorage/src/lib.rs b/crust-collator/pallets/xstorage/src/lib.rs index beec200a..3008db15 100644 --- a/crust-collator/pallets/xstorage/src/lib.rs +++ b/crust-collator/pallets/xstorage/src/lib.rs @@ -1,6 +1,6 @@ #![cfg_attr(not(feature = "std"), no_std)] - use frame_support::pallet; + pub use pallet::*; #[pallet] diff --git a/crust-collator/primitives/Cargo.toml b/crust-collator/primitives/Cargo.toml index 7fbd9b3f..a9e73123 100644 --- a/crust-collator/primitives/Cargo.toml +++ b/crust-collator/primitives/Cargo.toml @@ -7,23 +7,23 @@ edition = "2018" [dependencies] hex = { version = "0.4", default-features = false } log = "0.4.17" -serde = { version = "1.0.140", optional = true, default-features = false, features = [ "derive" ] } +serde = { version = "1.0.144", optional = true, default-features = false, features = [ "derive" ] } sha3 = { version = "0.8", default-features = false } # Substrate dependencies -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -sp-core = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +sp-core = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } -frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } -sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } +frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } parity-scale-codec = { version = "3.0.0", default-features = false, features = [ "derive" ] } -scale-info = { version = "2.1.1", default-features = false, features = [ "derive" ] } +scale-info = { version = "2.2.0", default-features = false, features = [ "derive" ] } # Polkadot / XCM -xcm = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.27", default-features = false } -xcm-builder = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.27", default-features = false } -xcm-executor = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.27", default-features = false } +xcm = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.29", default-features = false } +xcm-builder = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.29", default-features = false } +xcm-executor = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.29", default-features = false } [features] default = [ "std" ] diff --git a/crust-collator/primitives/src/lib.rs b/crust-collator/primitives/src/lib.rs index b3641ffc..00830b03 100644 --- a/crust-collator/primitives/src/lib.rs +++ b/crust-collator/primitives/src/lib.rs @@ -26,7 +26,7 @@ use sp_runtime::{ use frame_support::{ traits::{tokens::fungibles::Mutate, Get, Contains}, - weights::{constants::WEIGHT_PER_SECOND, Weight}, ensure + weights::{constants::WEIGHT_PER_SECOND}, ensure }; use sp_runtime::traits::Zero; use sp_std::{borrow::Borrow, vec::Vec}; @@ -210,7 +210,7 @@ pub struct FirstAssetTrader< AssetIdInfoGetter: UnitsToWeightRatio, R: TakeRevenue, >( - Weight, + u64, Option<(MultiLocation, u128, u128)>, PhantomData<(AssetType, AssetIdInfoGetter, R)>, ); @@ -225,7 +225,7 @@ impl< } fn buy_weight( &mut self, - weight: Weight, + weight: u64, payment: xcm_executor::Assets, ) -> Result { log::trace!( @@ -253,7 +253,7 @@ impl< if let Some(units_per_second) = AssetIdInfoGetter::get_units_per_second(asset_type) { let amount = units_per_second.saturating_mul(weight as u128) - / (WEIGHT_PER_SECOND as u128); + / (WEIGHT_PER_SECOND.ref_time() as u128); // We dont need to proceed if the amount is 0 // For cases (specially tests) where the asset is very cheap with respect @@ -304,11 +304,11 @@ impl< } } - fn refund_weight(&mut self, weight: Weight) -> Option { + fn refund_weight(&mut self, weight: u64) -> Option { if let Some((id, prev_amount, units_per_second)) = self.1.clone() { let weight = weight.min(self.0); self.0 -= weight; - let amount = units_per_second * (weight as u128) / (WEIGHT_PER_SECOND as u128); + let amount = units_per_second * (weight as u128) / (WEIGHT_PER_SECOND.ref_time() as u128); self.1 = Some(( id.clone(), prev_amount.saturating_sub(amount), @@ -343,8 +343,8 @@ impl> ShouldExecute for AllowDescendOriginFromLocal( origin: &MultiLocation, message: &mut Xcm, - max_weight: Weight, - _weight_credit: &mut Weight, + max_weight: u64, + _weight_credit: &mut u64, ) -> Result<(), ()> { log::trace!( target: "xcm::barriers", diff --git a/crust-collator/runtime/Cargo.toml b/crust-collator/runtime/Cargo.toml index 3bfa714d..d1cbaf7a 100644 --- a/crust-collator/runtime/Cargo.toml +++ b/crust-collator/runtime/Cargo.toml @@ -5,10 +5,10 @@ authors = ["Parity Technologies "] edition = '2018' [dependencies] -serde = { version = "1.0.140", optional = true, features = ["derive"] } +serde = { version = "1.0.144", optional = true, features = ["derive"] } codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } log = { version = "0.4.17", default-features = false } -scale-info = { version = "2.1.1", default-features = false, features = ["derive"] } +scale-info = { version = "2.2.0", default-features = false, features = ["derive"] } smallvec = "1.4.1" hex-literal = "0.3.4" @@ -24,50 +24,50 @@ bridge-transfer = { package = "cstrml-bridge-transfer", path = "../pallets/bridg crust-parachain-primitives = { path = "../primitives", default-features = false } # Substrate dependencies -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -sp-api = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -sp-io = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -sp-version = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -sp-core = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -sp-session = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -sp-offchain = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -sp-block-builder = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -sp-transaction-pool = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -sp-inherents = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -sp-consensus-aura = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -sp-arithmetic = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +sp-api = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +sp-io = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +sp-version = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +sp-core = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +sp-session = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +sp-offchain = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +sp-block-builder = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +sp-transaction-pool = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +sp-inherents = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +sp-consensus-aura = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +sp-arithmetic = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -frame-executive = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -frame-system = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -frame-system-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -pallet-balances = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -pallet-randomness-collective-flip = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -pallet-timestamp = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -pallet-sudo = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -pallet-transaction-payment = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } -pallet-scheduler = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } -pallet-aura = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -pallet-session = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -pallet-authorship = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -pallet-proxy = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.27" } -pallet-multisig = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.27" } -pallet-utility = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } -pallet-assets = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.27" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +frame-executive = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +frame-system = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +frame-system-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +pallet-balances = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +pallet-randomness-collective-flip = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +pallet-timestamp = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +pallet-sudo = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +pallet-transaction-payment = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } +pallet-scheduler = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } +pallet-aura = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +pallet-session = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +pallet-authorship = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +pallet-proxy = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.29" } +pallet-multisig = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.29" } +pallet-utility = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } +pallet-assets = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.29" } # Moonbeam's pallet for managing assets pallet-asset-manager = { path = "../pallets/asset-manager", default-features = false } # Governance -pallet-collective = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } -pallet-membership = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } -pallet-treasury = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } -pallet-identity = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } -pallet-democracy = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } -pallet-elections-phragmen = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } -pallet-tips = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false } +pallet-collective = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } +pallet-membership = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } +pallet-treasury = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } +pallet-identity = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } +pallet-democracy = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } +pallet-elections-phragmen = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } +pallet-tips = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29", default-features = false } # Cumulus dependencies cumulus-pallet-aura-ext = { path = "../../cumulus/pallets/aura-ext", default-features = false } @@ -82,19 +82,19 @@ cumulus-ping = { path = "../../cumulus/parachains/pallets/ping", default-feature parachain-info = { path = "../../cumulus/parachains/pallets/parachain-info", default-features = false } # Polkadot dependencies -polkadot-parachain = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.27" } -xcm = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.27" } -xcm-builder = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.27" } -xcm-executor = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.27" } -pallet-xcm = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.27" } +polkadot-parachain = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.29" } +xcm = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.29" } +xcm-builder = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.29" } +xcm-executor = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.29" } +pallet-xcm = { git = "https://github.com/paritytech/polkadot", default-features = false, branch = "release-v0.9.29" } -orml-xcm = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, rev = "377213f750755cc48e80a3131eaae63b5eda8362"} -orml-xtokens = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, rev = "377213f750755cc48e80a3131eaae63b5eda8362"} -orml-xcm-support = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, rev = "377213f750755cc48e80a3131eaae63b5eda8362"} -orml-traits = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, rev = "377213f750755cc48e80a3131eaae63b5eda8362"} +orml-xcm = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, rev = "44fda4432b71f49ee59a650cf4775db895ab97af"} +orml-xtokens = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, rev = "44fda4432b71f49ee59a650cf4775db895ab97af"} +orml-xcm-support = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, rev = "44fda4432b71f49ee59a650cf4775db895ab97af"} +orml-traits = { git = "https://github.com/open-web3-stack/open-runtime-module-library", default-features = false, rev = "44fda4432b71f49ee59a650cf4775db895ab97af"} [build-dependencies] -substrate-wasm-builder = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" } +substrate-wasm-builder = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.29" } [features] default = [ "std" ] diff --git a/crust-collator/runtime/src/lib.rs b/crust-collator/runtime/src/lib.rs index eb463997..72336d3b 100644 --- a/crust-collator/runtime/src/lib.rs +++ b/crust-collator/runtime/src/lib.rs @@ -53,8 +53,9 @@ pub use frame_support::{ LockIdentifier, EitherOfDiverse, PrivilegeCmp, Currency, OnUnbalanced, Nothing }, weights::{ - constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND}, - DispatchClass, IdentityFee, Weight, ConstantMultiplier, + DispatchClass, + constants::WEIGHT_PER_SECOND, + IdentityFee, Weight, ConstantMultiplier, WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial, }, StorageValue, RuntimeDebug, @@ -68,6 +69,7 @@ use sp_core::H256; use sp_runtime::traits::Hash as THash; #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; +use weights::{BlockExecutionWeight, ExtrinsicBaseWeight}; // XCM imports use polkadot_parachain::primitives::Sibling; @@ -101,6 +103,7 @@ use smallvec::smallvec; use orml_xcm_support::MultiNativeAsset; use orml_traits::location::{RelativeReserveProvider, Reserve}; use orml_traits::parameter_type_with_key; +pub type XcmV2Weight = xcm::v2::Weight; type NegativeImbalance = >::NegativeImbalance; @@ -168,7 +171,7 @@ const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10); /// by Operational extrinsics. const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); /// We allow for 2 seconds of compute with a 6 second average block time. -const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND; +const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND.saturating_mul(2); parameter_types! { pub const BlockHashCount: BlockNumber = 250; @@ -415,7 +418,7 @@ impl pallet_proxy::Config for Runtime { type ProxyDepositBase = ProxyDepositBase; type ProxyDepositFactor = ProxyDepositFactor; type MaxProxies = MaxProxies; - type WeightInfo = weights::pallet_proxy::WeightInfo; + type WeightInfo = pallet_proxy::weights::SubstrateWeight; type MaxPending = MaxPending; type CallHasher = BlakeTwo256; type AnnouncementDepositBase = AnnouncementDepositBase; @@ -618,7 +621,7 @@ pub type XcmOriginToTransactDispatchOrigin = ( parameter_types! { // One XCM operation is 1_000_000_000 weight - almost certainly a conservative estimate. - pub UnitWeightCost: Weight = 1_000_000_000; + pub UnitWeightCost: XcmV2Weight = 1_000_000_000; // One ROC buys 1 second of weight. pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), ROC); pub const MaxInstructions: u32 = 100; @@ -1034,6 +1037,7 @@ parameter_types! { pub const TermDuration: BlockNumber = 3 * DAYS; pub const DesiredMembers: u32 = 7; pub const DesiredRunnersUp: u32 = 6; + pub const MaxVoters: u32 = 10 * 1000; pub const PhragmenElectionPalletId: LockIdentifier = *b"phrelect"; } @@ -1055,6 +1059,8 @@ impl pallet_elections_phragmen::Config for Runtime { type DesiredRunnersUp = DesiredRunnersUp; type TermDuration = TermDuration; type PalletId = PhragmenElectionPalletId; + type MaxVoters = MaxVoters; + type MaxCandidates = MaxCandidates; type WeightInfo = pallet_elections_phragmen::weights::SubstrateWeight; } @@ -1454,7 +1460,7 @@ where } parameter_types! { - pub const BaseXcmWeight: Weight = 100_000_000; + pub const BaseXcmWeight: XcmV2Weight = 100_000_000; pub const MaxAssetsForTransfer: usize = 2; // This is how we are going to detect whether the asset is a Reserve asset @@ -1722,6 +1728,23 @@ impl_runtime_apis! { } } + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi + for Runtime + { + fn query_call_info( + call: Call, + len: u32, + ) -> pallet_transaction_payment::RuntimeDispatchInfo { + TransactionPayment::query_call_info(call, len) + } + fn query_call_fee_details( + call: Call, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_call_fee_details(call, len) + } + } + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { fn account_nonce(account: AccountId) -> crust_parachain_primitives::Index { System::account_nonce(account) diff --git a/crust-collator/runtime/src/weights/block_weights.rs b/crust-collator/runtime/src/weights/block_weights.rs new file mode 100644 index 00000000..c0043073 --- /dev/null +++ b/crust-collator/runtime/src/weights/block_weights.rs @@ -0,0 +1,52 @@ +// This file is part of Substrate. + +// Copyright (C) 2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, Weight}, + }; + + parameter_types! { + /// Importing a block with 0 Extrinsics. + pub const BlockExecutionWeight: Weight = constants::WEIGHT_PER_NANOS.saturating_mul(5_000_000); + } + + #[cfg(test)] + mod test_weights { + use frame_support::weights::constants; + + /// Checks that the weight exists and is sane. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + let w = super::constants::BlockExecutionWeight::get(); + + // At least 100 µs. + assert!( + w.ref_time() >= 100u64 * constants::WEIGHT_PER_MICROS.ref_time(), + "Weight should be at least 100 µs." + ); + // At most 50 ms. + assert!( + w.ref_time() <= 50u64 * constants::WEIGHT_PER_MILLIS.ref_time(), + "Weight should be at most 50 ms." + ); + } + } +} diff --git a/crust-collator/runtime/src/weights/cumulus_pallet_xcmp_queue.rs b/crust-collator/runtime/src/weights/cumulus_pallet_xcmp_queue.rs new file mode 100644 index 00000000..40fa7ad4 --- /dev/null +++ b/crust-collator/runtime/src/weights/cumulus_pallet_xcmp_queue.rs @@ -0,0 +1,61 @@ +// Copyright 2021 Parity Technologies (UK) Ltd. +// This file is part of Cumulus. + +// Cumulus 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. + +// Cumulus 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 Cumulus. If not, see . + +//! Autogenerated weights for `cumulus_pallet_xcmp_queue` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-08-09, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `bm6`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 1024 + +// Executed Command: +// ./artifacts/polkadot-parachain +// benchmark +// pallet +// --chain=statemint-dev +// --execution=wasm +// --wasm-execution=compiled +// --pallet=cumulus_pallet_xcmp_queue +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/statemint/src/weights + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for `cumulus_pallet_xcmp_queue`. +pub struct WeightInfo(PhantomData); +impl cumulus_pallet_xcmp_queue::WeightInfo for WeightInfo { + // Storage: XcmpQueue QueueConfig (r:1 w:1) + fn set_config_with_u32() -> Weight { + Weight::from_ref_time(5_192_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } + // Storage: XcmpQueue QueueConfig (r:1 w:1) + fn set_config_with_weight() -> Weight { + Weight::from_ref_time(5_363_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } +} diff --git a/crust-collator/runtime/src/weights/extrinsic_weights.rs b/crust-collator/runtime/src/weights/extrinsic_weights.rs new file mode 100644 index 00000000..3ce6b73d --- /dev/null +++ b/crust-collator/runtime/src/weights/extrinsic_weights.rs @@ -0,0 +1,52 @@ +// This file is part of Substrate. + +// Copyright (C) 2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, Weight}, + }; + + parameter_types! { + /// Executing a NO-OP `System::remarks` Extrinsic. + pub const ExtrinsicBaseWeight: Weight = constants::WEIGHT_PER_NANOS.saturating_mul(125_000); + } + + #[cfg(test)] + mod test_weights { + use frame_support::weights::constants; + + /// Checks that the weight exists and is sane. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + let w = super::constants::ExtrinsicBaseWeight::get(); + + // At least 10 µs. + assert!( + w.ref_time() >= 10u64 * constants::WEIGHT_PER_MICROS.ref_time(), + "Weight should be at least 10 µs." + ); + // At most 1 ms. + assert!( + w.ref_time() <= constants::WEIGHT_PER_MILLIS.ref_time(), + "Weight should be at most 1 ms." + ); + } + } +} diff --git a/crust-collator/runtime/src/weights/frame_system.rs b/crust-collator/runtime/src/weights/frame_system.rs new file mode 100644 index 00000000..f2e55bc0 --- /dev/null +++ b/crust-collator/runtime/src/weights/frame_system.rs @@ -0,0 +1,90 @@ +// Copyright 2021 Parity Technologies (UK) Ltd. +// This file is part of Cumulus. + +// Cumulus 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. + +// Cumulus 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 Cumulus. If not, see . + +//! Autogenerated weights for `frame_system` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-09-21, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `bm6`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 1024 + +// Executed Command: +// ./artifacts/polkadot-parachain +// benchmark +// pallet +// --chain=statemint-dev +// --execution=wasm +// --wasm-execution=compiled +// --pallet=frame_system +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/statemint/src/weights/frame_system.rs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::{Weight}}; +use sp_std::marker::PhantomData; + +/// Weight functions for `frame_system`. +pub struct WeightInfo(PhantomData); +impl frame_system::WeightInfo for WeightInfo { + /// The range of component `b` is `[0, 3932160]`. + fn remark(_b: u32, ) -> Weight { + Weight::from_ref_time(0 as u64) + } + /// The range of component `b` is `[0, 3932160]`. + fn remark_with_event(b: u32, ) -> Weight { + Weight::from_ref_time(0 as u64) + // Standard Error: 0 + .saturating_add(Weight::from_ref_time(2_000 as u64).saturating_mul(b as u64)) + } + // Storage: System Digest (r:1 w:1) + // Storage: unknown [0x3a686561707061676573] (r:0 w:1) + fn set_heap_pages() -> Weight { + Weight::from_ref_time(8_784_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) + } + // Storage: Skipped Metadata (r:0 w:0) + /// The range of component `i` is `[1, 1000]`. + fn set_storage(i: u32, ) -> Weight { + Weight::from_ref_time(0 as u64) + // Standard Error: 1_000 + .saturating_add(Weight::from_ref_time(625_000 as u64).saturating_mul(i as u64)) + .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(i as u64))) + } + // Storage: Skipped Metadata (r:0 w:0) + /// The range of component `i` is `[1, 1000]`. + fn kill_storage(i: u32, ) -> Weight { + Weight::from_ref_time(0 as u64) + // Standard Error: 1_000 + .saturating_add(Weight::from_ref_time(553_000 as u64).saturating_mul(i as u64)) + .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(i as u64))) + } + // Storage: Skipped Metadata (r:0 w:0) + /// The range of component `p` is `[1, 1000]`. + fn kill_prefix(p: u32, ) -> Weight { + Weight::from_ref_time(0 as u64) + // Standard Error: 2_000 + .saturating_add(Weight::from_ref_time(1_138_000 as u64).saturating_mul(p as u64)) + .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(p as u64))) + } +} diff --git a/crust-collator/runtime/src/weights/mod.rs b/crust-collator/runtime/src/weights/mod.rs index cc09b40e..345227a4 100644 --- a/crust-collator/runtime/src/weights/mod.rs +++ b/crust-collator/runtime/src/weights/mod.rs @@ -1,7 +1,19 @@ +pub mod block_weights; +pub mod cumulus_pallet_xcmp_queue; +pub mod extrinsic_weights; +pub mod frame_system; +pub mod pallet_assets; pub mod pallet_balances; pub mod pallet_collator_selection; pub mod pallet_multisig; -pub mod pallet_proxy; pub mod pallet_session; pub mod pallet_timestamp; pub mod pallet_utility; +pub mod paritydb_weights; +pub mod rocksdb_weights; +pub mod xcm; + +pub use block_weights::constants::BlockExecutionWeight; +pub use extrinsic_weights::constants::ExtrinsicBaseWeight; +pub use paritydb_weights::constants::ParityDbWeight; +pub use rocksdb_weights::constants::RocksDbWeight; diff --git a/crust-collator/runtime/src/weights/pallet_assets.rs b/crust-collator/runtime/src/weights/pallet_assets.rs new file mode 100644 index 00000000..445d1b94 --- /dev/null +++ b/crust-collator/runtime/src/weights/pallet_assets.rs @@ -0,0 +1,235 @@ +// Copyright 2021 Parity Technologies (UK) Ltd. +// This file is part of Cumulus. + +// Cumulus 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. + +// Cumulus 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 Cumulus. If not, see . + +//! Autogenerated weights for `pallet_assets` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-09-21, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `bm6`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 1024 + +// Executed Command: +// ./artifacts/polkadot-parachain +// benchmark +// pallet +// --chain=statemint-dev +// --execution=wasm +// --wasm-execution=compiled +// --pallet=pallet_assets +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/statemint/src/weights/pallet_assets.rs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::{Weight}}; +use sp_std::marker::PhantomData; + +/// Weight functions for `pallet_assets`. +pub struct WeightInfo(PhantomData); +impl pallet_assets::WeightInfo for WeightInfo { + // Storage: Assets Asset (r:1 w:1) + fn create() -> Weight { + Weight::from_ref_time(30_406_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } + // Storage: Assets Asset (r:1 w:1) + fn force_create() -> Weight { + Weight::from_ref_time(18_225_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } + // 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) + /// The range of component `c` is `[0, 5000]`. + /// The range of component `s` is `[0, 5000]`. + /// The range of component `a` is `[0, 500]`. + fn destroy(c: u32, s: u32, a: u32, ) -> Weight { + Weight::from_ref_time(0 as u64) + // Standard Error: 96_000 + .saturating_add(Weight::from_ref_time(15_834_000 as u64).saturating_mul(c as u64)) + // Standard Error: 96_000 + .saturating_add(Weight::from_ref_time(17_275_000 as u64).saturating_mul(s as u64)) + // Standard Error: 966_000 + .saturating_add(Weight::from_ref_time(35_635_000 as u64).saturating_mul(a as u64)) + .saturating_add(T::DbWeight::get().reads(5 as u64)) + .saturating_add(T::DbWeight::get().reads((2 as u64).saturating_mul(c as u64))) + .saturating_add(T::DbWeight::get().reads((2 as u64).saturating_mul(s as u64))) + .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(a as u64))) + .saturating_add(T::DbWeight::get().writes(2 as u64)) + .saturating_add(T::DbWeight::get().writes((2 as u64).saturating_mul(c as u64))) + .saturating_add(T::DbWeight::get().writes((2 as u64).saturating_mul(s as u64))) + .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(a as u64))) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + fn mint() -> Weight { + Weight::from_ref_time(36_535_000 as u64) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + fn burn() -> Weight { + Weight::from_ref_time(39_821_000 as u64) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:2 w:2) + // Storage: System Account (r:1 w:1) + fn transfer() -> Weight { + Weight::from_ref_time(52_287_000 as u64) + .saturating_add(T::DbWeight::get().reads(4 as u64)) + .saturating_add(T::DbWeight::get().writes(4 as u64)) + } + // 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 { + Weight::from_ref_time(45_347_000 as u64) + .saturating_add(T::DbWeight::get().reads(4 as u64)) + .saturating_add(T::DbWeight::get().writes(4 as u64)) + } + // 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 { + Weight::from_ref_time(52_369_000 as u64) + .saturating_add(T::DbWeight::get().reads(4 as u64)) + .saturating_add(T::DbWeight::get().writes(4 as u64)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Account (r:1 w:1) + fn freeze() -> Weight { + Weight::from_ref_time(25_896_000 as u64) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Account (r:1 w:1) + fn thaw() -> Weight { + Weight::from_ref_time(25_630_000 as u64) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } + // Storage: Assets Asset (r:1 w:1) + fn freeze_asset() -> Weight { + Weight::from_ref_time(22_340_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } + // Storage: Assets Asset (r:1 w:1) + fn thaw_asset() -> Weight { + Weight::from_ref_time(22_204_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:0) + fn transfer_ownership() -> Weight { + Weight::from_ref_time(24_971_000 as u64) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } + // Storage: Assets Asset (r:1 w:1) + fn set_team() -> Weight { + Weight::from_ref_time(24_079_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + fn set_metadata(_n: u32, s: u32, ) -> Weight { + Weight::from_ref_time(36_505_000 as u64) + // Standard Error: 1_000 + .saturating_add(Weight::from_ref_time(4_000 as u64).saturating_mul(s as u64)) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + fn clear_metadata() -> Weight { + Weight::from_ref_time(38_931_000 as u64) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + fn force_set_metadata(_n: u32, s: u32, ) -> Weight { + Weight::from_ref_time(25_165_000 as u64) + // Standard Error: 5_000 + .saturating_add(Weight::from_ref_time(9_000 as u64).saturating_mul(s as u64)) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + fn force_clear_metadata() -> Weight { + Weight::from_ref_time(40_301_000 as u64) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } + // Storage: Assets Asset (r:1 w:1) + fn force_asset_status() -> Weight { + Weight::from_ref_time(23_393_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Approvals (r:1 w:1) + fn approve_transfer() -> Weight { + Weight::from_ref_time(39_465_000 as u64) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) + } + // 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 { + Weight::from_ref_time(69_070_000 as u64) + .saturating_add(T::DbWeight::get().reads(5 as u64)) + .saturating_add(T::DbWeight::get().writes(5 as u64)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Approvals (r:1 w:1) + fn cancel_approval() -> Weight { + Weight::from_ref_time(40_461_000 as u64) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) + } + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Approvals (r:1 w:1) + fn force_cancel_approval() -> Weight { + Weight::from_ref_time(41_788_000 as u64) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) + } +} diff --git a/crust-collator/runtime/src/weights/pallet_balances.rs b/crust-collator/runtime/src/weights/pallet_balances.rs index 9511a017..46524721 100644 --- a/crust-collator/runtime/src/weights/pallet_balances.rs +++ b/crust-collator/runtime/src/weights/pallet_balances.rs @@ -1,12 +1,30 @@ -//! Autogenerated weights for pallet_balances +// Copyright 2021 Parity Technologies (UK) Ltd. +// This file is part of Cumulus. + +// Cumulus 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. + +// Cumulus 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 Cumulus. If not, see . + +//! Autogenerated weights for `pallet_balances` //! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 -//! DATE: 2021-05-31, STEPS: `[50, ]`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 128 +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-09-21, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `bm6`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 1024 // Executed Command: -// ./target/release/statemint +// ./artifacts/polkadot-parachain // benchmark +// pallet // --chain=statemint-dev // --execution=wasm // --wasm-execution=compiled @@ -14,52 +32,60 @@ // --extrinsic=* // --steps=50 // --repeat=20 -// --raw -// --output=./runtime/statemint/src/weights/ +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/statemint/src/weights/pallet_balances.rs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::Weight}; +use frame_support::{traits::Get, weights::{Weight}}; use sp_std::marker::PhantomData; -/// Weight functions for pallet_balances. +/// Weight functions for `pallet_balances`. pub struct WeightInfo(PhantomData); impl pallet_balances::WeightInfo for WeightInfo { + // Storage: System Account (r:1 w:1) fn transfer() -> Weight { - (79_601_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) + Weight::from_ref_time(48_009_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) } + // Storage: System Account (r:1 w:1) fn transfer_keep_alive() -> Weight { - (58_429_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) + Weight::from_ref_time(35_939_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) } + // Storage: System Account (r:1 w:1) fn set_balance_creating() -> Weight { - (29_124_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) + Weight::from_ref_time(26_600_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) } + // Storage: System Account (r:1 w:1) fn set_balance_killing() -> Weight { - (36_476_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) + Weight::from_ref_time(30_092_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) } + // Storage: System Account (r:2 w:2) fn force_transfer() -> Weight { - (78_772_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) + Weight::from_ref_time(47_435_000 as u64) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) } + // Storage: System Account (r:1 w:1) fn transfer_all() -> Weight { - (84_170_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) + Weight::from_ref_time(41_179_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) } // Storage: System Account (r:1 w:1) fn force_unreserve() -> Weight { - (27_766_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) + Weight::from_ref_time(22_413_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) } } diff --git a/crust-collator/runtime/src/weights/pallet_collator_selection.rs b/crust-collator/runtime/src/weights/pallet_collator_selection.rs index 328b8c12..2a95ad7a 100644 --- a/crust-collator/runtime/src/weights/pallet_collator_selection.rs +++ b/crust-collator/runtime/src/weights/pallet_collator_selection.rs @@ -1,12 +1,30 @@ -//! Autogenerated weights for pallet_collator_selection +// Copyright 2021 Parity Technologies (UK) Ltd. +// This file is part of Cumulus. + +// Cumulus 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. + +// Cumulus 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 Cumulus. If not, see . + +//! Autogenerated weights for `pallet_collator_selection` //! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 -//! DATE: 2021-05-31, STEPS: `[50, ]`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 128 +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-09-21, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `bm6`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 1024 // Executed Command: -// ./target/release/statemint +// ./artifacts/polkadot-parachain // benchmark +// pallet // --chain=statemint-dev // --execution=wasm // --wasm-execution=compiled @@ -14,58 +32,87 @@ // --extrinsic=* // --steps=50 // --repeat=20 -// --raw -// --output=./runtime/statemint/src/weights/ +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/statemint/src/weights/pallet_collator_selection.rs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::Weight}; +use frame_support::{traits::Get, weights::{Weight}}; use sp_std::marker::PhantomData; -/// Weight functions for pallet_collator_selection. +/// Weight functions for `pallet_collator_selection`. pub struct WeightInfo(PhantomData); impl pallet_collator_selection::WeightInfo for WeightInfo { - fn set_invulnerables(b: u32) -> Weight { - (18_563_000 as Weight) - // Standard Error: 0 - .saturating_add((68_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) + // Storage: Session NextKeys (r:1 w:0) + // Storage: CollatorSelection Invulnerables (r:0 w:1) + /// The range of component `b` is `[1, 100]`. + fn set_invulnerables(b: u32, ) -> Weight { + Weight::from_ref_time(22_504_000 as u64) + // Standard Error: 2_000 + .saturating_add(Weight::from_ref_time(2_465_000 as u64).saturating_mul(b as u64)) + .saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(b as u64))) + .saturating_add(T::DbWeight::get().writes(1 as u64)) } + // Storage: CollatorSelection DesiredCandidates (r:0 w:1) fn set_desired_candidates() -> Weight { - (16_363_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight)) + Weight::from_ref_time(14_572_000 as u64) + .saturating_add(T::DbWeight::get().writes(1 as u64)) } + // Storage: CollatorSelection CandidacyBond (r:0 w:1) fn set_candidacy_bond() -> Weight { - (16_840_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight)) + Weight::from_ref_time(14_791_000 as u64) + .saturating_add(T::DbWeight::get().writes(1 as u64)) } - fn register_as_candidate(c: u32) -> Weight { - (71_196_000 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) + // Storage: CollatorSelection LastAuthoredBlock (r:0 w:1) + /// The range of component `c` is `[1, 1000]`. + fn register_as_candidate(c: u32, ) -> Weight { + Weight::from_ref_time(60_440_000 as u64) // Standard Error: 0 - .saturating_add((198_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) + .saturating_add(Weight::from_ref_time(174_000 as u64).saturating_mul(c as u64)) + .saturating_add(T::DbWeight::get().reads(5 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) } - fn leave_intent(c: u32) -> Weight { - (55_336_000 as Weight) - // Standard Error: 0 - .saturating_add((151_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) + // Storage: CollatorSelection Candidates (r:1 w:1) + // Storage: CollatorSelection LastAuthoredBlock (r:0 w:1) + /// The range of component `c` is `[6, 1000]`. + fn leave_intent(c: u32, ) -> Weight { + Weight::from_ref_time(66_209_000 as u64) + // Standard Error: 1_000 + .saturating_add(Weight::from_ref_time(157_000 as u64).saturating_mul(c as u64)) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) } + // Storage: System Account (r:2 w:2) + // Storage: System BlockWeight (r:1 w:1) + // Storage: CollatorSelection LastAuthoredBlock (r:0 w:1) fn note_author() -> Weight { - (71_461_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) + Weight::from_ref_time(35_644_000 as u64) + .saturating_add(T::DbWeight::get().reads(3 as u64)) + .saturating_add(T::DbWeight::get().writes(4 as u64)) } - fn new_session(r: u32, c: u32) -> Weight { - (0 as Weight) - // Standard Error: 1_010_000 - .saturating_add((109_961_000 as Weight).saturating_mul(r as Weight)) - // Standard Error: 1_010_000 - .saturating_add((151_952_000 as Weight).saturating_mul(c as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r 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_mul(r as Weight))) - .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(c as Weight))) + // Storage: CollatorSelection Candidates (r:1 w:1) + // Storage: CollatorSelection LastAuthoredBlock (r:1000 w:1) + // Storage: System Account (r:1 w:1) + // Storage: CollatorSelection Invulnerables (r:1 w:0) + // Storage: System BlockWeight (r:1 w:1) + /// The range of component `r` is `[1, 1000]`. + /// The range of component `c` is `[1, 1000]`. + fn new_session(r: u32, c: u32, ) -> Weight { + Weight::from_ref_time(0 as u64) + // Standard Error: 1_251_000 + .saturating_add(Weight::from_ref_time(6_889_000 as u64).saturating_mul(r as u64)) + // Standard Error: 1_251_000 + .saturating_add(Weight::from_ref_time(32_938_000 as u64).saturating_mul(c as u64)) + .saturating_add(T::DbWeight::get().reads((2 as u64).saturating_mul(c as u64))) + .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(r as u64))) + .saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(c as u64))) } } diff --git a/crust-collator/runtime/src/weights/pallet_multisig.rs b/crust-collator/runtime/src/weights/pallet_multisig.rs index b79a8e0c..8c22cfaa 100644 --- a/crust-collator/runtime/src/weights/pallet_multisig.rs +++ b/crust-collator/runtime/src/weights/pallet_multisig.rs @@ -1,12 +1,30 @@ -//! Autogenerated weights for pallet_multisig +// Copyright 2021 Parity Technologies (UK) Ltd. +// This file is part of Cumulus. + +// Cumulus 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. + +// Cumulus 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 Cumulus. If not, see . + +//! Autogenerated weights for `pallet_multisig` //! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 -//! DATE: 2021-05-31, STEPS: `[50, ]`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 128 +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-09-21, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `bm6`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 1024 // Executed Command: -// ./target/release/statemint +// ./artifacts/polkadot-parachain // benchmark +// pallet // --chain=statemint-dev // --execution=wasm // --wasm-execution=compiled @@ -14,94 +32,131 @@ // --extrinsic=* // --steps=50 // --repeat=20 -// --raw -// --output=./runtime/statemint/src/weights/ +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/statemint/src/weights/pallet_multisig.rs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::Weight}; +use frame_support::{traits::Get, weights::{Weight}}; use sp_std::marker::PhantomData; -/// Weight functions for pallet_multisig. +/// Weight functions for `pallet_multisig`. pub struct WeightInfo(PhantomData); impl pallet_multisig::WeightInfo for WeightInfo { - fn as_multi_threshold_1(z: u32) -> Weight { - (14_936_000 as Weight) + /// The range of component `z` is `[0, 10000]`. + fn as_multi_threshold_1(z: u32, ) -> Weight { + Weight::from_ref_time(21_264_000 as u64) // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) + .saturating_add(Weight::from_ref_time(1_000 as u64).saturating_mul(z as u64)) } - fn as_multi_create(s: u32, z: u32) -> Weight { - (56_090_000 as Weight) - // Standard Error: 1_000 - .saturating_add((63_000 as Weight).saturating_mul(s as Weight)) + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) + /// The range of component `s` is `[2, 100]`. + /// The range of component `z` is `[0, 10000]`. + fn as_multi_create(s: u32, z: u32, ) -> Weight { + Weight::from_ref_time(40_726_000 as u64) + // Standard Error: 0 + .saturating_add(Weight::from_ref_time(100_000 as u64).saturating_mul(s as u64)) // 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)) + .saturating_add(Weight::from_ref_time(1_000 as u64).saturating_mul(z as u64)) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) } - fn as_multi_create_store(s: u32, z: u32) -> Weight { - (62_519_000 as Weight) + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) + /// The range of component `s` is `[2, 100]`. + /// The range of component `z` is `[0, 10000]`. + fn as_multi_create_store(s: u32, z: u32, ) -> Weight { + Weight::from_ref_time(42_052_000 as u64) // Standard Error: 1_000 - .saturating_add((66_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(Weight::from_ref_time(109_000 as u64).saturating_mul(s as u64)) // 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(2 as Weight)) + .saturating_add(Weight::from_ref_time(2_000 as u64).saturating_mul(z as u64)) + .saturating_add(T::DbWeight::get().reads(3 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) } - fn as_multi_approve(s: u32, z: u32) -> Weight { - (30_781_000 as Weight) + // Storage: Multisig Multisigs (r:1 w:1) + /// The range of component `s` is `[3, 100]`. + /// The range of component `z` is `[0, 10000]`. + fn as_multi_approve(s: u32, z: u32, ) -> Weight { + Weight::from_ref_time(29_056_000 as u64) // Standard Error: 0 - .saturating_add((111_000 as Weight).saturating_mul(s as Weight)) + .saturating_add(Weight::from_ref_time(112_000 as u64).saturating_mul(s as u64)) // 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)) + .saturating_add(Weight::from_ref_time(1_000 as u64).saturating_mul(z as u64)) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) } - fn as_multi_approve_store(s: u32, z: u32) -> Weight { - (60_393_000 as Weight) - // Standard Error: 0 - .saturating_add((118_000 as Weight).saturating_mul(s as Weight)) + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + /// The range of component `s` is `[3, 100]`. + /// The range of component `z` is `[0, 10000]`. + fn as_multi_approve_store(s: u32, z: u32, ) -> Weight { + Weight::from_ref_time(44_006_000 as u64) + // Standard Error: 1_000 + .saturating_add(Weight::from_ref_time(106_000 as u64).saturating_mul(s as u64)) // Standard Error: 0 - .saturating_add((3_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)) + .saturating_add(Weight::from_ref_time(2_000 as u64).saturating_mul(z as u64)) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) } - fn as_multi_complete(s: u32, z: u32) -> Weight { - (81_704_000 as Weight) - // Standard Error: 1_000 - .saturating_add((248_000 as Weight).saturating_mul(s as Weight)) + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + // Storage: System Account (r:1 w:1) + /// The range of component `s` is `[2, 100]`. + /// The range of component `z` is `[0, 10000]`. + fn as_multi_complete(s: u32, z: u32, ) -> Weight { + Weight::from_ref_time(53_470_000 as u64) // Standard Error: 0 - .saturating_add((5_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)) + .saturating_add(Weight::from_ref_time(136_000 as u64).saturating_mul(s as u64)) + // Standard Error: 0 + .saturating_add(Weight::from_ref_time(2_000 as u64).saturating_mul(z as u64)) + .saturating_add(T::DbWeight::get().reads(3 as u64)) + .saturating_add(T::DbWeight::get().writes(3 as u64)) } - fn approve_as_multi_create(s: u32) -> Weight { - (55_585_000 as Weight) + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) + /// The range of component `s` is `[2, 100]`. + fn approve_as_multi_create(s: u32, ) -> Weight { + Weight::from_ref_time(36_826_000 as u64) // Standard Error: 1_000 - .saturating_add((115_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)) + .saturating_add(Weight::from_ref_time(125_000 as u64).saturating_mul(s as u64)) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) } - fn approve_as_multi_approve(s: u32) -> Weight { - (33_483_000 as Weight) - // Standard Error: 1_000 - .saturating_add((82_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:0) + /// The range of component `s` is `[2, 100]`. + fn approve_as_multi_approve(s: u32, ) -> Weight { + Weight::from_ref_time(26_801_000 as u64) + // Standard Error: 0 + .saturating_add(Weight::from_ref_time(126_000 as u64).saturating_mul(s as u64)) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) } - fn approve_as_multi_complete(s: u32) -> Weight { - (154_732_000 as Weight) + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + // Storage: System Account (r:1 w:1) + /// The range of component `s` is `[2, 100]`. + fn approve_as_multi_complete(s: u32, ) -> Weight { + Weight::from_ref_time(67_374_000 as u64) // Standard Error: 1_000 - .saturating_add((253_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)) + .saturating_add(Weight::from_ref_time(152_000 as u64).saturating_mul(s as u64)) + .saturating_add(T::DbWeight::get().reads(3 as u64)) + .saturating_add(T::DbWeight::get().writes(3 as u64)) } - fn cancel_as_multi(s: u32) -> Weight { - (104_447_000 as Weight) + // Storage: Multisig Multisigs (r:1 w:1) + // Storage: Multisig Calls (r:1 w:1) + /// The range of component `s` is `[2, 100]`. + fn cancel_as_multi(s: u32, ) -> Weight { + Weight::from_ref_time(54_556_000 as u64) // Standard Error: 1_000 - .saturating_add((114_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)) + .saturating_add(Weight::from_ref_time(125_000 as u64).saturating_mul(s as u64)) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) } } diff --git a/crust-collator/runtime/src/weights/pallet_proxy.rs b/crust-collator/runtime/src/weights/pallet_proxy.rs deleted file mode 100644 index 493ebdfb..00000000 --- a/crust-collator/runtime/src/weights/pallet_proxy.rs +++ /dev/null @@ -1,106 +0,0 @@ -//! Autogenerated weights for pallet_proxy -//! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 -//! DATE: 2021-05-31, STEPS: `[50, ]`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 128 - -// Executed Command: -// ./target/release/statemint -// benchmark -// --chain=statemint-dev -// --execution=wasm -// --wasm-execution=compiled -// --pallet=pallet_proxy -// --extrinsic=* -// --steps=50 -// --repeat=20 -// --raw -// --output=./runtime/statemint/src/weights/ - -#![allow(unused_parens)] -#![allow(unused_imports)] - -use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; - -/// Weight functions for pallet_proxy. -pub struct WeightInfo(PhantomData); -impl pallet_proxy::WeightInfo for WeightInfo { - fn proxy(p: u32) -> Weight { - (27_585_000 as Weight) - // Standard Error: 1_000 - .saturating_add((203_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - } - fn proxy_announced(a: u32, p: u32) -> Weight { - (61_093_000 as Weight) - // Standard Error: 2_000 - .saturating_add((680_000 as Weight).saturating_mul(a as Weight)) - // Standard Error: 2_000 - .saturating_add((201_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - fn remove_announcement(a: u32, p: u32) -> Weight { - (39_494_000 as Weight) - // Standard Error: 2_000 - .saturating_add((686_000 as Weight).saturating_mul(a as Weight)) - // Standard Error: 2_000 - .saturating_add((1_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - fn reject_announcement(a: u32, p: u32) -> Weight { - (39_817_000 as Weight) - // Standard Error: 2_000 - .saturating_add((685_000 as Weight).saturating_mul(a as Weight)) - // Standard Error: 2_000 - .saturating_add((1_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - fn announce(a: u32, p: u32) -> Weight { - (54_835_000 as Weight) - // Standard Error: 2_000 - .saturating_add((684_000 as Weight).saturating_mul(a as Weight)) - // Standard Error: 2_000 - .saturating_add((205_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - fn add_proxy(p: u32) -> Weight { - (37_625_000 as Weight) - // Standard Error: 2_000 - .saturating_add((300_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn remove_proxy(p: u32) -> Weight { - (36_945_000 as Weight) - // Standard Error: 3_000 - .saturating_add((325_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn remove_proxies(p: u32) -> Weight { - (35_128_000 as Weight) - // Standard Error: 1_000 - .saturating_add((209_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn anonymous(p: u32) -> Weight { - (51_624_000 as Weight) - // Standard Error: 1_000 - .saturating_add((41_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)) - } - fn kill_anonymous(p: u32) -> Weight { - (37_469_000 as Weight) - // Standard Error: 1_000 - .saturating_add((204_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } -} diff --git a/crust-collator/runtime/src/weights/pallet_session.rs b/crust-collator/runtime/src/weights/pallet_session.rs index f8f9ae73..3cda2056 100644 --- a/crust-collator/runtime/src/weights/pallet_session.rs +++ b/crust-collator/runtime/src/weights/pallet_session.rs @@ -1,12 +1,30 @@ -//! Autogenerated weights for pallet_session +// Copyright 2021 Parity Technologies (UK) Ltd. +// This file is part of Cumulus. + +// Cumulus 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. + +// Cumulus 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 Cumulus. If not, see . + +//! Autogenerated weights for `pallet_session` //! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 -//! DATE: 2021-06-08, STEPS: `[50, ]`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 128 +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-09-21, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `bm6`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 1024 // Executed Command: -// ./target/release/polkadot-collator +// ./artifacts/polkadot-parachain // benchmark +// pallet // --chain=statemint-dev // --execution=wasm // --wasm-execution=compiled @@ -14,26 +32,32 @@ // --extrinsic=* // --steps=50 // --repeat=20 -// --raw -// --output=./polkadot-parachains/statemint-runtime/src/weights +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/statemint/src/weights/pallet_session.rs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::Weight}; +use frame_support::{traits::Get, weights::{Weight}}; use sp_std::marker::PhantomData; -/// Weight functions for pallet_session. +/// Weight functions for `pallet_session`. pub struct WeightInfo(PhantomData); impl pallet_session::WeightInfo for WeightInfo { + // Storage: Session NextKeys (r:1 w:1) + // Storage: Session KeyOwner (r:1 w:1) fn set_keys() -> Weight { - (25_040_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) + Weight::from_ref_time(24_731_000 as u64) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) } + // Storage: Session NextKeys (r:1 w:1) + // Storage: Session KeyOwner (r:0 w:1) fn purge_keys() -> Weight { - (17_551_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) + Weight::from_ref_time(20_852_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) } } diff --git a/crust-collator/runtime/src/weights/pallet_timestamp.rs b/crust-collator/runtime/src/weights/pallet_timestamp.rs index bd8c76a4..784b0043 100644 --- a/crust-collator/runtime/src/weights/pallet_timestamp.rs +++ b/crust-collator/runtime/src/weights/pallet_timestamp.rs @@ -1,12 +1,30 @@ -//! Autogenerated weights for pallet_timestamp +// Copyright 2021 Parity Technologies (UK) Ltd. +// This file is part of Cumulus. + +// Cumulus 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. + +// Cumulus 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 Cumulus. If not, see . + +//! Autogenerated weights for `pallet_timestamp` //! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 -//! DATE: 2021-05-31, STEPS: `[50, ]`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 128 +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-09-21, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `bm6`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 1024 // Executed Command: -// ./target/release/statemint +// ./artifacts/polkadot-parachain // benchmark +// pallet // --chain=statemint-dev // --execution=wasm // --wasm-execution=compiled @@ -14,24 +32,27 @@ // --extrinsic=* // --steps=50 // --repeat=20 -// --raw -// --output=./runtime/statemint/src/weights/ +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/statemint/src/weights/pallet_timestamp.rs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::Weight}; +use frame_support::{traits::Get, weights::{Weight}}; use sp_std::marker::PhantomData; -/// Weight functions for pallet_timestamp. +/// Weight functions for `pallet_timestamp`. pub struct WeightInfo(PhantomData); impl pallet_timestamp::WeightInfo for WeightInfo { + // Storage: Timestamp Now (r:1 w:1) fn set() -> Weight { - (7_687_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) + Weight::from_ref_time(7_972_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) } fn on_finalize() -> Weight { - (4_303_000 as Weight) + Weight::from_ref_time(4_333_000 as u64) } } diff --git a/crust-collator/runtime/src/weights/pallet_utility.rs b/crust-collator/runtime/src/weights/pallet_utility.rs index e9d68484..d504d467 100644 --- a/crust-collator/runtime/src/weights/pallet_utility.rs +++ b/crust-collator/runtime/src/weights/pallet_utility.rs @@ -1,12 +1,30 @@ -//! Autogenerated weights for pallet_utility +// Copyright 2021 Parity Technologies (UK) Ltd. +// This file is part of Cumulus. + +// Cumulus 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. + +// Cumulus 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 Cumulus. If not, see . + +//! Autogenerated weights for `pallet_utility` //! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 -//! DATE: 2021-05-31, STEPS: `[50, ]`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 128 +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-09-21, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `bm6`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 1024 // Executed Command: -// ./target/release/statemint +// ./artifacts/polkadot-parachain // benchmark +// pallet // --chain=statemint-dev // --execution=wasm // --wasm-execution=compiled @@ -14,39 +32,42 @@ // --extrinsic=* // --steps=50 // --repeat=20 -// --raw -// --output=./runtime/statemint/src/weights/ +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/statemint/src/weights/pallet_utility.rs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -use frame_support::{traits::Get, weights::Weight}; +use frame_support::{traits::Get, weights::{Weight}}; use sp_std::marker::PhantomData; -/// Weight functions for pallet_utility. +/// Weight functions for `pallet_utility`. pub struct WeightInfo(PhantomData); impl pallet_utility::WeightInfo for WeightInfo { - fn batch(c: u32) -> Weight { - (15_408_000 as Weight) - // Standard Error: 0 - .saturating_add((4_571_000 as Weight).saturating_mul(c as Weight)) + /// The range of component `c` is `[0, 1000]`. + fn batch(c: u32, ) -> Weight { + Weight::from_ref_time(21_360_000 as u64) + // Standard Error: 1_000 + .saturating_add(Weight::from_ref_time(3_860_000 as u64).saturating_mul(c as u64)) } fn as_derivative() -> Weight { - (7_817_000 as Weight) + Weight::from_ref_time(6_860_000 as u64) } - fn batch_all(c: u32) -> Weight { - (16_520_000 as Weight) - // Standard Error: 0 - .saturating_add((4_571_000 as Weight).saturating_mul(c as Weight)) + /// The range of component `c` is `[0, 1000]`. + fn batch_all(c: u32, ) -> Weight { + Weight::from_ref_time(14_622_000 as u64) + // Standard Error: 3_000 + .saturating_add(Weight::from_ref_time(4_028_000 as u64).saturating_mul(c as u64)) } fn dispatch_as() -> Weight { - (8_463_000 as Weight) + Weight::from_ref_time(15_303_000 as u64) } + /// The range of component `c` is `[0, 1000]`. fn force_batch(c: u32, ) -> Weight { - (13_470_000 as Weight) - // Standard Error: 1_000 - .saturating_add((4_229_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)) + Weight::from_ref_time(19_985_000 as u64) + // Standard Error: 2_000 + .saturating_add(Weight::from_ref_time(3_859_000 as u64).saturating_mul(c as u64)) } } diff --git a/crust-collator/runtime/src/weights/paritydb_weights.rs b/crust-collator/runtime/src/weights/paritydb_weights.rs new file mode 100644 index 00000000..dca7d348 --- /dev/null +++ b/crust-collator/runtime/src/weights/paritydb_weights.rs @@ -0,0 +1,63 @@ +// This file is part of Substrate. + +// Copyright (C) 2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, RuntimeDbWeight}, + }; + + parameter_types! { + /// `ParityDB` can be enabled with a feature flag, but is still experimental. These weights + /// are available for brave runtime engineers who may want to try this out as default. + pub const ParityDbWeight: RuntimeDbWeight = RuntimeDbWeight { + read: 8_000 * constants::WEIGHT_PER_NANOS.ref_time(), + write: 50_000 * constants::WEIGHT_PER_NANOS.ref_time(), + }; + } + + #[cfg(test)] + mod test_db_weights { + use super::constants::ParityDbWeight as W; + use frame_support::weights::constants; + + /// Checks that all weights exist and have sane values. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + // At least 1 µs. + assert!( + W::get().reads(1).ref_time() >= constants::WEIGHT_PER_MICROS.ref_time(), + "Read weight should be at least 1 µs." + ); + assert!( + W::get().writes(1).ref_time() >= constants::WEIGHT_PER_MICROS.ref_time(), + "Write weight should be at least 1 µs." + ); + // At most 1 ms. + assert!( + W::get().reads(1).ref_time() <= constants::WEIGHT_PER_MILLIS.ref_time(), + "Read weight should be at most 1 ms." + ); + assert!( + W::get().writes(1).ref_time() <= constants::WEIGHT_PER_MILLIS.ref_time(), + "Write weight should be at most 1 ms." + ); + } + } +} diff --git a/crust-collator/runtime/src/weights/rocksdb_weights.rs b/crust-collator/runtime/src/weights/rocksdb_weights.rs new file mode 100644 index 00000000..87867ebf --- /dev/null +++ b/crust-collator/runtime/src/weights/rocksdb_weights.rs @@ -0,0 +1,63 @@ +// This file is part of Substrate. + +// Copyright (C) 2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, RuntimeDbWeight}, + }; + + parameter_types! { + /// By default, Substrate uses `RocksDB`, so this will be the weight used throughout + /// the runtime. + pub const RocksDbWeight: RuntimeDbWeight = RuntimeDbWeight { + read: 25_000 * constants::WEIGHT_PER_NANOS.ref_time(), + write: 100_000 * constants::WEIGHT_PER_NANOS.ref_time(), + }; + } + + #[cfg(test)] + mod test_db_weights { + use super::constants::RocksDbWeight as W; + use frame_support::weights::constants; + + /// Checks that all weights exist and have sane values. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + // At least 1 µs. + assert!( + W::get().reads(1).ref_time() >= constants::WEIGHT_PER_MICROS.ref_time(), + "Read weight should be at least 1 µs." + ); + assert!( + W::get().writes(1).ref_time() >= constants::WEIGHT_PER_MICROS.ref_time(), + "Write weight should be at least 1 µs." + ); + // At most 1 ms. + assert!( + W::get().reads(1).ref_time() <= constants::WEIGHT_PER_MILLIS.ref_time(), + "Read weight should be at most 1 ms." + ); + assert!( + W::get().writes(1).ref_time() <= constants::WEIGHT_PER_MILLIS.ref_time(), + "Write weight should be at most 1 ms." + ); + } + } +} diff --git a/crust-collator/runtime/src/weights/xcm/cumulus_pallet_xcmp_queue.rs b/crust-collator/runtime/src/weights/xcm/cumulus_pallet_xcmp_queue.rs new file mode 100644 index 00000000..db40762b --- /dev/null +++ b/crust-collator/runtime/src/weights/xcm/cumulus_pallet_xcmp_queue.rs @@ -0,0 +1,63 @@ +// Copyright 2022 Parity Technologies (UK) Ltd. +// This file is part of Cumulus. + +// Cumulus 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. + +// Cumulus 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 Cumulus. If not, see . + + +//! Autogenerated weights for `cumulus_pallet_xcmp_queue` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-09-21, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `bm6`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 1024 + +// Executed Command: +// ./artifacts/polkadot-parachain +// benchmark +// pallet +// --template=./templates/xcm-bench-template.hbs +// --chain=statemint-dev +// --execution=wasm +// --wasm-execution=compiled +// --pallet=cumulus_pallet_xcmp_queue +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/statemint/src/weights/xcm/cumulus_pallet_xcmp_queue.rs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weights for `cumulus_pallet_xcmp_queue`. +pub struct WeightInfo(PhantomData); +impl WeightInfo { + // Storage: XcmpQueue QueueConfig (r:1 w:1) + pub(crate) fn set_config_with_u32() -> Weight { + Weight::from_ref_time(7_362_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } + // Storage: XcmpQueue QueueConfig (r:1 w:1) + pub(crate) fn set_config_with_weight() -> Weight { + Weight::from_ref_time(7_234_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } +} diff --git a/crust-collator/runtime/src/weights/xcm/mod.rs b/crust-collator/runtime/src/weights/xcm/mod.rs new file mode 100644 index 00000000..1a0ffcdb --- /dev/null +++ b/crust-collator/runtime/src/weights/xcm/mod.rs @@ -0,0 +1,188 @@ +// Copyright 2022 Parity Technologies (UK) Ltd. +// This file is part of Cumulus. + +// Cumulus 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. + +// Cumulus 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 Cumulus. If not, see . + +mod pallet_xcm_benchmarks_fungible; +mod pallet_xcm_benchmarks_generic; + +use crate::Runtime; +use frame_support::weights::Weight; +use pallet_xcm_benchmarks_fungible::WeightInfo as XcmFungibleWeight; +use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; +use sp_std::{cmp, prelude::*}; +use xcm::{ + latest::{prelude::*, Weight as XCMWeight}, + DoubleEncoded, +}; + +trait WeighMultiAssets { + fn weigh_multi_assets(&self, weight: Weight) -> XCMWeight; +} + +const MAX_ASSETS: u32 = 100; + +impl WeighMultiAssets for MultiAssetFilter { + fn weigh_multi_assets(&self, weight: Weight) -> XCMWeight { + let weight = match self { + Self::Definite(assets) => + weight.saturating_mul(assets.inner().into_iter().count() as u64), + Self::Wild(_) => weight.saturating_mul(MAX_ASSETS as u64), + }; + weight.ref_time() + } +} + +impl WeighMultiAssets for MultiAssets { + fn weigh_multi_assets(&self, weight: Weight) -> XCMWeight { + weight.saturating_mul(self.inner().into_iter().count() as u64).ref_time() + } +} + +pub struct StatemintXcmWeight(core::marker::PhantomData); +impl XcmWeightInfo for StatemintXcmWeight { + fn withdraw_asset(assets: &MultiAssets) -> XCMWeight { + assets.weigh_multi_assets(XcmFungibleWeight::::withdraw_asset()) + } + // Currently there is no trusted reserve + fn reserve_asset_deposited(_assets: &MultiAssets) -> XCMWeight { + u64::MAX + } + fn receive_teleported_asset(assets: &MultiAssets) -> XCMWeight { + assets.weigh_multi_assets(XcmFungibleWeight::::receive_teleported_asset()) + } + fn query_response(_query_id: &u64, _response: &Response, _max_weight: &u64) -> XCMWeight { + XcmGeneric::::query_response().ref_time() + } + fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> XCMWeight { + assets.weigh_multi_assets(XcmFungibleWeight::::transfer_asset()) + } + fn transfer_reserve_asset( + assets: &MultiAssets, + _dest: &MultiLocation, + _xcm: &Xcm<()>, + ) -> XCMWeight { + assets.weigh_multi_assets(XcmFungibleWeight::::transfer_reserve_asset()) + } + fn transact( + _origin_type: &OriginKind, + _require_weight_at_most: &u64, + _call: &DoubleEncoded, + ) -> XCMWeight { + XcmGeneric::::transact().ref_time() + } + fn hrmp_new_channel_open_request( + _sender: &u32, + _max_message_size: &u32, + _max_capacity: &u32, + ) -> XCMWeight { + // XCM Executor does not currently support HRMP channel operations + Weight::MAX.ref_time() + } + fn hrmp_channel_accepted(_recipient: &u32) -> XCMWeight { + // XCM Executor does not currently support HRMP channel operations + Weight::MAX.ref_time() + } + fn hrmp_channel_closing(_initiator: &u32, _sender: &u32, _recipient: &u32) -> XCMWeight { + // XCM Executor does not currently support HRMP channel operations + Weight::MAX.ref_time() + } + fn clear_origin() -> XCMWeight { + XcmGeneric::::clear_origin().ref_time() + } + fn descend_origin(_who: &InteriorMultiLocation) -> XCMWeight { + XcmGeneric::::descend_origin().ref_time() + } + fn report_error( + _query_id: &QueryId, + _dest: &MultiLocation, + _max_response_weight: &u64, + ) -> XCMWeight { + XcmGeneric::::report_error().ref_time() + } + + fn deposit_asset( + assets: &MultiAssetFilter, + _max_assets: &u32, + _dest: &MultiLocation, + ) -> XCMWeight { + // Hardcoded till the XCM pallet is fixed + let hardcoded_weight = Weight::from_ref_time(1_000_000_000 as u64).ref_time(); + let weight = assets.weigh_multi_assets(XcmFungibleWeight::::deposit_asset()); + cmp::min(hardcoded_weight, weight) + } + fn deposit_reserve_asset( + assets: &MultiAssetFilter, + _max_assets: &u32, + _dest: &MultiLocation, + _xcm: &Xcm<()>, + ) -> XCMWeight { + assets.weigh_multi_assets(XcmFungibleWeight::::deposit_reserve_asset()) + } + fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets) -> XCMWeight { + Weight::MAX.ref_time() + } + fn initiate_reserve_withdraw( + assets: &MultiAssetFilter, + _reserve: &MultiLocation, + _xcm: &Xcm<()>, + ) -> XCMWeight { + assets.weigh_multi_assets(XcmGeneric::::initiate_reserve_withdraw()) + } + fn initiate_teleport( + assets: &MultiAssetFilter, + _dest: &MultiLocation, + _xcm: &Xcm<()>, + ) -> XCMWeight { + // Hardcoded till the XCM pallet is fixed + let hardcoded_weight = Weight::from_ref_time(200_000_000 as u64).ref_time(); + let weight = assets.weigh_multi_assets(XcmFungibleWeight::::initiate_teleport()); + cmp::min(hardcoded_weight, weight) + } + fn query_holding( + _query_id: &u64, + _dest: &MultiLocation, + _assets: &MultiAssetFilter, + _max_response_weight: &u64, + ) -> XCMWeight { + XcmGeneric::::query_holding().ref_time() + } + fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> XCMWeight { + XcmGeneric::::buy_execution().ref_time() + } + fn refund_surplus() -> XCMWeight { + XcmGeneric::::refund_surplus().ref_time() + } + fn set_error_handler(_xcm: &Xcm) -> XCMWeight { + XcmGeneric::::set_error_handler().ref_time() + } + fn set_appendix(_xcm: &Xcm) -> XCMWeight { + XcmGeneric::::set_appendix().ref_time() + } + fn clear_error() -> XCMWeight { + XcmGeneric::::clear_error().ref_time() + } + fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> XCMWeight { + XcmGeneric::::claim_asset().ref_time() + } + fn trap(_code: &u64) -> XCMWeight { + XcmGeneric::::trap().ref_time() + } + fn subscribe_version(_query_id: &QueryId, _max_response_weight: &u64) -> XCMWeight { + XcmGeneric::::subscribe_version().ref_time() + } + fn unsubscribe_version() -> XCMWeight { + XcmGeneric::::unsubscribe_version().ref_time() + } +} diff --git a/crust-collator/runtime/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/crust-collator/runtime/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs new file mode 100644 index 00000000..900472b6 --- /dev/null +++ b/crust-collator/runtime/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -0,0 +1,107 @@ +// Copyright 2022 Parity Technologies (UK) Ltd. +// This file is part of Cumulus. + +// Cumulus 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. + +// Cumulus 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 Cumulus. If not, see . + + +//! Autogenerated weights for `pallet_xcm_benchmarks::fungible` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-09-21, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `bm6`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 1024 + +// Executed Command: +// ./artifacts/polkadot-parachain +// benchmark +// pallet +// --template=./templates/xcm-bench-template.hbs +// --chain=statemint-dev +// --execution=wasm +// --wasm-execution=compiled +// --pallet=pallet_xcm_benchmarks::fungible +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/statemint/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weights for `pallet_xcm_benchmarks::fungible`. +pub struct WeightInfo(PhantomData); +impl WeightInfo { + // Storage: System Account (r:1 w:1) + pub(crate) fn withdraw_asset() -> Weight { + Weight::from_ref_time(33_878_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } + // Storage: System Account (r:2 w:2) + pub(crate) fn transfer_asset() -> Weight { + Weight::from_ref_time(39_130_000 as u64) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) + } + // Storage: System Account (r:2 w:2) + // Storage: ParachainInfo ParachainId (r:1 w:0) + // Storage: PolkadotXcm SupportedVersion (r:1 w:0) + // Storage: PolkadotXcm VersionDiscoveryQueue (r:1 w:1) + // Storage: PolkadotXcm SafeXcmVersion (r:1 w:0) + // Storage: ParachainSystem HostConfiguration (r:1 w:0) + // Storage: ParachainSystem PendingUpwardMessages (r:1 w:1) + pub(crate) fn transfer_reserve_asset() -> Weight { + Weight::from_ref_time(54_404_000 as u64) + .saturating_add(T::DbWeight::get().reads(8 as u64)) + .saturating_add(T::DbWeight::get().writes(4 as u64)) + } + pub(crate) fn receive_teleported_asset() -> Weight { + Weight::from_ref_time(6_586_000 as u64) + } + // Storage: System Account (r:1 w:1) + pub(crate) fn deposit_asset() -> Weight { + Weight::from_ref_time(34_055_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } + // Storage: System Account (r:1 w:1) + // Storage: ParachainInfo ParachainId (r:1 w:0) + // Storage: PolkadotXcm SupportedVersion (r:1 w:0) + // Storage: PolkadotXcm VersionDiscoveryQueue (r:1 w:1) + // Storage: PolkadotXcm SafeXcmVersion (r:1 w:0) + // Storage: ParachainSystem HostConfiguration (r:1 w:0) + // Storage: ParachainSystem PendingUpwardMessages (r:1 w:1) + pub(crate) fn deposit_reserve_asset() -> Weight { + Weight::from_ref_time(50_905_000 as u64) + .saturating_add(T::DbWeight::get().reads(7 as u64)) + .saturating_add(T::DbWeight::get().writes(3 as u64)) + } + // Storage: ParachainInfo ParachainId (r:1 w:0) + // Storage: PolkadotXcm SupportedVersion (r:1 w:0) + // Storage: PolkadotXcm VersionDiscoveryQueue (r:1 w:1) + // Storage: PolkadotXcm SafeXcmVersion (r:1 w:0) + // Storage: ParachainSystem HostConfiguration (r:1 w:0) + // Storage: ParachainSystem PendingUpwardMessages (r:1 w:1) + pub(crate) fn initiate_teleport() -> Weight { + Weight::from_ref_time(26_715_000 as u64) + .saturating_add(T::DbWeight::get().reads(6 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) + } +} diff --git a/crust-collator/runtime/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/crust-collator/runtime/src/weights/xcm/pallet_xcm_benchmarks_generic.rs new file mode 100644 index 00000000..bd9ac30b --- /dev/null +++ b/crust-collator/runtime/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -0,0 +1,137 @@ +// Copyright 2022 Parity Technologies (UK) Ltd. +// This file is part of Cumulus. + +// Cumulus 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. + +// Cumulus 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 Cumulus. If not, see . + + +//! Autogenerated weights for `pallet_xcm_benchmarks::generic` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-09-21, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `bm6`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 1024 + +// Executed Command: +// ./artifacts/polkadot-parachain +// benchmark +// pallet +// --template=./templates/xcm-bench-template.hbs +// --chain=statemint-dev +// --execution=wasm +// --wasm-execution=compiled +// --pallet=pallet_xcm_benchmarks::generic +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/statemint/src/weights/xcm/pallet_xcm_benchmarks_generic.rs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weights for `pallet_xcm_benchmarks::generic`. +pub struct WeightInfo(PhantomData); +impl WeightInfo { + // Storage: ParachainInfo ParachainId (r:1 w:0) + // Storage: PolkadotXcm SupportedVersion (r:1 w:0) + // Storage: PolkadotXcm VersionDiscoveryQueue (r:1 w:1) + // Storage: PolkadotXcm SafeXcmVersion (r:1 w:0) + // Storage: ParachainSystem HostConfiguration (r:1 w:0) + // Storage: ParachainSystem PendingUpwardMessages (r:1 w:1) + pub(crate) fn query_holding() -> Weight { + Weight::from_ref_time(693_490_000 as u64) + .saturating_add(T::DbWeight::get().reads(6 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) + } + pub(crate) fn buy_execution() -> Weight { + Weight::from_ref_time(9_276_000 as u64) + } + // Storage: PolkadotXcm Queries (r:1 w:0) + pub(crate) fn query_response() -> Weight { + Weight::from_ref_time(17_581_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + } + pub(crate) fn transact() -> Weight { + Weight::from_ref_time(20_807_000 as u64) + } + pub(crate) fn refund_surplus() -> Weight { + Weight::from_ref_time(9_523_000 as u64) + } + pub(crate) fn set_error_handler() -> Weight { + Weight::from_ref_time(5_732_000 as u64) + } + pub(crate) fn set_appendix() -> Weight { + Weight::from_ref_time(5_666_000 as u64) + } + pub(crate) fn clear_error() -> Weight { + Weight::from_ref_time(5_621_000 as u64) + } + pub(crate) fn descend_origin() -> Weight { + Weight::from_ref_time(6_570_000 as u64) + } + pub(crate) fn clear_origin() -> Weight { + Weight::from_ref_time(5_773_000 as u64) + } + // Storage: PolkadotXcm SupportedVersion (r:1 w:0) + // Storage: PolkadotXcm VersionDiscoveryQueue (r:1 w:1) + // Storage: PolkadotXcm SafeXcmVersion (r:1 w:0) + // Storage: ParachainSystem HostConfiguration (r:1 w:0) + // Storage: ParachainSystem PendingUpwardMessages (r:1 w:1) + pub(crate) fn report_error() -> Weight { + Weight::from_ref_time(16_085_000 as u64) + .saturating_add(T::DbWeight::get().reads(5 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) + } + // Storage: PolkadotXcm AssetTraps (r:1 w:1) + pub(crate) fn claim_asset() -> Weight { + Weight::from_ref_time(12_664_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } + pub(crate) fn trap() -> Weight { + Weight::from_ref_time(5_774_000 as u64) + } + // Storage: PolkadotXcm VersionNotifyTargets (r:1 w:1) + // Storage: PolkadotXcm SupportedVersion (r:1 w:0) + // Storage: PolkadotXcm VersionDiscoveryQueue (r:1 w:1) + // Storage: PolkadotXcm SafeXcmVersion (r:1 w:0) + // Storage: ParachainSystem HostConfiguration (r:1 w:0) + // Storage: ParachainSystem PendingUpwardMessages (r:1 w:1) + pub(crate) fn subscribe_version() -> Weight { + Weight::from_ref_time(19_102_000 as u64) + .saturating_add(T::DbWeight::get().reads(6 as u64)) + .saturating_add(T::DbWeight::get().writes(3 as u64)) + } + // Storage: PolkadotXcm VersionNotifyTargets (r:0 w:1) + pub(crate) fn unsubscribe_version() -> Weight { + Weight::from_ref_time(8_841_000 as u64) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } + // Storage: ParachainInfo ParachainId (r:1 w:0) + // Storage: PolkadotXcm SupportedVersion (r:1 w:0) + // Storage: PolkadotXcm VersionDiscoveryQueue (r:1 w:1) + // Storage: PolkadotXcm SafeXcmVersion (r:1 w:0) + // Storage: ParachainSystem HostConfiguration (r:1 w:0) + // Storage: ParachainSystem PendingUpwardMessages (r:1 w:1) + pub(crate) fn initiate_reserve_withdraw() -> Weight { + Weight::from_ref_time(864_425_000 as u64) + .saturating_add(T::DbWeight::get().reads(6 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) + } +} diff --git a/crust-collator/src/command.rs b/crust-collator/src/command.rs index c3031d5f..79078f7b 100644 --- a/crust-collator/src/command.rs +++ b/crust-collator/src/command.rs @@ -325,7 +325,7 @@ impl CliConfiguration for RelayChainCli { fn base_path(&self) -> Result> { Ok(self .shared_params() - .base_path() + .base_path()? .or_else(|| self.base_path.clone().map(Into::into))) } @@ -376,10 +376,6 @@ impl CliConfiguration for RelayChainCli { self.base.base.transaction_pool(is_dev) } - fn state_cache_child_ratio(&self) -> Result> { - self.base.base.state_cache_child_ratio() - } - fn rpc_methods(&self) -> Result { self.base.base.rpc_methods() } diff --git a/crust-collator/src/rpc.rs b/crust-collator/src/rpc.rs index af004e17..42e0948b 100644 --- a/crust-collator/src/rpc.rs +++ b/crust-collator/src/rpc.rs @@ -30,7 +30,7 @@ use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; use crust_parachain_primitives::{AccountId, Balance, Block, Index as Nonce}; /// A type representing all RPC extensions. -pub type RpcExtension = jsonrpsee::RpcModule<()>; +use jsonrpsee::RpcModule; /// Full client dependencies pub struct FullDeps { @@ -43,7 +43,7 @@ pub struct FullDeps { } /// Instantiate all RPC extensions. -pub fn create_full(deps: FullDeps) -> Result> +pub fn create_full(deps: FullDeps) -> Result, Box> where C: ProvideRuntimeApi + HeaderBackend @@ -60,7 +60,7 @@ where use frame_rpc_system::{System, SystemApiServer}; use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; - let mut module = RpcExtension::new(()); + let mut module = RpcModule::new(()); let FullDeps { client, pool, deny_unsafe } = deps; module.merge(System::new(client.clone(), pool, deny_unsafe).into_rpc())?; diff --git a/crust-collator/src/service.rs b/crust-collator/src/service.rs index 8f56407f..f8c89b4b 100644 --- a/crust-collator/src/service.rs +++ b/crust-collator/src/service.rs @@ -32,12 +32,13 @@ use crust_parachain_primitives::Block; use sc_service::{Configuration, PartialComponents, TFullBackend, TFullClient, TaskManager}; use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle}; use sc_network::NetworkService; +use sc_network_common::service::NetworkBlock; use sp_keystore::SyncCryptoStorePtr; use std::{sync::Arc, time::Duration}; use sc_executor::WasmExecutor; use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain; use cumulus_relay_chain_interface::{RelayChainError, RelayChainInterface, RelayChainResult}; -use cumulus_relay_chain_rpc_interface::RelayChainRPCInterface; +use cumulus_relay_chain_rpc_interface::{create_client_and_start_worker, RelayChainRpcInterface}; use substrate_prometheus_endpoint::Registry; use polkadot_service::CollatorPair; @@ -135,8 +136,8 @@ pub fn new_partial( Ok((time, slot)) }, registry: config.prometheus_registry().clone(), - can_author_with: sp_consensus::AlwaysCanAuthor, spawner: &task_manager.spawn_essential_handle(), + can_author_with: sp_consensus::AlwaysCanAuthor, telemetry: telemetry.as_ref().map(|t| t.handle()).clone(), })?; @@ -185,8 +186,10 @@ async fn build_relay_chain_interface( collator_options: CollatorOptions, ) -> RelayChainResult<(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)), + Some(relay_chain_url) => { + let client = create_client_and_start_worker(relay_chain_url, task_manager).await?; + Ok((Arc::new(RelayChainRpcInterface::new(client)) as Arc<_>, None)) + }, None => build_inprocess_relay_chain( polkadot_config, parachain_config, diff --git a/cumulus b/cumulus index b86cd207..2fa95572 160000 --- a/cumulus +++ b/cumulus @@ -1 +1 @@ -Subproject commit b86cd207fc77af888f223c10363ae4d18a4b63b4 +Subproject commit 2fa95572487cfcf8dbe6941bf93545c39d47f784