From 4c1adf6ac095909400c03ea6e88a4710f80bbd81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Tue, 15 Sep 2020 17:16:07 +0200 Subject: [PATCH 01/16] Start --- frame/support/procedural/src/lib.rs | 18 +++++++++++ .../support/procedural/src/pallet_version.rs | 30 +++++++++++++++++++ frame/support/src/traits.rs | 15 ++++++++-- 3 files changed, 61 insertions(+), 2 deletions(-) create mode 100644 frame/support/procedural/src/pallet_version.rs diff --git a/frame/support/procedural/src/lib.rs b/frame/support/procedural/src/lib.rs index 054d90d7bbaeb..5f97c975dde0f 100644 --- a/frame/support/procedural/src/lib.rs +++ b/frame/support/procedural/src/lib.rs @@ -23,6 +23,7 @@ mod storage; mod construct_runtime; +mod pallet_version; mod transactional; use proc_macro::TokenStream; @@ -315,3 +316,20 @@ pub fn construct_runtime(input: TokenStream) -> TokenStream { pub fn transactional(attr: TokenStream, input: TokenStream) -> TokenStream { transactional::transactional(attr, input) } + +/// Convert the current crate version into a [`PalletVersion`]. +/// +/// It uses the `CARGO_PKG_VERSION_MAJOR`, `CARGO_PKG_VERSION_MINOR` and +/// `CARGO_PKG_VERSION_PATCH` environment variables to fetch the crate version. +/// This means that the [`PalletVersion`] object will correspond to the version of the +/// crate the macro is called in! +/// +/// # Example +/// +/// ``` +/// const Version: PalletVersion = crate_to_pallet_version!(); +/// ``` +#[proc_macro] +pub fn crate_version_to_pallet_version(input: TokenStream) -> TokenStream { + TokenStream::default() +} diff --git a/frame/support/procedural/src/pallet_version.rs b/frame/support/procedural/src/pallet_version.rs new file mode 100644 index 0000000000000..d33a8a71deae7 --- /dev/null +++ b/frame/support/procedural/src/pallet_version.rs @@ -0,0 +1,30 @@ +// This file is part of Substrate. + +// Copyright (C) 2020 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. + +//! Implementation of macros related to pallet versioning. + +use proc_macro2::{TokenStream, Span}; +use syn::{Result, Error}; + +/// Implementation of the `crate_to_pallet_version!` macro. +pub fn crate_to_pallet_version(input: proc_macro::TokenStream) -> Result { + if !input.is_empty() { + return Err(Error::new(Span::call_site(), "No arguments expected!")); + } + + Ok(TokenStream::default()) +} diff --git a/frame/support/src/traits.rs b/frame/support/src/traits.rs index 6f50f38a23369..55c94a333c944 100644 --- a/frame/support/src/traits.rs +++ b/frame/support/src/traits.rs @@ -1663,8 +1663,19 @@ impl IsType for T { /// E.g. for module MyModule default instance will have prefix "MyModule" and other instances /// "InstanceNMyModule". pub trait Instance: 'static { - /// Unique module prefix. E.g. "InstanceNMyModule" or "MyModule" - const PREFIX: &'static str ; + /// Unique module prefix. E.g. "InstanceNMyModule" or "MyModule" + const PREFIX: &'static str ; +} + +/// The version of a pallet. +#[derive(RuntimeDebug, Eq, PartialEq, Encode, Decode)] +pub struct PalletVersion { + /// The major version of the pallet. + pub major: u16, + /// The minor version of the pallet. + pub minor: u8, + /// The patch version of the pallet. + pub patch: u8, } #[cfg(test)] From f1beba94cdb41b374a99a7d7cdc6b1ceec9293a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Thu, 17 Sep 2020 14:56:37 +0200 Subject: [PATCH 02/16] Make macro work --- frame/support/procedural/src/lib.rs | 16 +------- .../support/procedural/src/pallet_version.rs | 38 ++++++++++++++++++- frame/support/src/lib.rs | 15 ++++++++ frame/support/test/src/lib.rs | 3 ++ frame/support/test/src/pallet_version.rs | 32 ++++++++++++++++ 5 files changed, 88 insertions(+), 16 deletions(-) create mode 100644 frame/support/test/src/pallet_version.rs diff --git a/frame/support/procedural/src/lib.rs b/frame/support/procedural/src/lib.rs index 94a24de8857ad..1ace099abd942 100644 --- a/frame/support/procedural/src/lib.rs +++ b/frame/support/procedural/src/lib.rs @@ -315,19 +315,7 @@ pub fn transactional(attr: TokenStream, input: TokenStream) -> TokenStream { transactional::transactional(attr, input).unwrap_or_else(|e| e.to_compile_error().into()) } -/// Convert the current crate version into a [`PalletVersion`]. -/// -/// It uses the `CARGO_PKG_VERSION_MAJOR`, `CARGO_PKG_VERSION_MINOR` and -/// `CARGO_PKG_VERSION_PATCH` environment variables to fetch the crate version. -/// This means that the [`PalletVersion`] object will correspond to the version of the -/// crate the macro is called in! -/// -/// # Example -/// -/// ``` -/// const Version: PalletVersion = crate_to_pallet_version!(); -/// ``` #[proc_macro] -pub fn crate_version_to_pallet_version(input: TokenStream) -> TokenStream { - TokenStream::default() +pub fn crate_to_pallet_version(input: TokenStream) -> TokenStream { + pallet_version::crate_to_pallet_version(input).unwrap_or_else(|e| e.to_compile_error()).into() } diff --git a/frame/support/procedural/src/pallet_version.rs b/frame/support/procedural/src/pallet_version.rs index d33a8a71deae7..ffd4b41208d56 100644 --- a/frame/support/procedural/src/pallet_version.rs +++ b/frame/support/procedural/src/pallet_version.rs @@ -19,12 +19,46 @@ use proc_macro2::{TokenStream, Span}; use syn::{Result, Error}; +use std::{env, str::FromStr}; +use frame_support_procedural_tools::generate_crate_access_2018; + +/// Get the version from the given version environment variable. +/// +/// The version is parsed into the requested destination type. +fn get_version(version_env: &str) -> std::result::Result { + let version = env::var(version_env) + .expect(&format!("`{}` is always set by cargo; qed", version_env)); + + T::from_str(&version).map_err(drop) +} + +/// Create an error that will be shown by rustc at the call site of the macro. +fn create_error(message: &str) -> Error { + Error::new(Span::call_site(), message) +} /// Implementation of the `crate_to_pallet_version!` macro. pub fn crate_to_pallet_version(input: proc_macro::TokenStream) -> Result { if !input.is_empty() { - return Err(Error::new(Span::call_site(), "No arguments expected!")); + return Err(create_error("No arguments expected!")) } - Ok(TokenStream::default()) + let major_version = get_version::("CARGO_PKG_VERSION_MAJOR") + .map_err(|_| create_error("Major version needs to fit into `u16`"))?; + + let minor_version = get_version::("CARGO_PKG_VERSION_MINOR") + .map_err(|_| create_error("Minor version needs to fit into `u8`"))?; + + let patch_version = get_version::("CARGO_PKG_VERSION_PATCH") + .map_err(|_| create_error("Patch version needs to fit into `u8`"))?; + + let crate_ = generate_crate_access_2018()?; + + Ok(quote::quote! { + #crate_::traits::PalletVersion { + major: #major_version, + minor: #minor_version, + patch: #patch_version, + } + }) } diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index bdbdfc04a31f9..314ce74a25793 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -269,6 +269,21 @@ macro_rules! ord_parameter_types { #[doc(inline)] pub use frame_support_procedural::{decl_storage, construct_runtime, transactional}; +/// Convert the current crate version into a [`PalletVersion`](crate::traits::PalletVersion). +/// +/// It uses the `CARGO_PKG_VERSION_MAJOR`, `CARGO_PKG_VERSION_MINOR` and +/// `CARGO_PKG_VERSION_PATCH` environment variables to fetch the crate version. +/// This means that the [`PalletVersion`](crate::traits::PalletVersion) +/// object will correspond to the version of the crate the macro is called in! +/// +/// # Example +/// +/// ``` +/// #use frame_support::{traits::PalletVersion, crate_to_pallet_version}; +/// const Version: PalletVersion = crate_to_pallet_version!(); +/// ``` +pub use frame_support_procedural::crate_to_pallet_version; + /// Return Err of the expression: `return Err($expression);`. /// /// Used as `fail!(expression)`. diff --git a/frame/support/test/src/lib.rs b/frame/support/test/src/lib.rs index d5f49299880ca..cf9a54ae2eb16 100644 --- a/frame/support/test/src/lib.rs +++ b/frame/support/test/src/lib.rs @@ -22,6 +22,9 @@ #![warn(missing_docs)] #![deny(warnings)] +#[cfg(test)] +mod pallet_version; + /// The configuration trait pub trait Trait { /// The runtime origin type. diff --git a/frame/support/test/src/pallet_version.rs b/frame/support/test/src/pallet_version.rs new file mode 100644 index 0000000000000..5912bd5b8e47f --- /dev/null +++ b/frame/support/test/src/pallet_version.rs @@ -0,0 +1,32 @@ +// This file is part of Substrate. + +// Copyright (C) 2020 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use frame_support::{crate_to_pallet_version, traits::PalletVersion}; + +#[test] +fn ensure_that_current_pallet_version_is_correct() { + let expected = PalletVersion { + major: env!("CARGO_PKG_VERSION_MAJOR").parse().unwrap(), + minor: env!("CARGO_PKG_VERSION_MINOR").parse().unwrap(), + patch: env!("CARGO_PKG_VERSION_PATCH").parse().unwrap(), + }; + + assert_eq!( + expected, + crate_to_pallet_version!(), + ) +} From bdc1251a002c59937ed0df536b2f5032117ce77c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Fri, 18 Sep 2020 19:03:09 +0200 Subject: [PATCH 03/16] Rename `ModuleToIndex` to `PalletRuntimeSetup` Besides the renaming it also adds support getting the name of a pallet as configured in the runtime. --- .../pallets/template/src/mock.rs | 2 +- bin/node-template/runtime/src/lib.rs | 2 +- bin/node/runtime/src/lib.rs | 2 +- frame/assets/src/lib.rs | 2 +- frame/atomic-swap/src/tests.rs | 2 +- frame/aura/src/mock.rs | 2 +- frame/authority-discovery/src/lib.rs | 2 +- frame/authorship/src/lib.rs | 2 +- frame/babe/src/mock.rs | 2 +- frame/balances/src/lib.rs | 2 +- frame/balances/src/tests_composite.rs | 2 +- frame/balances/src/tests_local.rs | 2 +- frame/benchmarking/src/tests.rs | 2 +- frame/collective/src/lib.rs | 2 +- frame/contracts/src/tests.rs | 2 +- frame/democracy/src/tests.rs | 2 +- frame/elections-phragmen/src/lib.rs | 2 +- frame/elections/src/mock.rs | 2 +- frame/evm/src/tests.rs | 2 +- frame/example-offchain-worker/src/tests.rs | 2 +- frame/example/src/lib.rs | 2 +- frame/executive/src/lib.rs | 2 +- frame/finality-tracker/src/lib.rs | 2 +- frame/generic-asset/src/lib.rs | 2 +- frame/generic-asset/src/mock.rs | 2 +- frame/grandpa/src/mock.rs | 2 +- frame/identity/src/lib.rs | 2 +- frame/im-online/src/mock.rs | 2 +- frame/indices/src/mock.rs | 2 +- frame/membership/src/lib.rs | 2 +- frame/multisig/src/tests.rs | 2 +- frame/nicks/src/lib.rs | 2 +- frame/node-authorization/src/lib.rs | 2 +- frame/offences/benchmarking/src/mock.rs | 2 +- frame/offences/src/mock.rs | 2 +- frame/proxy/src/tests.rs | 2 +- frame/randomness-collective-flip/src/lib.rs | 2 +- frame/recovery/src/mock.rs | 2 +- frame/scheduler/src/lib.rs | 2 +- frame/scored-pool/src/mock.rs | 2 +- frame/session/benchmarking/src/mock.rs | 2 +- frame/session/src/mock.rs | 2 +- frame/society/src/mock.rs | 2 +- frame/staking/fuzzer/src/mock.rs | 2 +- frame/staking/src/mock.rs | 2 +- frame/sudo/src/mock.rs | 2 +- .../procedural/src/construct_runtime/mod.rs | 38 +++++++++++++------ frame/support/src/error.rs | 4 +- frame/support/src/metadata.rs | 4 +- frame/support/src/traits.rs | 24 ++++++------ frame/support/test/tests/construct_runtime.rs | 17 ++++++++- frame/support/test/tests/instance.rs | 2 +- frame/support/test/tests/issue2219.rs | 2 +- frame/support/test/tests/system.rs | 2 +- frame/system/benches/bench.rs | 2 +- frame/system/benchmarking/src/mock.rs | 2 +- frame/system/src/lib.rs | 12 +++--- frame/system/src/mock.rs | 2 +- frame/timestamp/src/lib.rs | 2 +- frame/transaction-payment/src/lib.rs | 2 +- frame/treasury/src/tests.rs | 2 +- frame/utility/src/tests.rs | 2 +- frame/vesting/src/lib.rs | 2 +- test-utils/runtime/src/lib.rs | 2 +- 64 files changed, 123 insertions(+), 92 deletions(-) diff --git a/bin/node-template/pallets/template/src/mock.rs b/bin/node-template/pallets/template/src/mock.rs index 8c3bf2b40473c..41246023441e4 100644 --- a/bin/node-template/pallets/template/src/mock.rs +++ b/bin/node-template/pallets/template/src/mock.rs @@ -42,7 +42,7 @@ impl system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/bin/node-template/runtime/src/lib.rs b/bin/node-template/runtime/src/lib.rs index 9612394cc7fbf..10ec47dd4e2ee 100644 --- a/bin/node-template/runtime/src/lib.rs +++ b/bin/node-template/runtime/src/lib.rs @@ -181,7 +181,7 @@ impl frame_system::Trait for Runtime { /// Converts a module to the index of the module in `construct_runtime!`. /// /// This type is being generated by `construct_runtime!`. - type ModuleToIndex = ModuleToIndex; + type PalletRuntimeSetup = PalletRuntimeSetup; /// What to do if a new account is created. type OnNewAccount = (); /// What to do if an account is fully reaped from the system. diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index 104cd2ba96cab..9bfa7a63de3db 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -179,7 +179,7 @@ impl frame_system::Trait for Runtime { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = Version; - type ModuleToIndex = ModuleToIndex; + type PalletRuntimeSetup = PalletRuntimeSetup; type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/assets/src/lib.rs b/frame/assets/src/lib.rs index e1303fcd03b0d..4d8cb01dff404 100644 --- a/frame/assets/src/lib.rs +++ b/frame/assets/src/lib.rs @@ -319,7 +319,7 @@ mod tests { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/atomic-swap/src/tests.rs b/frame/atomic-swap/src/tests.rs index 528203fc39096..fe61743d737db 100644 --- a/frame/atomic-swap/src/tests.rs +++ b/frame/atomic-swap/src/tests.rs @@ -45,7 +45,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/aura/src/mock.rs b/frame/aura/src/mock.rs index 9277cb14f3002..1153809224934 100644 --- a/frame/aura/src/mock.rs +++ b/frame/aura/src/mock.rs @@ -66,7 +66,7 @@ impl frame_system::Trait for Test { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/authority-discovery/src/lib.rs b/frame/authority-discovery/src/lib.rs index d584838ecbedd..ab9d385fb8489 100644 --- a/frame/authority-discovery/src/lib.rs +++ b/frame/authority-discovery/src/lib.rs @@ -164,7 +164,7 @@ mod tests { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/authorship/src/lib.rs b/frame/authorship/src/lib.rs index 91cad247cac57..657bb03bcbea5 100644 --- a/frame/authorship/src/lib.rs +++ b/frame/authorship/src/lib.rs @@ -438,7 +438,7 @@ mod tests { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/babe/src/mock.rs b/frame/babe/src/mock.rs index 34e9ff113d42c..8dbab2e1b23b9 100644 --- a/frame/babe/src/mock.rs +++ b/frame/babe/src/mock.rs @@ -86,7 +86,7 @@ impl frame_system::Trait for Test { type MaximumExtrinsicWeight = MaximumBlockWeight; type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index 471efb90bf3ff..8bb11e16ea2b1 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -902,7 +902,7 @@ impl, I: Instance> frame_system::Trait for ElevatedTrait { type MaximumBlockLength = T::MaximumBlockLength; type AvailableBlockRatio = T::AvailableBlockRatio; type Version = T::Version; - type ModuleToIndex = T::ModuleToIndex; + type PalletRuntimeSetup = T::PalletRuntimeSetup; type OnNewAccount = T::OnNewAccount; type OnKilledAccount = T::OnKilledAccount; type AccountData = T::AccountData; diff --git a/frame/balances/src/tests_composite.rs b/frame/balances/src/tests_composite.rs index 90ad145f22521..9a24e5bed3421 100644 --- a/frame/balances/src/tests_composite.rs +++ b/frame/balances/src/tests_composite.rs @@ -87,7 +87,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = super::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/balances/src/tests_local.rs b/frame/balances/src/tests_local.rs index 75813c6b1bc9a..b48c3aa40c31d 100644 --- a/frame/balances/src/tests_local.rs +++ b/frame/balances/src/tests_local.rs @@ -87,7 +87,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = super::AccountData; type OnNewAccount = (); type OnKilledAccount = Module; diff --git a/frame/benchmarking/src/tests.rs b/frame/benchmarking/src/tests.rs index 94f3574100739..a091e7c1c52a4 100644 --- a/frame/benchmarking/src/tests.rs +++ b/frame/benchmarking/src/tests.rs @@ -93,7 +93,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = (); type AvailableBlockRatio = (); type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index e19d220533d45..475589cfb0754 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -985,7 +985,7 @@ mod tests { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index 1c30021793146..84f5c0a446359 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -137,7 +137,7 @@ impl frame_system::Trait for Test { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/democracy/src/tests.rs b/frame/democracy/src/tests.rs index aed6739c77ebb..77c930d241001 100644 --- a/frame/democracy/src/tests.rs +++ b/frame/democracy/src/tests.rs @@ -112,7 +112,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index 372ae11b148ff..ae1f3b525191c 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -1139,7 +1139,7 @@ mod tests { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/elections/src/mock.rs b/frame/elections/src/mock.rs index adde24c25d32f..5047541116344 100644 --- a/frame/elections/src/mock.rs +++ b/frame/elections/src/mock.rs @@ -59,7 +59,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/evm/src/tests.rs b/frame/evm/src/tests.rs index f741e3e4fc048..2e06feb352d15 100644 --- a/frame/evm/src/tests.rs +++ b/frame/evm/src/tests.rs @@ -52,7 +52,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/example-offchain-worker/src/tests.rs b/frame/example-offchain-worker/src/tests.rs index 4e7e4def2ba68..770d03ebe6669 100644 --- a/frame/example-offchain-worker/src/tests.rs +++ b/frame/example-offchain-worker/src/tests.rs @@ -74,7 +74,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/example/src/lib.rs b/frame/example/src/lib.rs index 0585307061bcd..71eff03a0177e 100644 --- a/frame/example/src/lib.rs +++ b/frame/example/src/lib.rs @@ -764,7 +764,7 @@ mod tests { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index cd9642fb82c9d..706ce1e4a595d 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -567,7 +567,7 @@ mod tests { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = RuntimeVersion; - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/finality-tracker/src/lib.rs b/frame/finality-tracker/src/lib.rs index 58f16d72766eb..259b37bfb8f7f 100644 --- a/frame/finality-tracker/src/lib.rs +++ b/frame/finality-tracker/src/lib.rs @@ -273,7 +273,7 @@ mod tests { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/generic-asset/src/lib.rs b/frame/generic-asset/src/lib.rs index 6c3683312d0a8..861b98eecadbb 100644 --- a/frame/generic-asset/src/lib.rs +++ b/frame/generic-asset/src/lib.rs @@ -1131,7 +1131,7 @@ impl frame_system::Trait for ElevatedTrait { type MaximumBlockLength = T::MaximumBlockLength; type AvailableBlockRatio = T::AvailableBlockRatio; type Version = T::Version; - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/generic-asset/src/mock.rs b/frame/generic-asset/src/mock.rs index 8c0a06a1564df..b001813174642 100644 --- a/frame/generic-asset/src/mock.rs +++ b/frame/generic-asset/src/mock.rs @@ -63,7 +63,7 @@ impl frame_system::Trait for Test { type AvailableBlockRatio = AvailableBlockRatio; type BlockHashCount = BlockHashCount; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/grandpa/src/mock.rs b/frame/grandpa/src/mock.rs index 81026c756273a..8fc33e9f37021 100644 --- a/frame/grandpa/src/mock.rs +++ b/frame/grandpa/src/mock.rs @@ -100,7 +100,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/identity/src/lib.rs b/frame/identity/src/lib.rs index e69255ab1980b..5ac696ee15e5e 100644 --- a/frame/identity/src/lib.rs +++ b/frame/identity/src/lib.rs @@ -1377,7 +1377,7 @@ mod tests { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/im-online/src/mock.rs b/frame/im-online/src/mock.rs index 29fe6acb3337c..b3f06efd6107d 100644 --- a/frame/im-online/src/mock.rs +++ b/frame/im-online/src/mock.rs @@ -130,7 +130,7 @@ impl frame_system::Trait for Runtime { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/indices/src/mock.rs b/frame/indices/src/mock.rs index a47e1251d63db..1d43201ef1dcb 100644 --- a/frame/indices/src/mock.rs +++ b/frame/indices/src/mock.rs @@ -70,7 +70,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/membership/src/lib.rs b/frame/membership/src/lib.rs index 2bc4a440b8d47..e5a4bdddd56a2 100644 --- a/frame/membership/src/lib.rs +++ b/frame/membership/src/lib.rs @@ -320,7 +320,7 @@ mod tests { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/multisig/src/tests.rs b/frame/multisig/src/tests.rs index b727ec8cdb41d..075f8e397dbeb 100644 --- a/frame/multisig/src/tests.rs +++ b/frame/multisig/src/tests.rs @@ -80,7 +80,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/nicks/src/lib.rs b/frame/nicks/src/lib.rs index ca90da1750b3c..b4c1325f3da75 100644 --- a/frame/nicks/src/lib.rs +++ b/frame/nicks/src/lib.rs @@ -283,7 +283,7 @@ mod tests { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/node-authorization/src/lib.rs b/frame/node-authorization/src/lib.rs index 9b401091beb02..15c190495e0fd 100644 --- a/frame/node-authorization/src/lib.rs +++ b/frame/node-authorization/src/lib.rs @@ -474,7 +474,7 @@ mod tests { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/offences/benchmarking/src/mock.rs b/frame/offences/benchmarking/src/mock.rs index 12a14e90b0e53..f0884f411be44 100644 --- a/frame/offences/benchmarking/src/mock.rs +++ b/frame/offences/benchmarking/src/mock.rs @@ -59,7 +59,7 @@ impl frame_system::Trait for Test { type AvailableBlockRatio = (); type MaximumBlockLength = (); type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (Balances,); diff --git a/frame/offences/src/mock.rs b/frame/offences/src/mock.rs index f981e70835c0e..8bb6b532ee23f 100644 --- a/frame/offences/src/mock.rs +++ b/frame/offences/src/mock.rs @@ -116,7 +116,7 @@ impl frame_system::Trait for Runtime { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/proxy/src/tests.rs b/frame/proxy/src/tests.rs index ea9b321ee0a8e..4e925478ed58f 100644 --- a/frame/proxy/src/tests.rs +++ b/frame/proxy/src/tests.rs @@ -82,7 +82,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/randomness-collective-flip/src/lib.rs b/frame/randomness-collective-flip/src/lib.rs index 74a08c0150935..bf873624f1405 100644 --- a/frame/randomness-collective-flip/src/lib.rs +++ b/frame/randomness-collective-flip/src/lib.rs @@ -178,7 +178,7 @@ mod tests { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/recovery/src/mock.rs b/frame/recovery/src/mock.rs index 9256ec9425de5..6262141baa880 100644 --- a/frame/recovery/src/mock.rs +++ b/frame/recovery/src/mock.rs @@ -79,7 +79,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/scheduler/src/lib.rs b/frame/scheduler/src/lib.rs index edd112bd89299..381405b76229f 100644 --- a/frame/scheduler/src/lib.rs +++ b/frame/scheduler/src/lib.rs @@ -723,7 +723,7 @@ mod tests { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/scored-pool/src/mock.rs b/frame/scored-pool/src/mock.rs index 2341832748f68..13f6244864630 100644 --- a/frame/scored-pool/src/mock.rs +++ b/frame/scored-pool/src/mock.rs @@ -70,7 +70,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/session/benchmarking/src/mock.rs b/frame/session/benchmarking/src/mock.rs index c1f75ec4e0965..76954187f133d 100644 --- a/frame/session/benchmarking/src/mock.rs +++ b/frame/session/benchmarking/src/mock.rs @@ -78,7 +78,7 @@ impl frame_system::Trait for Test { type AvailableBlockRatio = (); type MaximumBlockLength = (); type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = Balances; diff --git a/frame/session/src/mock.rs b/frame/session/src/mock.rs index bd94264b15560..d3ac87fd72641 100644 --- a/frame/session/src/mock.rs +++ b/frame/session/src/mock.rs @@ -193,7 +193,7 @@ impl frame_system::Trait for Test { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/society/src/mock.rs b/frame/society/src/mock.rs index 03fa9b60f74dd..1d81108bff760 100644 --- a/frame/society/src/mock.rs +++ b/frame/society/src/mock.rs @@ -81,7 +81,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type OnNewAccount = (); type OnKilledAccount = (); type AccountData = pallet_balances::AccountData; diff --git a/frame/staking/fuzzer/src/mock.rs b/frame/staking/fuzzer/src/mock.rs index 766f088f40388..2c9438bfa9405 100644 --- a/frame/staking/fuzzer/src/mock.rs +++ b/frame/staking/fuzzer/src/mock.rs @@ -77,7 +77,7 @@ impl frame_system::Trait for Test { type AvailableBlockRatio = (); type MaximumBlockLength = (); type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (Balances,); diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index 805df5d56f38e..b15b53c07ca81 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -220,7 +220,7 @@ impl frame_system::Trait for Test { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/sudo/src/mock.rs b/frame/sudo/src/mock.rs index 5052d9c52d1b4..0e3f0d0d50843 100644 --- a/frame/sudo/src/mock.rs +++ b/frame/sudo/src/mock.rs @@ -139,7 +139,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/support/procedural/src/construct_runtime/mod.rs b/frame/support/procedural/src/construct_runtime/mod.rs index 57827b0673916..0376f2f37b927 100644 --- a/frame/support/procedural/src/construct_runtime/mod.rs +++ b/frame/support/procedural/src/construct_runtime/mod.rs @@ -52,6 +52,8 @@ fn construct_runtime_parsed(definition: RuntimeDefinition) -> Result>(); + // Assert we have system module declared let system_module = match find_system_module(modules.iter()) { Some(sm) => sm, @@ -82,7 +84,7 @@ fn construct_runtime_parsed(definition: RuntimeDefinition) -> Result( ) } -fn decl_module_to_index<'a>( - module_declarations: impl Iterator, - num_modules: usize, +fn decl_pallet_runtime_setup( + module_declarations: &[ModuleDeclaration], scrate: &TokenStream2, ) -> TokenStream2 { - let names = module_declarations.map(|d| &d.name); - let indices = 0..num_modules; + let names = module_declarations.iter().map(|d| &d.name); + let names2 = module_declarations.iter().map(|d| &d.name); + let name_strings = module_declarations.iter().map(|d| d.name.to_string()); + let indices = 0..module_declarations.len(); quote!( - /// Provides an implementation of `ModuleToIndex` to map a module - /// to its index in the runtime. - pub struct ModuleToIndex; + /// Provides an implementation of `PalletRuntimeSetup` to provide information + /// about the pallet setup in the runtime. + pub struct PalletRuntimeSetup; - impl #scrate::traits::ModuleToIndex for ModuleToIndex { - fn module_to_index() -> Option { - let type_id = #scrate::sp_std::any::TypeId::of::(); + impl #scrate::traits::PalletRuntimeSetup for PalletRuntimeSetup { + fn index() -> Option { + let type_id = #scrate::sp_std::any::TypeId::of::

(); #( if type_id == #scrate::sp_std::any::TypeId::of::<#names>() { return Some(#indices) @@ -400,6 +403,17 @@ fn decl_module_to_index<'a>( None } + + fn name() -> Option<&'static str> { + let type_id = #scrate::sp_std::any::TypeId::of::

(); + #( + if type_id == #scrate::sp_std::any::TypeId::of::<#names2>() { + return Some(#name_strings) + } + )* + + None + } } ) } diff --git a/frame/support/src/error.rs b/frame/support/src/error.rs index d758ad52e72b3..be20167f77771 100644 --- a/frame/support/src/error.rs +++ b/frame/support/src/error.rs @@ -140,8 +140,8 @@ macro_rules! decl_error { for $crate::sp_runtime::DispatchError { fn from(err: $error<$generic $(, $inst_generic)?>) -> Self { - let index = <$generic::ModuleToIndex as $crate::traits::ModuleToIndex> - ::module_to_index::<$module<$generic $(, $inst_generic)?>>() + let index = <$generic::PalletRuntimeSetup as $crate::traits::PalletRuntimeSetup> + ::index::<$module<$generic $(, $inst_generic)?>>() .expect("Every active module has an index in the runtime; qed") as u8; $crate::sp_runtime::DispatchError::Module { diff --git a/frame/support/src/metadata.rs b/frame/support/src/metadata.rs index aa7d71b52e0b6..5284b2f766b62 100644 --- a/frame/support/src/metadata.rs +++ b/frame/support/src/metadata.rs @@ -297,7 +297,7 @@ mod tests { type AccountId: From + Encode; type BlockNumber: From + Encode; type SomeValue: Get; - type ModuleToIndex: crate::traits::ModuleToIndex; + type PalletRuntimeSetup: crate::traits::PalletRuntimeSetup; type Call; } @@ -443,7 +443,7 @@ mod tests { type AccountId = u32; type BlockNumber = u32; type SomeValue = SystemValue; - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type Call = Call; } diff --git a/frame/support/src/traits.rs b/frame/support/src/traits.rs index 32983b414d304..d62ef11b219ec 100644 --- a/frame/support/src/traits.rs +++ b/frame/support/src/traits.rs @@ -1313,8 +1313,6 @@ impl ChangeMembers for () { fn set_prime(_: Option) {} } - - /// Trait for type that can handle the initialization of account IDs at genesis. pub trait InitializeMembers { /// Initialize the members to the given `members`. @@ -1380,16 +1378,20 @@ pub trait ValidatorRegistration { fn is_registered(id: &ValidatorId) -> bool; } -/// Something that can convert a given module into the index of the module in the runtime. +/// Provides information about the pallet setup in the runtime. /// -/// The index of a module is determined by the position it appears in `construct_runtime!`. -pub trait ModuleToIndex { - /// Convert the given module `M` into an index. - fn module_to_index() -> Option; -} - -impl ModuleToIndex for () { - fn module_to_index() -> Option { Some(0) } +/// An implementor should be able to provide information about each pallet that +/// is configured in `construct_runtime!`. +pub trait PalletRuntimeSetup { + /// Convert the given pallet `P` into its index as configured in the runtime. + fn index() -> Option; + /// Convert the given pallet `P` into its name as configured in the runtime. + fn name() -> Option<&'static str>; +} + +impl PalletRuntimeSetup for () { + fn index() -> Option { Some(0) } + fn name() -> Option<&'static str> { Some("test") } } /// The function and pallet name of the Call. diff --git a/frame/support/test/tests/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index 9cb3a2532a745..a67e58d94c702 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -24,13 +24,14 @@ use sp_runtime::{generic, traits::{BlakeTwo256, Block as _, Verify}, DispatchError}; use sp_core::{H256, sr25519}; use sp_std::cell::RefCell; +use frame_support::traits::PalletRuntimeSetup as _; mod system; pub trait Currency {} thread_local! { - pub static INTEGRITY_TEST_EXEC: RefCell = RefCell::new(0); + pub static INTEGRITY_TEST_EXEC: RefCell = RefCell::new(0); } mod module1 { @@ -107,7 +108,7 @@ impl system::Trait for Runtime { type BlockNumber = BlockNumber; type AccountId = AccountId; type Event = Event; - type ModuleToIndex = ModuleToIndex; + type PalletRuntimeSetup = PalletRuntimeSetup; type Call = Call; } @@ -157,3 +158,15 @@ fn integrity_test_works() { __construct_runtime_integrity_test::runtime_integrity_tests(); assert_eq!(INTEGRITY_TEST_EXEC.with(|i| *i.borrow()), 1); } + +#[test] +fn pallet_in_runtime_is_correct() { + assert_eq!(PalletRuntimeSetup::index::().unwrap(), 0); + assert_eq!(PalletRuntimeSetup::name::().unwrap(), "System"); + + assert_eq!(PalletRuntimeSetup::index::().unwrap(), 3); + assert_eq!(PalletRuntimeSetup::name::().unwrap(), "Module1_2"); + + assert_eq!(PalletRuntimeSetup::index::().unwrap(), 2); + assert_eq!(PalletRuntimeSetup::name::().unwrap(), "Module2"); +} diff --git a/frame/support/test/tests/instance.rs b/frame/support/test/tests/instance.rs index b0df32ddf9c93..5500d825714b3 100644 --- a/frame/support/test/tests/instance.rs +++ b/frame/support/test/tests/instance.rs @@ -241,7 +241,7 @@ impl system::Trait for Runtime { type BlockNumber = BlockNumber; type AccountId = AccountId; type Event = Event; - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type Call = Call; } diff --git a/frame/support/test/tests/issue2219.rs b/frame/support/test/tests/issue2219.rs index 2e47ef64926d6..12e9dd06969e2 100644 --- a/frame/support/test/tests/issue2219.rs +++ b/frame/support/test/tests/issue2219.rs @@ -164,7 +164,7 @@ impl system::Trait for Runtime { type BlockNumber = BlockNumber; type AccountId = AccountId; type Event = Event; - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type Call = Call; } diff --git a/frame/support/test/tests/system.rs b/frame/support/test/tests/system.rs index fd5fe20a69a2b..b9af3ed31271a 100644 --- a/frame/support/test/tests/system.rs +++ b/frame/support/test/tests/system.rs @@ -27,7 +27,7 @@ pub trait Trait: 'static + Eq + Clone { type AccountId: Encode + EncodeLike + Decode; type Call; type Event: From>; - type ModuleToIndex: frame_support::traits::ModuleToIndex; + type PalletRuntimeSetup: frame_support::traits::PalletRuntimeSetup; } frame_support::decl_module! { diff --git a/frame/system/benches/bench.rs b/frame/system/benches/bench.rs index 1b64b813e5910..ed797405256f8 100644 --- a/frame/system/benches/bench.rs +++ b/frame/system/benches/bench.rs @@ -81,7 +81,7 @@ impl system::Trait for Runtime { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/system/benchmarking/src/mock.rs b/frame/system/benchmarking/src/mock.rs index 050fd40afe138..9d7ad3667d212 100644 --- a/frame/system/benchmarking/src/mock.rs +++ b/frame/system/benchmarking/src/mock.rs @@ -71,7 +71,7 @@ impl frame_system::Trait for Test { type AvailableBlockRatio = (); type MaximumBlockLength = (); type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index 93dea5f473075..71ee29908939e 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -117,7 +117,7 @@ use frame_support::{ decl_module, decl_event, decl_storage, decl_error, Parameter, ensure, debug, storage, traits::{ - Contains, Get, ModuleToIndex, OnNewAccount, OnKilledAccount, IsDeadAccount, Happened, + Contains, Get, PalletRuntimeSetup, OnNewAccount, OnKilledAccount, IsDeadAccount, Happened, StoredMap, EnsureOrigin, OriginTrait, Filter, }, weights::{ @@ -256,11 +256,13 @@ pub trait Trait: 'static + Eq + Clone { /// Get the chain's current version. type Version: Get; - /// Convert a module to its index in the runtime. + /// Provides information about the pallet setup in the runtime. /// - /// Expects the `ModuleToIndex` type that is being generated by `construct_runtime!` in the - /// runtime. For tests it is okay to use `()` as type (returns `0` for each input). - type ModuleToIndex: ModuleToIndex; + /// Expects the `PalletRuntimeSetup` type that is being generated by `construct_runtime!` in the + /// runtime. + /// + /// For tests it is okay to use `()` as type, however it will provide "useless" data. + type PalletRuntimeSetup: PalletRuntimeSetup; /// Data to be associated with an account (other than nonce/transaction counter, which this /// module does regardless). diff --git a/frame/system/src/mock.rs b/frame/system/src/mock.rs index d7c4d1c9e7b20..ef0a2fc3fec4e 100644 --- a/frame/system/src/mock.rs +++ b/frame/system/src/mock.rs @@ -101,7 +101,7 @@ impl Trait for Test { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = Version; - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = u32; type OnNewAccount = (); type OnKilledAccount = RecordKilled; diff --git a/frame/timestamp/src/lib.rs b/frame/timestamp/src/lib.rs index d74a94cb9201b..c323bb056f6ca 100644 --- a/frame/timestamp/src/lib.rs +++ b/frame/timestamp/src/lib.rs @@ -339,7 +339,7 @@ mod tests { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index bfd69ea29e3b9..523f9c34d7306 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -654,7 +654,7 @@ mod tests { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/treasury/src/tests.rs b/frame/treasury/src/tests.rs index a4e1e3d8d77b2..71c0204b8cb9b 100644 --- a/frame/treasury/src/tests.rs +++ b/frame/treasury/src/tests.rs @@ -80,7 +80,7 @@ impl frame_system::Trait for Test { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/utility/src/tests.rs b/frame/utility/src/tests.rs index cf5b0dd7568e7..2b3720d421db2 100644 --- a/frame/utility/src/tests.rs +++ b/frame/utility/src/tests.rs @@ -79,7 +79,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/vesting/src/lib.rs b/frame/vesting/src/lib.rs index 223dc168645f4..901f3c1643300 100644 --- a/frame/vesting/src/lib.rs +++ b/frame/vesting/src/lib.rs @@ -444,7 +444,7 @@ mod tests { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index a67d2455be18d..5590a41169ac5 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -453,7 +453,7 @@ impl frame_system::Trait for Runtime { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type ModuleToIndex = (); + type PalletRuntimeSetup = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); From 7dcbcf1c52511ab25b94e0d67ef76b3de0ff7755 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Tue, 22 Sep 2020 09:40:31 +0200 Subject: [PATCH 04/16] Rename it to `PalletInfo` --- bin/node-template/pallets/template/src/mock.rs | 2 +- bin/node-template/runtime/src/lib.rs | 2 +- bin/node/runtime/src/lib.rs | 2 +- frame/assets/src/lib.rs | 2 +- frame/atomic-swap/src/tests.rs | 2 +- frame/aura/src/mock.rs | 2 +- frame/authority-discovery/src/lib.rs | 2 +- frame/authorship/src/lib.rs | 2 +- frame/babe/src/mock.rs | 2 +- frame/balances/src/lib.rs | 2 +- frame/balances/src/tests_composite.rs | 2 +- frame/balances/src/tests_local.rs | 2 +- frame/benchmarking/src/tests.rs | 2 +- frame/collective/src/lib.rs | 2 +- frame/contracts/src/tests.rs | 2 +- frame/democracy/src/tests.rs | 2 +- frame/elections-phragmen/src/lib.rs | 2 +- frame/elections/src/mock.rs | 2 +- frame/evm/src/tests.rs | 2 +- frame/example-offchain-worker/src/tests.rs | 2 +- frame/example/src/lib.rs | 2 +- frame/executive/src/lib.rs | 2 +- frame/finality-tracker/src/lib.rs | 2 +- frame/generic-asset/src/lib.rs | 2 +- frame/generic-asset/src/mock.rs | 2 +- frame/grandpa/src/mock.rs | 2 +- frame/identity/src/tests.rs | 2 +- frame/im-online/src/mock.rs | 2 +- frame/indices/src/mock.rs | 2 +- frame/membership/src/lib.rs | 2 +- frame/multisig/src/tests.rs | 2 +- frame/nicks/src/lib.rs | 2 +- frame/node-authorization/src/lib.rs | 2 +- frame/offences/benchmarking/src/mock.rs | 2 +- frame/offences/src/mock.rs | 2 +- frame/proxy/src/tests.rs | 2 +- frame/randomness-collective-flip/src/lib.rs | 2 +- frame/recovery/src/mock.rs | 2 +- frame/scheduler/src/lib.rs | 2 +- frame/scored-pool/src/mock.rs | 2 +- frame/session/benchmarking/src/mock.rs | 2 +- frame/session/src/mock.rs | 2 +- frame/society/src/mock.rs | 2 +- frame/staking/fuzzer/src/mock.rs | 2 +- frame/staking/src/mock.rs | 2 +- frame/sudo/src/mock.rs | 2 +- .../procedural/src/construct_runtime/mod.rs | 6 +++--- frame/support/src/error.rs | 2 +- frame/support/src/metadata.rs | 4 ++-- frame/support/src/traits.rs | 4 ++-- frame/support/test/tests/construct_runtime.rs | 16 ++++++++-------- frame/support/test/tests/instance.rs | 2 +- frame/support/test/tests/issue2219.rs | 2 +- frame/support/test/tests/system.rs | 2 +- frame/system/benches/bench.rs | 2 +- frame/system/benchmarking/src/mock.rs | 2 +- frame/system/src/lib.rs | 6 +++--- frame/system/src/mock.rs | 2 +- frame/timestamp/src/lib.rs | 2 +- frame/transaction-payment/src/lib.rs | 2 +- frame/treasury/src/tests.rs | 2 +- frame/utility/src/tests.rs | 2 +- frame/vesting/src/lib.rs | 2 +- test-utils/runtime/src/lib.rs | 2 +- 64 files changed, 77 insertions(+), 77 deletions(-) diff --git a/bin/node-template/pallets/template/src/mock.rs b/bin/node-template/pallets/template/src/mock.rs index 41246023441e4..a3dff240e4847 100644 --- a/bin/node-template/pallets/template/src/mock.rs +++ b/bin/node-template/pallets/template/src/mock.rs @@ -42,7 +42,7 @@ impl system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/bin/node-template/runtime/src/lib.rs b/bin/node-template/runtime/src/lib.rs index 10ec47dd4e2ee..620a597f94c06 100644 --- a/bin/node-template/runtime/src/lib.rs +++ b/bin/node-template/runtime/src/lib.rs @@ -181,7 +181,7 @@ impl frame_system::Trait for Runtime { /// Converts a module to the index of the module in `construct_runtime!`. /// /// This type is being generated by `construct_runtime!`. - type PalletRuntimeSetup = PalletRuntimeSetup; + type PalletInfo = PalletInfo; /// What to do if a new account is created. type OnNewAccount = (); /// What to do if an account is fully reaped from the system. diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index ef01631987df8..15082cb806ff4 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -179,7 +179,7 @@ impl frame_system::Trait for Runtime { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = Version; - type PalletRuntimeSetup = PalletRuntimeSetup; + type PalletInfo = PalletInfo; type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/assets/src/lib.rs b/frame/assets/src/lib.rs index 4d8cb01dff404..e5ad2ae352eb8 100644 --- a/frame/assets/src/lib.rs +++ b/frame/assets/src/lib.rs @@ -319,7 +319,7 @@ mod tests { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/atomic-swap/src/tests.rs b/frame/atomic-swap/src/tests.rs index fe61743d737db..060411c8815da 100644 --- a/frame/atomic-swap/src/tests.rs +++ b/frame/atomic-swap/src/tests.rs @@ -45,7 +45,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/aura/src/mock.rs b/frame/aura/src/mock.rs index 1153809224934..a3875727e47c2 100644 --- a/frame/aura/src/mock.rs +++ b/frame/aura/src/mock.rs @@ -66,7 +66,7 @@ impl frame_system::Trait for Test { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/authority-discovery/src/lib.rs b/frame/authority-discovery/src/lib.rs index ab9d385fb8489..09be533474fca 100644 --- a/frame/authority-discovery/src/lib.rs +++ b/frame/authority-discovery/src/lib.rs @@ -164,7 +164,7 @@ mod tests { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/authorship/src/lib.rs b/frame/authorship/src/lib.rs index 657bb03bcbea5..0a10c8849571b 100644 --- a/frame/authorship/src/lib.rs +++ b/frame/authorship/src/lib.rs @@ -438,7 +438,7 @@ mod tests { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/babe/src/mock.rs b/frame/babe/src/mock.rs index 8dbab2e1b23b9..80f1f1d5107f7 100644 --- a/frame/babe/src/mock.rs +++ b/frame/babe/src/mock.rs @@ -86,7 +86,7 @@ impl frame_system::Trait for Test { type MaximumExtrinsicWeight = MaximumBlockWeight; type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index 8bb11e16ea2b1..422e112bdf276 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -902,7 +902,7 @@ impl, I: Instance> frame_system::Trait for ElevatedTrait { type MaximumBlockLength = T::MaximumBlockLength; type AvailableBlockRatio = T::AvailableBlockRatio; type Version = T::Version; - type PalletRuntimeSetup = T::PalletRuntimeSetup; + type PalletInfo = T::PalletInfo; type OnNewAccount = T::OnNewAccount; type OnKilledAccount = T::OnKilledAccount; type AccountData = T::AccountData; diff --git a/frame/balances/src/tests_composite.rs b/frame/balances/src/tests_composite.rs index 9a24e5bed3421..0ee488d097294 100644 --- a/frame/balances/src/tests_composite.rs +++ b/frame/balances/src/tests_composite.rs @@ -87,7 +87,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = super::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/balances/src/tests_local.rs b/frame/balances/src/tests_local.rs index b48c3aa40c31d..4efcdad8ca334 100644 --- a/frame/balances/src/tests_local.rs +++ b/frame/balances/src/tests_local.rs @@ -87,7 +87,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = super::AccountData; type OnNewAccount = (); type OnKilledAccount = Module; diff --git a/frame/benchmarking/src/tests.rs b/frame/benchmarking/src/tests.rs index a091e7c1c52a4..0429d98e18618 100644 --- a/frame/benchmarking/src/tests.rs +++ b/frame/benchmarking/src/tests.rs @@ -93,7 +93,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = (); type AvailableBlockRatio = (); type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index 475589cfb0754..dd44f5e2aea9e 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -985,7 +985,7 @@ mod tests { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index 84f5c0a446359..83a680396f417 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -137,7 +137,7 @@ impl frame_system::Trait for Test { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/democracy/src/tests.rs b/frame/democracy/src/tests.rs index ebda51735de3d..7f23eb4cca8ad 100644 --- a/frame/democracy/src/tests.rs +++ b/frame/democracy/src/tests.rs @@ -112,7 +112,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index ae1f3b525191c..ead51bc593a1d 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -1139,7 +1139,7 @@ mod tests { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/elections/src/mock.rs b/frame/elections/src/mock.rs index 5047541116344..deec77da7b837 100644 --- a/frame/elections/src/mock.rs +++ b/frame/elections/src/mock.rs @@ -59,7 +59,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/evm/src/tests.rs b/frame/evm/src/tests.rs index 2e06feb352d15..d05fdca1407e5 100644 --- a/frame/evm/src/tests.rs +++ b/frame/evm/src/tests.rs @@ -52,7 +52,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/example-offchain-worker/src/tests.rs b/frame/example-offchain-worker/src/tests.rs index 770d03ebe6669..b71329b5ee1b8 100644 --- a/frame/example-offchain-worker/src/tests.rs +++ b/frame/example-offchain-worker/src/tests.rs @@ -74,7 +74,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/example/src/lib.rs b/frame/example/src/lib.rs index 71eff03a0177e..230aacbc01d5a 100644 --- a/frame/example/src/lib.rs +++ b/frame/example/src/lib.rs @@ -764,7 +764,7 @@ mod tests { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index eaaa2728ecbbc..3e5bbb1e25c0f 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -591,7 +591,7 @@ mod tests { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = RuntimeVersion; - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/finality-tracker/src/lib.rs b/frame/finality-tracker/src/lib.rs index 259b37bfb8f7f..3b38c4c20033f 100644 --- a/frame/finality-tracker/src/lib.rs +++ b/frame/finality-tracker/src/lib.rs @@ -273,7 +273,7 @@ mod tests { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/generic-asset/src/lib.rs b/frame/generic-asset/src/lib.rs index 861b98eecadbb..45449f65c8e8c 100644 --- a/frame/generic-asset/src/lib.rs +++ b/frame/generic-asset/src/lib.rs @@ -1131,7 +1131,7 @@ impl frame_system::Trait for ElevatedTrait { type MaximumBlockLength = T::MaximumBlockLength; type AvailableBlockRatio = T::AvailableBlockRatio; type Version = T::Version; - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/generic-asset/src/mock.rs b/frame/generic-asset/src/mock.rs index b001813174642..7daf959a4b88c 100644 --- a/frame/generic-asset/src/mock.rs +++ b/frame/generic-asset/src/mock.rs @@ -63,7 +63,7 @@ impl frame_system::Trait for Test { type AvailableBlockRatio = AvailableBlockRatio; type BlockHashCount = BlockHashCount; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/grandpa/src/mock.rs b/frame/grandpa/src/mock.rs index 8fc33e9f37021..4f4b293716a9f 100644 --- a/frame/grandpa/src/mock.rs +++ b/frame/grandpa/src/mock.rs @@ -100,7 +100,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/identity/src/tests.rs b/frame/identity/src/tests.rs index e7943de79917d..0637ac6aafc5f 100644 --- a/frame/identity/src/tests.rs +++ b/frame/identity/src/tests.rs @@ -63,7 +63,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/im-online/src/mock.rs b/frame/im-online/src/mock.rs index b3f06efd6107d..dae4bb3447e56 100644 --- a/frame/im-online/src/mock.rs +++ b/frame/im-online/src/mock.rs @@ -130,7 +130,7 @@ impl frame_system::Trait for Runtime { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/indices/src/mock.rs b/frame/indices/src/mock.rs index 1d43201ef1dcb..cfbd2e38c3d3f 100644 --- a/frame/indices/src/mock.rs +++ b/frame/indices/src/mock.rs @@ -70,7 +70,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/membership/src/lib.rs b/frame/membership/src/lib.rs index e5a4bdddd56a2..492fda88dd170 100644 --- a/frame/membership/src/lib.rs +++ b/frame/membership/src/lib.rs @@ -320,7 +320,7 @@ mod tests { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/multisig/src/tests.rs b/frame/multisig/src/tests.rs index 075f8e397dbeb..ca15e04597eaa 100644 --- a/frame/multisig/src/tests.rs +++ b/frame/multisig/src/tests.rs @@ -80,7 +80,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/nicks/src/lib.rs b/frame/nicks/src/lib.rs index b4c1325f3da75..ddeadfb7680fe 100644 --- a/frame/nicks/src/lib.rs +++ b/frame/nicks/src/lib.rs @@ -283,7 +283,7 @@ mod tests { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/node-authorization/src/lib.rs b/frame/node-authorization/src/lib.rs index 15c190495e0fd..91f89ad1d9100 100644 --- a/frame/node-authorization/src/lib.rs +++ b/frame/node-authorization/src/lib.rs @@ -474,7 +474,7 @@ mod tests { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/offences/benchmarking/src/mock.rs b/frame/offences/benchmarking/src/mock.rs index f0884f411be44..499d3547e95dd 100644 --- a/frame/offences/benchmarking/src/mock.rs +++ b/frame/offences/benchmarking/src/mock.rs @@ -59,7 +59,7 @@ impl frame_system::Trait for Test { type AvailableBlockRatio = (); type MaximumBlockLength = (); type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (Balances,); diff --git a/frame/offences/src/mock.rs b/frame/offences/src/mock.rs index 8bb6b532ee23f..d2334134e033f 100644 --- a/frame/offences/src/mock.rs +++ b/frame/offences/src/mock.rs @@ -116,7 +116,7 @@ impl frame_system::Trait for Runtime { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/proxy/src/tests.rs b/frame/proxy/src/tests.rs index 4e925478ed58f..bcf3b678ed644 100644 --- a/frame/proxy/src/tests.rs +++ b/frame/proxy/src/tests.rs @@ -82,7 +82,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/randomness-collective-flip/src/lib.rs b/frame/randomness-collective-flip/src/lib.rs index bf873624f1405..6b1b9f4f37448 100644 --- a/frame/randomness-collective-flip/src/lib.rs +++ b/frame/randomness-collective-flip/src/lib.rs @@ -178,7 +178,7 @@ mod tests { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/recovery/src/mock.rs b/frame/recovery/src/mock.rs index 6262141baa880..35373562487f7 100644 --- a/frame/recovery/src/mock.rs +++ b/frame/recovery/src/mock.rs @@ -79,7 +79,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/scheduler/src/lib.rs b/frame/scheduler/src/lib.rs index fc4dcc1eab657..3024c7d6d0d05 100644 --- a/frame/scheduler/src/lib.rs +++ b/frame/scheduler/src/lib.rs @@ -735,7 +735,7 @@ mod tests { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/scored-pool/src/mock.rs b/frame/scored-pool/src/mock.rs index 13f6244864630..59c0dc66cca60 100644 --- a/frame/scored-pool/src/mock.rs +++ b/frame/scored-pool/src/mock.rs @@ -70,7 +70,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/session/benchmarking/src/mock.rs b/frame/session/benchmarking/src/mock.rs index 76954187f133d..645ac14d88a44 100644 --- a/frame/session/benchmarking/src/mock.rs +++ b/frame/session/benchmarking/src/mock.rs @@ -78,7 +78,7 @@ impl frame_system::Trait for Test { type AvailableBlockRatio = (); type MaximumBlockLength = (); type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = Balances; diff --git a/frame/session/src/mock.rs b/frame/session/src/mock.rs index d3ac87fd72641..1d787ac53b438 100644 --- a/frame/session/src/mock.rs +++ b/frame/session/src/mock.rs @@ -193,7 +193,7 @@ impl frame_system::Trait for Test { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/society/src/mock.rs b/frame/society/src/mock.rs index 1d81108bff760..212bcfd404ff1 100644 --- a/frame/society/src/mock.rs +++ b/frame/society/src/mock.rs @@ -81,7 +81,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type OnNewAccount = (); type OnKilledAccount = (); type AccountData = pallet_balances::AccountData; diff --git a/frame/staking/fuzzer/src/mock.rs b/frame/staking/fuzzer/src/mock.rs index 2c9438bfa9405..aae044d75acd9 100644 --- a/frame/staking/fuzzer/src/mock.rs +++ b/frame/staking/fuzzer/src/mock.rs @@ -77,7 +77,7 @@ impl frame_system::Trait for Test { type AvailableBlockRatio = (); type MaximumBlockLength = (); type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (Balances,); diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index b15b53c07ca81..ce1aa9339d4ba 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -220,7 +220,7 @@ impl frame_system::Trait for Test { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/sudo/src/mock.rs b/frame/sudo/src/mock.rs index 0e3f0d0d50843..7996cd05d071f 100644 --- a/frame/sudo/src/mock.rs +++ b/frame/sudo/src/mock.rs @@ -139,7 +139,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/support/procedural/src/construct_runtime/mod.rs b/frame/support/procedural/src/construct_runtime/mod.rs index 0376f2f37b927..867b6a72f4586 100644 --- a/frame/support/procedural/src/construct_runtime/mod.rs +++ b/frame/support/procedural/src/construct_runtime/mod.rs @@ -388,11 +388,11 @@ fn decl_pallet_runtime_setup( let indices = 0..module_declarations.len(); quote!( - /// Provides an implementation of `PalletRuntimeSetup` to provide information + /// Provides an implementation of `PalletInfo` to provide information /// about the pallet setup in the runtime. - pub struct PalletRuntimeSetup; + pub struct PalletInfo; - impl #scrate::traits::PalletRuntimeSetup for PalletRuntimeSetup { + impl #scrate::traits::PalletInfo for PalletInfo { fn index() -> Option { let type_id = #scrate::sp_std::any::TypeId::of::

(); #( diff --git a/frame/support/src/error.rs b/frame/support/src/error.rs index be20167f77771..ef963f3c59733 100644 --- a/frame/support/src/error.rs +++ b/frame/support/src/error.rs @@ -140,7 +140,7 @@ macro_rules! decl_error { for $crate::sp_runtime::DispatchError { fn from(err: $error<$generic $(, $inst_generic)?>) -> Self { - let index = <$generic::PalletRuntimeSetup as $crate::traits::PalletRuntimeSetup> + let index = <$generic::PalletInfo as $crate::traits::PalletInfo> ::index::<$module<$generic $(, $inst_generic)?>>() .expect("Every active module has an index in the runtime; qed") as u8; diff --git a/frame/support/src/metadata.rs b/frame/support/src/metadata.rs index 5284b2f766b62..8d3b5fb527af7 100644 --- a/frame/support/src/metadata.rs +++ b/frame/support/src/metadata.rs @@ -297,7 +297,7 @@ mod tests { type AccountId: From + Encode; type BlockNumber: From + Encode; type SomeValue: Get; - type PalletRuntimeSetup: crate::traits::PalletRuntimeSetup; + type PalletInfo: crate::traits::PalletInfo; type Call; } @@ -443,7 +443,7 @@ mod tests { type AccountId = u32; type BlockNumber = u32; type SomeValue = SystemValue; - type PalletRuntimeSetup = (); + type PalletInfo = (); type Call = Call; } diff --git a/frame/support/src/traits.rs b/frame/support/src/traits.rs index d62ef11b219ec..d047183eab93e 100644 --- a/frame/support/src/traits.rs +++ b/frame/support/src/traits.rs @@ -1382,14 +1382,14 @@ pub trait ValidatorRegistration { /// /// An implementor should be able to provide information about each pallet that /// is configured in `construct_runtime!`. -pub trait PalletRuntimeSetup { +pub trait PalletInfo { /// Convert the given pallet `P` into its index as configured in the runtime. fn index() -> Option; /// Convert the given pallet `P` into its name as configured in the runtime. fn name() -> Option<&'static str>; } -impl PalletRuntimeSetup for () { +impl PalletInfo for () { fn index() -> Option { Some(0) } fn name() -> Option<&'static str> { Some("test") } } diff --git a/frame/support/test/tests/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index a67e58d94c702..5596943031148 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -24,7 +24,7 @@ use sp_runtime::{generic, traits::{BlakeTwo256, Block as _, Verify}, DispatchError}; use sp_core::{H256, sr25519}; use sp_std::cell::RefCell; -use frame_support::traits::PalletRuntimeSetup as _; +use frame_support::traits::PalletInfo as _; mod system; @@ -108,7 +108,7 @@ impl system::Trait for Runtime { type BlockNumber = BlockNumber; type AccountId = AccountId; type Event = Event; - type PalletRuntimeSetup = PalletRuntimeSetup; + type PalletInfo = PalletInfo; type Call = Call; } @@ -161,12 +161,12 @@ fn integrity_test_works() { #[test] fn pallet_in_runtime_is_correct() { - assert_eq!(PalletRuntimeSetup::index::().unwrap(), 0); - assert_eq!(PalletRuntimeSetup::name::().unwrap(), "System"); + assert_eq!(PalletInfo::index::().unwrap(), 0); + assert_eq!(PalletInfo::name::().unwrap(), "System"); - assert_eq!(PalletRuntimeSetup::index::().unwrap(), 3); - assert_eq!(PalletRuntimeSetup::name::().unwrap(), "Module1_2"); + assert_eq!(PalletInfo::index::().unwrap(), 3); + assert_eq!(PalletInfo::name::().unwrap(), "Module1_2"); - assert_eq!(PalletRuntimeSetup::index::().unwrap(), 2); - assert_eq!(PalletRuntimeSetup::name::().unwrap(), "Module2"); + assert_eq!(PalletInfo::index::().unwrap(), 2); + assert_eq!(PalletInfo::name::().unwrap(), "Module2"); } diff --git a/frame/support/test/tests/instance.rs b/frame/support/test/tests/instance.rs index 5500d825714b3..0e4240528a379 100644 --- a/frame/support/test/tests/instance.rs +++ b/frame/support/test/tests/instance.rs @@ -241,7 +241,7 @@ impl system::Trait for Runtime { type BlockNumber = BlockNumber; type AccountId = AccountId; type Event = Event; - type PalletRuntimeSetup = (); + type PalletInfo = (); type Call = Call; } diff --git a/frame/support/test/tests/issue2219.rs b/frame/support/test/tests/issue2219.rs index 12e9dd06969e2..34310c2f5876f 100644 --- a/frame/support/test/tests/issue2219.rs +++ b/frame/support/test/tests/issue2219.rs @@ -164,7 +164,7 @@ impl system::Trait for Runtime { type BlockNumber = BlockNumber; type AccountId = AccountId; type Event = Event; - type PalletRuntimeSetup = (); + type PalletInfo = (); type Call = Call; } diff --git a/frame/support/test/tests/system.rs b/frame/support/test/tests/system.rs index b9af3ed31271a..90ce05199e16d 100644 --- a/frame/support/test/tests/system.rs +++ b/frame/support/test/tests/system.rs @@ -27,7 +27,7 @@ pub trait Trait: 'static + Eq + Clone { type AccountId: Encode + EncodeLike + Decode; type Call; type Event: From>; - type PalletRuntimeSetup: frame_support::traits::PalletRuntimeSetup; + type PalletInfo: frame_support::traits::PalletInfo; } frame_support::decl_module! { diff --git a/frame/system/benches/bench.rs b/frame/system/benches/bench.rs index ed797405256f8..00c965136c0d0 100644 --- a/frame/system/benches/bench.rs +++ b/frame/system/benches/bench.rs @@ -81,7 +81,7 @@ impl system::Trait for Runtime { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/system/benchmarking/src/mock.rs b/frame/system/benchmarking/src/mock.rs index 9d7ad3667d212..33255d7b50e19 100644 --- a/frame/system/benchmarking/src/mock.rs +++ b/frame/system/benchmarking/src/mock.rs @@ -71,7 +71,7 @@ impl frame_system::Trait for Test { type AvailableBlockRatio = (); type MaximumBlockLength = (); type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index 71ee29908939e..dd9d1fe6fa2b4 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -117,7 +117,7 @@ use frame_support::{ decl_module, decl_event, decl_storage, decl_error, Parameter, ensure, debug, storage, traits::{ - Contains, Get, PalletRuntimeSetup, OnNewAccount, OnKilledAccount, IsDeadAccount, Happened, + Contains, Get, PalletInfo, OnNewAccount, OnKilledAccount, IsDeadAccount, Happened, StoredMap, EnsureOrigin, OriginTrait, Filter, }, weights::{ @@ -258,11 +258,11 @@ pub trait Trait: 'static + Eq + Clone { /// Provides information about the pallet setup in the runtime. /// - /// Expects the `PalletRuntimeSetup` type that is being generated by `construct_runtime!` in the + /// Expects the `PalletInfo` type that is being generated by `construct_runtime!` in the /// runtime. /// /// For tests it is okay to use `()` as type, however it will provide "useless" data. - type PalletRuntimeSetup: PalletRuntimeSetup; + type PalletInfo: PalletInfo; /// Data to be associated with an account (other than nonce/transaction counter, which this /// module does regardless). diff --git a/frame/system/src/mock.rs b/frame/system/src/mock.rs index ef0a2fc3fec4e..cd67a74114073 100644 --- a/frame/system/src/mock.rs +++ b/frame/system/src/mock.rs @@ -101,7 +101,7 @@ impl Trait for Test { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = Version; - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = u32; type OnNewAccount = (); type OnKilledAccount = RecordKilled; diff --git a/frame/timestamp/src/lib.rs b/frame/timestamp/src/lib.rs index c323bb056f6ca..959382c07b610 100644 --- a/frame/timestamp/src/lib.rs +++ b/frame/timestamp/src/lib.rs @@ -339,7 +339,7 @@ mod tests { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index 523f9c34d7306..09caae54cf348 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -654,7 +654,7 @@ mod tests { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/treasury/src/tests.rs b/frame/treasury/src/tests.rs index a9a44b3ae41c8..d8cebbcd693ef 100644 --- a/frame/treasury/src/tests.rs +++ b/frame/treasury/src/tests.rs @@ -80,7 +80,7 @@ impl frame_system::Trait for Test { type AvailableBlockRatio = AvailableBlockRatio; type MaximumBlockLength = MaximumBlockLength; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/utility/src/tests.rs b/frame/utility/src/tests.rs index 2b3720d421db2..8e693b234a939 100644 --- a/frame/utility/src/tests.rs +++ b/frame/utility/src/tests.rs @@ -79,7 +79,7 @@ impl frame_system::Trait for Test { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/frame/vesting/src/lib.rs b/frame/vesting/src/lib.rs index 901f3c1643300..1583b06d69f83 100644 --- a/frame/vesting/src/lib.rs +++ b/frame/vesting/src/lib.rs @@ -444,7 +444,7 @@ mod tests { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index 5590a41169ac5..06576dd2a449f 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -453,7 +453,7 @@ impl frame_system::Trait for Runtime { type MaximumBlockLength = MaximumBlockLength; type AvailableBlockRatio = AvailableBlockRatio; type Version = (); - type PalletRuntimeSetup = (); + type PalletInfo = (); type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); From c6e7b8a7873ad5d0487f0c129c16553559624a79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Tue, 22 Sep 2020 10:02:38 +0200 Subject: [PATCH 05/16] Remove accidentally added files --- frame/generic-asset/src/lib.rs | 1369 ------------------------------- frame/generic-asset/src/mock.rs | 152 ---- 2 files changed, 1521 deletions(-) delete mode 100644 frame/generic-asset/src/lib.rs delete mode 100644 frame/generic-asset/src/mock.rs diff --git a/frame/generic-asset/src/lib.rs b/frame/generic-asset/src/lib.rs deleted file mode 100644 index 45449f65c8e8c..0000000000000 --- a/frame/generic-asset/src/lib.rs +++ /dev/null @@ -1,1369 +0,0 @@ -// Copyright 2019-2020 -// by Centrality Investments Ltd. -// and Parity Technologies (UK) Ltd. -// This file is part of Substrate. - -// Substrate 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. - -// Substrate 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 Substrate. If not, see . - -//! # Generic Asset Module -//! -//! The Generic Asset module provides functionality for handling accounts and asset balances. -//! -//! ## Overview -//! -//! The Generic Asset module provides functions for: -//! -//! - Creating a new kind of asset. -//! - Setting permissions of an asset. -//! - Getting and setting free balances. -//! - Retrieving total, reserved and unreserved balances. -//! - Repatriating a reserved balance to a beneficiary account. -//! - Transferring a balance between accounts (when not reserved). -//! - Slashing an account balance. -//! - Managing total issuance. -//! - Setting and managing locks. -//! -//! ### Terminology -//! -//! - **Staking Asset:** The asset for staking, to participate as Validators in the network. -//! - **Spending Asset:** The asset for payment, such as paying transfer fees, gas fees, etc. -//! - **Permissions:** A set of rules for a kind of asset, defining the allowed operations to the asset, and which -//! accounts are allowed to possess it. -//! - **Total Issuance:** The total number of units in existence in a system. -//! - **Free Balance:** The portion of a balance that is not reserved. The free balance is the only balance that matters -//! for most operations. When this balance falls below the existential deposit, most functionality of the account is -//! removed. When both it and the reserved balance are deleted, then the account is said to be dead. -//! - **Reserved Balance:** Reserved balance still belongs to the account holder, but is suspended. Reserved balance -//! can still be slashed, but only after all the free balance has been slashed. If the reserved balance falls below the -//! existential deposit then it and any related functionality will be deleted. When both it and the free balance are -//! deleted, then the account is said to be dead. -//! - **Imbalance:** A condition when some assets were credited or debited without equal and opposite accounting -//! (i.e. a difference between total issuance and account balances). Functions that result in an imbalance will -//! return an object of the `Imbalance` trait that can be managed within your runtime logic. (If an imbalance is -//! simply dropped, it should automatically maintain any book-keeping such as total issuance.) -//! - **Lock:** A freeze on a specified amount of an account's free balance until a specified block number. Multiple -//! locks always operate over the same funds, so they "overlay" rather than "stack". -//! -//! ### Implementations -//! -//! The Generic Asset module provides `AssetCurrency`, which implements the following traits. If these traits provide -//! the functionality that you need, you can avoid coupling with the Generic Asset module. -//! -//! - `Currency`: Functions for dealing with a fungible assets system. -//! - `ReservableCurrency`: Functions for dealing with assets that can be reserved from an account. -//! - `LockableCurrency`: Functions for dealing with accounts that allow liquidity restrictions. -//! - `Imbalance`: Functions for handling imbalances between total issuance in the system and account balances. -//! Must be used when a function creates new assets (e.g. a reward) or destroys some assets (e.g. a system fee). -//! -//! The Generic Asset module provides two types of `AssetCurrency` as follows. -//! -//! - `StakingAssetCurrency`: Currency for staking. -//! - `SpendingAssetCurrency`: Currency for payments such as transfer fee, gas fee. -//! -//! ## Interface -//! -//! ### Dispatchable Functions -//! -//! - `create`: Create a new kind of asset. -//! - `transfer`: Transfer some liquid free balance to another account. -//! - `update_permission`: Updates permission for a given `asset_id` and an account. The origin of this call -//! must have update permissions. -//! - `mint`: Mint an asset, increases its total issuance. The origin of this call must have mint permissions. -//! - `burn`: Burn an asset, decreases its total issuance. The origin of this call must have burn permissions. -//! - `create_reserved`: Create a new kind of reserved asset. The origin of this call must be root. -//! -//! ### Public Functions -//! -//! - `total_balance`: Get an account's total balance of an asset kind. -//! - `free_balance`: Get an account's free balance of an asset kind. -//! - `reserved_balance`: Get an account's reserved balance of an asset kind. -//! - `create_asset`: Creates an asset. -//! - `make_transfer`: Transfer some liquid free balance from one account to another. -//! This will not emit the `Transferred` event. -//! - `make_transfer_with_event`: Transfer some liquid free balance from one account to another. -//! This will emit the `Transferred` event. -//! - `reserve`: Moves an amount from free balance to reserved balance. -//! - `unreserve`: Move up to an amount from reserved balance to free balance. This function cannot fail. -//! - `mint_free`: Mint to an account's free balance. -//! - `burn_free`: Burn an account's free balance. -//! - `slash`: Deduct up to an amount from the combined balance of `who`, preferring to deduct from the -//! free balance. This function cannot fail. -//! - `slash_reserved`: Deduct up to an amount from reserved balance of an account. This function cannot fail. -//! - `repatriate_reserved`: Move up to an amount from reserved balance of an account to free balance of another -//! account. -//! - `check_permission`: Check permission to perform burn, mint or update. -//! - `ensure_can_withdraw`: Check if the account is able to make a withdrawal of the given amount -//! for the given reason. -//! -//! ### Usage -//! -//! The following examples show how to use the Generic Asset Pallet in your custom pallet. -//! -//! ### Examples from the FRAME pallet -//! -//! The Fees Pallet uses the `Currency` trait to handle fee charge/refund, and its types inherit from `Currency`: -//! -//! ``` -//! use frame_support::{ -//! dispatch, -//! traits::{Currency, ExistenceRequirement, WithdrawReason}, -//! }; -//! # pub trait Trait: frame_system::Trait { -//! # type Currency: Currency; -//! # } -//! type AssetOf = <::Currency as Currency<::AccountId>>::Balance; -//! -//! fn charge_fee(transactor: &T::AccountId, amount: AssetOf) -> dispatch::DispatchResult { -//! // ... -//! T::Currency::withdraw( -//! transactor, -//! amount, -//! WithdrawReason::TransactionPayment.into(), -//! ExistenceRequirement::KeepAlive, -//! )?; -//! // ... -//! Ok(()) -//! } -//! -//! fn refund_fee(transactor: &T::AccountId, amount: AssetOf) -> dispatch::DispatchResult { -//! // ... -//! T::Currency::deposit_into_existing(transactor, amount)?; -//! // ... -//! Ok(()) -//! } -//! -//! # fn main() {} -//! ``` -//! -//! ## Genesis config -//! -//! The Generic Asset Pallet depends on the [`GenesisConfig`](./struct.GenesisConfig.html). - -#![cfg_attr(not(feature = "std"), no_std)] - -use codec::{Decode, Encode, HasCompact, Input, Output, Error as CodecError}; - -use sp_runtime::{RuntimeDebug, DispatchResult, DispatchError}; -use sp_runtime::traits::{ - CheckedAdd, CheckedSub, MaybeSerializeDeserialize, Member, One, Saturating, AtLeast32Bit, - Zero, Bounded, AtLeast32BitUnsigned -}; - -use sp_std::prelude::*; -use sp_std::{cmp, result, fmt::Debug}; -use frame_support::{ - decl_event, decl_module, decl_storage, ensure, decl_error, - traits::{ - Currency, ExistenceRequirement, Imbalance, LockIdentifier, LockableCurrency, - ReservableCurrency, SignedImbalance, WithdrawReason, WithdrawReasons, TryDrop, - BalanceStatus, - }, - Parameter, StorageMap, -}; -use frame_system::{ensure_signed, ensure_root}; - -mod mock; -mod tests; - -pub use self::imbalances::{NegativeImbalance, PositiveImbalance}; - -pub trait Trait: frame_system::Trait { - type Balance: Parameter + Member + AtLeast32BitUnsigned + Default + Copy + Debug + - MaybeSerializeDeserialize; - type AssetId: Parameter + Member + AtLeast32Bit + Default + Copy; - type Event: From> + Into<::Event>; -} - -pub trait Subtrait: frame_system::Trait { - type Balance: Parameter + Member + AtLeast32BitUnsigned + Default + Copy + Debug + - MaybeSerializeDeserialize; - type AssetId: Parameter + Member + AtLeast32Bit + Default + Copy; -} - -impl Subtrait for T { - type Balance = T::Balance; - type AssetId = T::AssetId; -} - -/// Asset creation options. -#[derive(Clone, Encode, Decode, PartialEq, Eq, RuntimeDebug)] -pub struct AssetOptions { - /// Initial issuance of this asset. All deposit to the creator of the asset. - #[codec(compact)] - pub initial_issuance: Balance, - /// Which accounts are allowed to possess this asset. - pub permissions: PermissionLatest, -} - -/// Owner of an asset. -#[derive(Clone, Encode, Decode, PartialEq, Eq, RuntimeDebug)] -pub enum Owner { - /// No owner. - None, - /// Owned by an AccountId - Address(AccountId), -} - -impl Default for Owner { - fn default() -> Self { - Owner::None - } -} - -/// Asset permissions -#[derive(Clone, Encode, Decode, PartialEq, Eq, RuntimeDebug)] -pub struct PermissionsV1 { - /// Who have permission to update asset permission - pub update: Owner, - /// Who have permission to mint new asset - pub mint: Owner, - /// Who have permission to burn asset - pub burn: Owner, -} - -#[derive(Clone, Encode, Decode, PartialEq, Eq, RuntimeDebug)] -#[repr(u8)] -enum PermissionVersionNumber { - V1 = 0, -} - -/// Versioned asset permission -#[derive(Clone, PartialEq, Eq, RuntimeDebug)] -pub enum PermissionVersions { - V1(PermissionsV1), -} - -/// Asset permission types -pub enum PermissionType { - /// Permission to burn asset permission - Burn, - /// Permission to mint new asset - Mint, - /// Permission to update asset - Update, -} - -/// Alias to latest asset permissions -pub type PermissionLatest = PermissionsV1; - -impl Default for PermissionVersions { - fn default() -> Self { - PermissionVersions::V1(Default::default()) - } -} - -impl Encode for PermissionVersions { - fn encode_to(&self, dest: &mut T) { - match self { - PermissionVersions::V1(payload) => { - dest.push(&PermissionVersionNumber::V1); - dest.push(payload); - }, - } - } -} - -impl codec::EncodeLike for PermissionVersions {} - -impl Decode for PermissionVersions { - fn decode(input: &mut I) -> core::result::Result { - let version = PermissionVersionNumber::decode(input)?; - Ok( - match version { - PermissionVersionNumber::V1 => PermissionVersions::V1(Decode::decode(input)?) - } - ) - } -} - -impl Default for PermissionsV1 { - fn default() -> Self { - PermissionsV1 { - update: Owner::None, - mint: Owner::None, - burn: Owner::None, - } - } -} - -impl Into> for PermissionVersions { - fn into(self) -> PermissionLatest { - match self { - PermissionVersions::V1(v1) => v1, - } - } -} - -/// Converts the latest permission to other version. -impl Into> for PermissionLatest { - fn into(self) -> PermissionVersions { - PermissionVersions::V1(self) - } -} - -decl_error! { - /// Error for the generic-asset module. - pub enum Error for Module { - /// No new assets id available. - NoIdAvailable, - /// Cannot transfer zero amount. - ZeroAmount, - /// The origin does not have enough permission to update permissions. - NoUpdatePermission, - /// The origin does not have permission to mint an asset. - NoMintPermission, - /// The origin does not have permission to burn an asset. - NoBurnPermission, - /// Total issuance got overflowed after minting. - TotalMintingOverflow, - /// Free balance got overflowed after minting. - FreeMintingOverflow, - /// Total issuance got underflowed after burning. - TotalBurningUnderflow, - /// Free balance got underflowed after burning. - FreeBurningUnderflow, - /// Asset id is already taken. - IdAlreadyTaken, - /// Asset id not available. - IdUnavailable, - /// The balance is too low to send amount. - InsufficientBalance, - /// The account liquidity restrictions prevent withdrawal. - LiquidityRestrictions, - } -} - -decl_module! { - pub struct Module for enum Call where origin: T::Origin { - type Error = Error; - - fn deposit_event() = default; - - /// Create a new kind of asset. - #[weight = 0] - fn create(origin, options: AssetOptions) -> DispatchResult { - let origin = ensure_signed(origin)?; - Self::create_asset(None, Some(origin), options) - } - - /// Transfer some liquid free balance to another account. - #[weight = 0] - pub fn transfer(origin, #[compact] asset_id: T::AssetId, to: T::AccountId, #[compact] amount: T::Balance) { - let origin = ensure_signed(origin)?; - ensure!(!amount.is_zero(), Error::::ZeroAmount); - Self::make_transfer_with_event(&asset_id, &origin, &to, amount)?; - } - - /// Updates permission for a given `asset_id` and an account. - /// - /// The `origin` must have `update` permission. - #[weight = 0] - fn update_permission( - origin, - #[compact] asset_id: T::AssetId, - new_permission: PermissionLatest - ) -> DispatchResult { - let origin = ensure_signed(origin)?; - - let permissions: PermissionVersions = new_permission.into(); - - if Self::check_permission(&asset_id, &origin, &PermissionType::Update) { - >::insert(asset_id, &permissions); - - Self::deposit_event(RawEvent::PermissionUpdated(asset_id, permissions.into())); - - Ok(()) - } else { - Err(Error::::NoUpdatePermission)? - } - } - - /// Mints an asset, increases its total issuance. - /// The origin must have `mint` permissions. - #[weight = 0] - fn mint(origin, #[compact] asset_id: T::AssetId, to: T::AccountId, amount: T::Balance) -> DispatchResult { - let who = ensure_signed(origin)?; - Self::mint_free(&asset_id, &who, &to, &amount)?; - Self::deposit_event(RawEvent::Minted(asset_id, to, amount)); - Ok(()) - } - - /// Burns an asset, decreases its total issuance. - /// The `origin` must have `burn` permissions. - #[weight = 0] - fn burn(origin, #[compact] asset_id: T::AssetId, to: T::AccountId, amount: T::Balance) -> DispatchResult { - let who = ensure_signed(origin)?; - Self::burn_free(&asset_id, &who, &to, &amount)?; - Self::deposit_event(RawEvent::Burned(asset_id, to, amount)); - Ok(()) - } - - /// Can be used to create reserved tokens. - /// Requires Root call. - #[weight = 0] - fn create_reserved( - origin, - asset_id: T::AssetId, - options: AssetOptions - ) -> DispatchResult { - ensure_root(origin)?; - Self::create_asset(Some(asset_id), None, options) - } - } -} - -#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)] -pub struct BalanceLock { - pub id: LockIdentifier, - pub amount: Balance, - pub reasons: WithdrawReasons, -} - -decl_storage! { - trait Store for Module as GenericAsset { - /// Total issuance of a given asset. - /// - /// TWOX-NOTE: `AssetId` is trusted. - pub TotalIssuance get(fn total_issuance) build(|config: &GenesisConfig| { - let issuance = config.initial_balance * (config.endowed_accounts.len() as u32).into(); - config.assets.iter().map(|id| (id.clone(), issuance)).collect::>() - }): map hasher(twox_64_concat) T::AssetId => T::Balance; - - /// The free balance of a given asset under an account. - /// - /// TWOX-NOTE: `AssetId` is trusted. - pub FreeBalance: - double_map hasher(twox_64_concat) T::AssetId, hasher(blake2_128_concat) T::AccountId => T::Balance; - - /// The reserved balance of a given asset under an account. - /// - /// TWOX-NOTE: `AssetId` is trusted. - pub ReservedBalance: - double_map hasher(twox_64_concat) T::AssetId, hasher(blake2_128_concat) T::AccountId => T::Balance; - - /// Next available ID for user-created asset. - pub NextAssetId get(fn next_asset_id) config(): T::AssetId; - - /// Permission options for a given asset. - /// - /// TWOX-NOTE: `AssetId` is trusted. - pub Permissions get(fn get_permission): - map hasher(twox_64_concat) T::AssetId => PermissionVersions; - - /// Any liquidity locks on some account balances. - pub Locks get(fn locks): - map hasher(blake2_128_concat) T::AccountId => Vec>; - - /// The identity of the asset which is the one that is designated for the chain's staking system. - pub StakingAssetId get(fn staking_asset_id) config(): T::AssetId; - - /// The identity of the asset which is the one that is designated for paying the chain's transaction fee. - pub SpendingAssetId get(fn spending_asset_id) config(): T::AssetId; - } - add_extra_genesis { - config(assets): Vec; - config(initial_balance): T::Balance; - config(endowed_accounts): Vec; - - build(|config: &GenesisConfig| { - config.assets.iter().for_each(|asset_id| { - config.endowed_accounts.iter().for_each(|account_id| { - >::insert(asset_id, account_id, &config.initial_balance); - }); - }); - }); - } -} - -decl_event!( - pub enum Event where - ::AccountId, - ::Balance, - ::AssetId, - AssetOptions = AssetOptions<::Balance, ::AccountId> - { - /// Asset created. \[asset_id, creator, asset_options\] - Created(AssetId, AccountId, AssetOptions), - /// Asset transfer succeeded. \[asset_id, from, to, amount\] - Transferred(AssetId, AccountId, AccountId, Balance), - /// Asset permission updated. \[asset_id, new_permissions\] - PermissionUpdated(AssetId, PermissionLatest), - /// New asset minted. \[asset_id, account, amount\] - Minted(AssetId, AccountId, Balance), - /// Asset burned. \[asset_id, account, amount\] - Burned(AssetId, AccountId, Balance), - } -); - -impl Module { - // PUBLIC IMMUTABLES - - /// Get an account's total balance of an asset kind. - pub fn total_balance(asset_id: &T::AssetId, who: &T::AccountId) -> T::Balance { - Self::free_balance(asset_id, who) + Self::reserved_balance(asset_id, who) - } - - /// Get an account's free balance of an asset kind. - pub fn free_balance(asset_id: &T::AssetId, who: &T::AccountId) -> T::Balance { - >::get(asset_id, who) - } - - /// Get an account's reserved balance of an asset kind. - pub fn reserved_balance(asset_id: &T::AssetId, who: &T::AccountId) -> T::Balance { - >::get(asset_id, who) - } - - /// Mint to an account's free balance, without event - pub fn mint_free( - asset_id: &T::AssetId, - who: &T::AccountId, - to: &T::AccountId, - amount: &T::Balance, - ) -> DispatchResult { - if Self::check_permission(asset_id, who, &PermissionType::Mint) { - let original_free_balance = Self::free_balance(&asset_id, &to); - let current_total_issuance = >::get(asset_id); - let new_total_issuance = current_total_issuance.checked_add(&amount) - .ok_or(Error::::TotalMintingOverflow)?; - let value = original_free_balance.checked_add(&amount) - .ok_or(Error::::FreeMintingOverflow)?; - - >::insert(asset_id, new_total_issuance); - Self::set_free_balance(&asset_id, &to, value); - Ok(()) - } else { - Err(Error::::NoMintPermission)? - } - } - - /// Burn an account's free balance, without event - pub fn burn_free( - asset_id: &T::AssetId, - who: &T::AccountId, - to: &T::AccountId, - amount: &T::Balance, - ) -> DispatchResult { - if Self::check_permission(asset_id, who, &PermissionType::Burn) { - let original_free_balance = Self::free_balance(asset_id, to); - - let current_total_issuance = >::get(asset_id); - let new_total_issuance = current_total_issuance.checked_sub(amount) - .ok_or(Error::::TotalBurningUnderflow)?; - let value = original_free_balance.checked_sub(amount) - .ok_or(Error::::FreeBurningUnderflow)?; - - >::insert(asset_id, new_total_issuance); - Self::set_free_balance(asset_id, to, value); - Ok(()) - } else { - Err(Error::::NoBurnPermission)? - } - } - - /// Creates an asset. - /// - /// # Arguments - /// * `asset_id`: An ID of a reserved asset. - /// If not provided, a user-generated asset will be created with the next available ID. - /// * `from_account`: The initiator account of this call - /// * `asset_options`: Asset creation options. - /// - pub fn create_asset( - asset_id: Option, - from_account: Option, - options: AssetOptions, - ) -> DispatchResult { - let asset_id = if let Some(asset_id) = asset_id { - ensure!(!>::contains_key(&asset_id), Error::::IdAlreadyTaken); - ensure!(asset_id < Self::next_asset_id(), Error::::IdUnavailable); - asset_id - } else { - let asset_id = Self::next_asset_id(); - let next_id = asset_id - .checked_add(&One::one()) - .ok_or(Error::::NoIdAvailable)?; - >::put(next_id); - asset_id - }; - - let account_id = from_account.unwrap_or_default(); - let permissions: PermissionVersions = options.permissions.clone().into(); - - >::insert(asset_id, &options.initial_issuance); - >::insert(&asset_id, &account_id, &options.initial_issuance); - >::insert(&asset_id, permissions); - - Self::deposit_event(RawEvent::Created(asset_id, account_id, options)); - - Ok(()) - } - - /// Transfer some liquid free balance from one account to another. - /// This will not emit the `Transferred` event. - pub fn make_transfer( - asset_id: &T::AssetId, - from: &T::AccountId, - to: &T::AccountId, - amount: T::Balance - ) -> DispatchResult { - let new_balance = Self::free_balance(asset_id, from) - .checked_sub(&amount) - .ok_or(Error::::InsufficientBalance)?; - Self::ensure_can_withdraw(asset_id, from, amount, WithdrawReason::Transfer.into(), new_balance)?; - - if from != to { - >::mutate(asset_id, from, |balance| *balance -= amount); - >::mutate(asset_id, to, |balance| *balance += amount); - } - - Ok(()) - } - - /// Transfer some liquid free balance from one account to another. - /// This will emit the `Transferred` event. - pub fn make_transfer_with_event( - asset_id: &T::AssetId, - from: &T::AccountId, - to: &T::AccountId, - amount: T::Balance, - ) -> DispatchResult { - Self::make_transfer(asset_id, from, to, amount)?; - - if from != to { - Self::deposit_event(RawEvent::Transferred(*asset_id, from.clone(), to.clone(), amount)); - } - - Ok(()) - } - - /// Move `amount` from free balance to reserved balance. - /// - /// If the free balance is lower than `amount`, then no funds will be moved and an `Err` will - /// be returned. This is different behavior than `unreserve`. - pub fn reserve(asset_id: &T::AssetId, who: &T::AccountId, amount: T::Balance) - -> DispatchResult - { - // Do we need to consider that this is an atomic transaction? - let original_reserve_balance = Self::reserved_balance(asset_id, who); - let original_free_balance = Self::free_balance(asset_id, who); - if original_free_balance < amount { - Err(Error::::InsufficientBalance)? - } - let new_reserve_balance = original_reserve_balance + amount; - Self::set_reserved_balance(asset_id, who, new_reserve_balance); - let new_free_balance = original_free_balance - amount; - Self::set_free_balance(asset_id, who, new_free_balance); - Ok(()) - } - - /// Moves up to `amount` from reserved balance to free balance. This function cannot fail. - /// - /// As many assets up to `amount` will be moved as possible. If the reserve balance of `who` - /// is less than `amount`, then the remaining amount will be returned. - /// NOTE: This is different behavior than `reserve`. - pub fn unreserve(asset_id: &T::AssetId, who: &T::AccountId, amount: T::Balance) -> T::Balance { - let b = Self::reserved_balance(asset_id, who); - let actual = sp_std::cmp::min(b, amount); - let original_free_balance = Self::free_balance(asset_id, who); - let new_free_balance = original_free_balance + actual; - Self::set_free_balance(asset_id, who, new_free_balance); - Self::set_reserved_balance(asset_id, who, b - actual); - amount - actual - } - - /// Deduct up to `amount` from the combined balance of `who`, preferring to deduct from the - /// free balance. This function cannot fail. - /// - /// As much funds up to `amount` will be deducted as possible. If this is less than `amount` - /// then `Some(remaining)` will be returned. Full completion is given by `None`. - /// NOTE: LOW-LEVEL: This will not attempt to maintain total issuance. It is expected that - /// the caller will do this. - pub fn slash(asset_id: &T::AssetId, who: &T::AccountId, amount: T::Balance) -> Option { - let free_balance = Self::free_balance(asset_id, who); - let free_slash = sp_std::cmp::min(free_balance, amount); - let new_free_balance = free_balance - free_slash; - Self::set_free_balance(asset_id, who, new_free_balance); - if free_slash < amount { - Self::slash_reserved(asset_id, who, amount - free_slash) - } else { - None - } - } - - /// Deducts up to `amount` from reserved balance of `who`. This function cannot fail. - /// - /// As much funds up to `amount` will be deducted as possible. If the reserve balance of `who` - /// is less than `amount`, then a non-zero second item will be returned. - /// NOTE: LOW-LEVEL: This will not attempt to maintain total issuance. It is expected that - /// the caller will do this. - pub fn slash_reserved(asset_id: &T::AssetId, who: &T::AccountId, amount: T::Balance) -> Option { - let original_reserve_balance = Self::reserved_balance(asset_id, who); - let slash = sp_std::cmp::min(original_reserve_balance, amount); - let new_reserve_balance = original_reserve_balance - slash; - Self::set_reserved_balance(asset_id, who, new_reserve_balance); - if amount == slash { - None - } else { - Some(amount - slash) - } - } - - /// Move up to `amount` from reserved balance of account `who` to balance of account - /// `beneficiary`, either free or reserved depending on `status`. - /// - /// As much funds up to `amount` will be moved as possible. If this is less than `amount`, then - /// the `remaining` would be returned, else `Zero::zero()`. - /// NOTE: LOW-LEVEL: This will not attempt to maintain total issuance. It is expected that - /// the caller will do this. - pub fn repatriate_reserved( - asset_id: &T::AssetId, - who: &T::AccountId, - beneficiary: &T::AccountId, - amount: T::Balance, - status: BalanceStatus, - ) -> T::Balance { - let b = Self::reserved_balance(asset_id, who); - let slash = sp_std::cmp::min(b, amount); - - match status { - BalanceStatus::Free => { - let original_free_balance = Self::free_balance(asset_id, beneficiary); - let new_free_balance = original_free_balance + slash; - Self::set_free_balance(asset_id, beneficiary, new_free_balance); - } - BalanceStatus::Reserved => { - let original_reserved_balance = Self::reserved_balance(asset_id, beneficiary); - let new_reserved_balance = original_reserved_balance + slash; - Self::set_reserved_balance(asset_id, beneficiary, new_reserved_balance); - } - } - - let new_reserve_balance = b - slash; - Self::set_reserved_balance(asset_id, who, new_reserve_balance); - amount - slash - } - - /// Check permission to perform burn, mint or update. - /// - /// # Arguments - /// * `asset_id`: A `T::AssetId` type that contains the `asset_id`, which has the permission embedded. - /// * `who`: A `T::AccountId` type that contains the `account_id` for which to check permissions. - /// * `what`: The permission to check. - /// - pub fn check_permission(asset_id: &T::AssetId, who: &T::AccountId, what: &PermissionType) -> bool { - let permission_versions: PermissionVersions = Self::get_permission(asset_id); - let permission = permission_versions.into(); - - match (what, permission) { - ( - PermissionType::Burn, - PermissionLatest { - burn: Owner::Address(account), - .. - }, - ) => account == *who, - ( - PermissionType::Mint, - PermissionLatest { - mint: Owner::Address(account), - .. - }, - ) => account == *who, - ( - PermissionType::Update, - PermissionLatest { - update: Owner::Address(account), - .. - }, - ) => account == *who, - _ => false, - } - } - - /// Return `Ok` iff the account is able to make a withdrawal of the given amount - /// for the given reason. - /// - /// `Err(...)` with the reason why not otherwise. - pub fn ensure_can_withdraw( - asset_id: &T::AssetId, - who: &T::AccountId, - _amount: T::Balance, - reasons: WithdrawReasons, - new_balance: T::Balance, - ) -> DispatchResult { - if asset_id != &Self::staking_asset_id() { - return Ok(()); - } - - let locks = Self::locks(who); - if locks.is_empty() { - return Ok(()); - } - if Self::locks(who) - .into_iter().all(|l| new_balance >= l.amount || !l.reasons.intersects(reasons)) - { - Ok(()) - } else { - Err(Error::::LiquidityRestrictions)? - } - } - - // PRIVATE MUTABLES - - /// NOTE: LOW-LEVEL: This will not attempt to maintain total issuance. It is expected that - /// the caller will do this. - fn set_reserved_balance(asset_id: &T::AssetId, who: &T::AccountId, balance: T::Balance) { - >::insert(asset_id, who, &balance); - } - - /// NOTE: LOW-LEVEL: This will not attempt to maintain total issuance. It is expected that - /// the caller will do this. - fn set_free_balance(asset_id: &T::AssetId, who: &T::AccountId, balance: T::Balance) { - >::insert(asset_id, who, &balance); - } - - fn set_lock( - id: LockIdentifier, - who: &T::AccountId, - amount: T::Balance, - reasons: WithdrawReasons, - ) { - let mut new_lock = Some(BalanceLock { - id, - amount, - reasons, - }); - let mut locks = >::locks(who) - .into_iter() - .filter_map(|l| { - if l.id == id { - new_lock.take() - } else { - Some(l) - } - }) - .collect::>(); - if let Some(lock) = new_lock { - locks.push(lock) - } - >::insert(who, locks); - } - - fn extend_lock( - id: LockIdentifier, - who: &T::AccountId, - amount: T::Balance, - reasons: WithdrawReasons, - ) { - let mut new_lock = Some(BalanceLock { - id, - amount, - reasons, - }); - let mut locks = >::locks(who) - .into_iter() - .filter_map(|l| { - if l.id == id { - new_lock.take().map(|nl| BalanceLock { - id: l.id, - amount: l.amount.max(nl.amount), - reasons: l.reasons | nl.reasons, - }) - } else { - Some(l) - } - }) - .collect::>(); - if let Some(lock) = new_lock { - locks.push(lock) - } - >::insert(who, locks); - } - - fn remove_lock(id: LockIdentifier, who: &T::AccountId) { - let mut locks = >::locks(who); - locks.retain(|l| l.id != id); - >::insert(who, locks); - } -} - -pub trait AssetIdProvider { - type AssetId; - fn asset_id() -> Self::AssetId; -} - -// wrapping these imbalances in a private module is necessary to ensure absolute privacy -// of the inner member. -mod imbalances { - use super::{ - result, AssetIdProvider, Imbalance, Saturating, StorageMap, Subtrait, Zero, TryDrop - }; - use sp_std::mem; - - /// Opaque, move-only struct with private fields that serves as a token denoting that - /// funds have been created without any equal and opposite accounting. - #[must_use] - pub struct PositiveImbalance>( - T::Balance, - sp_std::marker::PhantomData, - ); - impl PositiveImbalance - where - T: Subtrait, - U: AssetIdProvider, - { - pub fn new(amount: T::Balance) -> Self { - PositiveImbalance(amount, Default::default()) - } - } - - /// Opaque, move-only struct with private fields that serves as a token denoting that - /// funds have been destroyed without any equal and opposite accounting. - #[must_use] - pub struct NegativeImbalance>( - T::Balance, - sp_std::marker::PhantomData, - ); - impl NegativeImbalance - where - T: Subtrait, - U: AssetIdProvider, - { - pub fn new(amount: T::Balance) -> Self { - NegativeImbalance(amount, Default::default()) - } - } - - impl TryDrop for PositiveImbalance - where - T: Subtrait, - U: AssetIdProvider, - { - fn try_drop(self) -> result::Result<(), Self> { - self.drop_zero() - } - } - - impl Imbalance for PositiveImbalance - where - T: Subtrait, - U: AssetIdProvider, - { - type Opposite = NegativeImbalance; - - fn zero() -> Self { - Self::new(Zero::zero()) - } - fn drop_zero(self) -> result::Result<(), Self> { - if self.0.is_zero() { - Ok(()) - } else { - Err(self) - } - } - fn split(self, amount: T::Balance) -> (Self, Self) { - let first = self.0.min(amount); - let second = self.0 - first; - - mem::forget(self); - (Self::new(first), Self::new(second)) - } - fn merge(mut self, other: Self) -> Self { - self.0 = self.0.saturating_add(other.0); - mem::forget(other); - - self - } - fn subsume(&mut self, other: Self) { - self.0 = self.0.saturating_add(other.0); - mem::forget(other); - } - fn offset(self, other: Self::Opposite) -> result::Result { - let (a, b) = (self.0, other.0); - mem::forget((self, other)); - - if a >= b { - Ok(Self::new(a - b)) - } else { - Err(NegativeImbalance::new(b - a)) - } - } - fn peek(&self) -> T::Balance { - self.0.clone() - } - } - - impl TryDrop for NegativeImbalance - where - T: Subtrait, - U: AssetIdProvider, - { - fn try_drop(self) -> result::Result<(), Self> { - self.drop_zero() - } - } - - impl Imbalance for NegativeImbalance - where - T: Subtrait, - U: AssetIdProvider, - { - type Opposite = PositiveImbalance; - - fn zero() -> Self { - Self::new(Zero::zero()) - } - fn drop_zero(self) -> result::Result<(), Self> { - if self.0.is_zero() { - Ok(()) - } else { - Err(self) - } - } - fn split(self, amount: T::Balance) -> (Self, Self) { - let first = self.0.min(amount); - let second = self.0 - first; - - mem::forget(self); - (Self::new(first), Self::new(second)) - } - fn merge(mut self, other: Self) -> Self { - self.0 = self.0.saturating_add(other.0); - mem::forget(other); - - self - } - fn subsume(&mut self, other: Self) { - self.0 = self.0.saturating_add(other.0); - mem::forget(other); - } - fn offset(self, other: Self::Opposite) -> result::Result { - let (a, b) = (self.0, other.0); - mem::forget((self, other)); - - if a >= b { - Ok(Self::new(a - b)) - } else { - Err(PositiveImbalance::new(b - a)) - } - } - fn peek(&self) -> T::Balance { - self.0.clone() - } - } - - impl Drop for PositiveImbalance - where - T: Subtrait, - U: AssetIdProvider, - { - /// Basic drop handler will just square up the total issuance. - fn drop(&mut self) { - >>::mutate(&U::asset_id(), |v| *v = v.saturating_add(self.0)); - } - } - - impl Drop for NegativeImbalance - where - T: Subtrait, - U: AssetIdProvider, - { - /// Basic drop handler will just square up the total issuance. - fn drop(&mut self) { - >>::mutate(&U::asset_id(), |v| *v = v.saturating_sub(self.0)); - } - } -} - -// TODO: #2052 -// Somewhat ugly hack in order to gain access to module's `increase_total_issuance_by` -// using only the Subtrait (which defines only the types that are not dependent -// on Positive/NegativeImbalance). Subtrait must be used otherwise we end up with a -// circular dependency with Trait having some types be dependent on PositiveImbalance -// and PositiveImbalance itself depending back on Trait for its Drop impl (and thus -// its type declaration). -// This works as long as `increase_total_issuance_by` doesn't use the Imbalance -// types (basically for charging fees). -// This should eventually be refactored so that the two type items that do -// depend on the Imbalance type (TransactionPayment, DustRemoval) -// are placed in their own pallet. -struct ElevatedTrait(T); -impl Clone for ElevatedTrait { - fn clone(&self) -> Self { - unimplemented!() - } -} -impl PartialEq for ElevatedTrait { - fn eq(&self, _: &Self) -> bool { - unimplemented!() - } -} -impl Eq for ElevatedTrait {} -impl frame_system::Trait for ElevatedTrait { - type BaseCallFilter = T::BaseCallFilter; - type Origin = T::Origin; - type Call = T::Call; - type Index = T::Index; - type BlockNumber = T::BlockNumber; - type Hash = T::Hash; - type Hashing = T::Hashing; - type AccountId = T::AccountId; - type Lookup = T::Lookup; - type Header = T::Header; - type Event = (); - type BlockHashCount = T::BlockHashCount; - type MaximumBlockWeight = T::MaximumBlockWeight; - type DbWeight = (); - type BlockExecutionWeight = (); - type ExtrinsicBaseWeight = (); - type MaximumExtrinsicWeight = T::MaximumBlockWeight; - type MaximumBlockLength = T::MaximumBlockLength; - type AvailableBlockRatio = T::AvailableBlockRatio; - type Version = T::Version; - type PalletInfo = (); - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); -} -impl Trait for ElevatedTrait { - type Balance = T::Balance; - type AssetId = T::AssetId; - type Event = (); -} - -#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)] -pub struct AssetCurrency(sp_std::marker::PhantomData, sp_std::marker::PhantomData); - -impl Currency for AssetCurrency -where - T: Trait, - U: AssetIdProvider, -{ - type Balance = T::Balance; - type PositiveImbalance = PositiveImbalance; - type NegativeImbalance = NegativeImbalance; - - fn total_balance(who: &T::AccountId) -> Self::Balance { - Self::free_balance(&who) + Self::reserved_balance(&who) - } - - fn free_balance(who: &T::AccountId) -> Self::Balance { - >::free_balance(&U::asset_id(), &who) - } - - /// Returns the total staking asset issuance - fn total_issuance() -> Self::Balance { - >::total_issuance(U::asset_id()) - } - - fn minimum_balance() -> Self::Balance { - Zero::zero() - } - - fn transfer( - transactor: &T::AccountId, - dest: &T::AccountId, - value: Self::Balance, - _: ExistenceRequirement, // no existential deposit policy for generic asset - ) -> DispatchResult { - >::make_transfer(&U::asset_id(), transactor, dest, value) - } - - fn ensure_can_withdraw( - who: &T::AccountId, - amount: Self::Balance, - reasons: WithdrawReasons, - new_balance: Self::Balance, - ) -> DispatchResult { - >::ensure_can_withdraw(&U::asset_id(), who, amount, reasons, new_balance) - } - - fn withdraw( - who: &T::AccountId, - value: Self::Balance, - reasons: WithdrawReasons, - _: ExistenceRequirement, // no existential deposit policy for generic asset - ) -> result::Result { - let new_balance = Self::free_balance(who) - .checked_sub(&value) - .ok_or(Error::::InsufficientBalance)?; - Self::ensure_can_withdraw(who, value, reasons, new_balance)?; - >::set_free_balance(&U::asset_id(), who, new_balance); - Ok(NegativeImbalance::new(value)) - } - - fn deposit_into_existing( - who: &T::AccountId, - value: Self::Balance, - ) -> result::Result { - // No existential deposit rule and creation fee in GA. `deposit_into_existing` is same with `deposit_creating`. - Ok(Self::deposit_creating(who, value)) - } - - fn deposit_creating(who: &T::AccountId, value: Self::Balance) -> Self::PositiveImbalance { - let imbalance = Self::make_free_balance_be(who, Self::free_balance(who) + value); - if let SignedImbalance::Positive(p) = imbalance { - p - } else { - // Impossible, but be defensive. - Self::PositiveImbalance::zero() - } - } - - fn make_free_balance_be( - who: &T::AccountId, - balance: Self::Balance, - ) -> SignedImbalance { - let original = >::free_balance(&U::asset_id(), who); - let imbalance = if original <= balance { - SignedImbalance::Positive(PositiveImbalance::new(balance - original)) - } else { - SignedImbalance::Negative(NegativeImbalance::new(original - balance)) - }; - >::set_free_balance(&U::asset_id(), who, balance); - imbalance - } - - fn can_slash(who: &T::AccountId, value: Self::Balance) -> bool { - >::free_balance(&U::asset_id(), &who) >= value - } - - fn slash(who: &T::AccountId, value: Self::Balance) -> (Self::NegativeImbalance, Self::Balance) { - let remaining = >::slash(&U::asset_id(), who, value); - if let Some(r) = remaining { - (NegativeImbalance::new(value - r), r) - } else { - (NegativeImbalance::new(value), Zero::zero()) - } - } - - fn burn(mut amount: Self::Balance) -> Self::PositiveImbalance { - >::mutate(&U::asset_id(), |issued| - issued.checked_sub(&amount).unwrap_or_else(|| { - amount = *issued; - Zero::zero() - }) - ); - PositiveImbalance::new(amount) - } - - fn issue(mut amount: Self::Balance) -> Self::NegativeImbalance { - >::mutate(&U::asset_id(), |issued| - *issued = issued.checked_add(&amount).unwrap_or_else(|| { - amount = Self::Balance::max_value() - *issued; - Self::Balance::max_value() - }) - ); - NegativeImbalance::new(amount) - } -} - -impl ReservableCurrency for AssetCurrency -where - T: Trait, - U: AssetIdProvider, -{ - fn can_reserve(who: &T::AccountId, value: Self::Balance) -> bool { - Self::free_balance(who) - .checked_sub(&value) - .map_or(false, |new_balance| - >::ensure_can_withdraw( - &U::asset_id(), who, value, WithdrawReason::Reserve.into(), new_balance - ).is_ok() - ) - } - - fn reserved_balance(who: &T::AccountId) -> Self::Balance { - >::reserved_balance(&U::asset_id(), &who) - } - - fn reserve(who: &T::AccountId, value: Self::Balance) -> DispatchResult { - >::reserve(&U::asset_id(), who, value) - } - - fn unreserve(who: &T::AccountId, value: Self::Balance) -> Self::Balance { - >::unreserve(&U::asset_id(), who, value) - } - - fn slash_reserved(who: &T::AccountId, value: Self::Balance) -> (Self::NegativeImbalance, Self::Balance) { - let b = Self::reserved_balance(&who.clone()); - let slash = cmp::min(b, value); - - >::set_reserved_balance(&U::asset_id(), who, b - slash); - (NegativeImbalance::new(slash), value - slash) - } - - fn repatriate_reserved( - slashed: &T::AccountId, - beneficiary: &T::AccountId, - value: Self::Balance, - status: BalanceStatus, - ) -> result::Result { - Ok(>::repatriate_reserved(&U::asset_id(), slashed, beneficiary, value, status)) - } -} - -pub struct StakingAssetIdProvider(sp_std::marker::PhantomData); - -impl AssetIdProvider for StakingAssetIdProvider { - type AssetId = T::AssetId; - fn asset_id() -> Self::AssetId { - >::staking_asset_id() - } -} - -pub struct SpendingAssetIdProvider(sp_std::marker::PhantomData); - -impl AssetIdProvider for SpendingAssetIdProvider { - type AssetId = T::AssetId; - fn asset_id() -> Self::AssetId { - >::spending_asset_id() - } -} - -impl LockableCurrency for AssetCurrency> -where - T: Trait, - T::Balance: MaybeSerializeDeserialize + Debug, -{ - type Moment = T::BlockNumber; - - type MaxLocks = (); - - fn set_lock( - id: LockIdentifier, - who: &T::AccountId, - amount: T::Balance, - reasons: WithdrawReasons, - ) { - >::set_lock(id, who, amount, reasons) - } - - fn extend_lock( - id: LockIdentifier, - who: &T::AccountId, - amount: T::Balance, - reasons: WithdrawReasons, - ) { - >::extend_lock(id, who, amount, reasons) - } - - fn remove_lock(id: LockIdentifier, who: &T::AccountId) { - >::remove_lock(id, who) - } -} - -pub type StakingAssetCurrency = AssetCurrency>; -pub type SpendingAssetCurrency = AssetCurrency>; diff --git a/frame/generic-asset/src/mock.rs b/frame/generic-asset/src/mock.rs deleted file mode 100644 index 7daf959a4b88c..0000000000000 --- a/frame/generic-asset/src/mock.rs +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright 2019-2020 -// by Centrality Investments Ltd. -// and Parity Technologies (UK) Ltd. -// This file is part of Substrate. - -// Substrate 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. - -// Substrate 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 Substrate. If not, see . - -//! Mocks for the module. - -#![cfg(test)] - -use sp_runtime::{ - Perbill, - testing::Header, - traits::{BlakeTwo256, IdentityLookup}, -}; -use sp_core::H256; -use frame_support::{parameter_types, impl_outer_event, impl_outer_origin, weights::Weight}; - -use super::*; - -impl_outer_origin! { - pub enum Origin for Test where system = frame_system {} -} - -#[derive(Clone, Eq, PartialEq)] -pub struct Test; -parameter_types! { - pub const BlockHashCount: u64 = 250; - pub const MaximumBlockWeight: Weight = 1024; - pub const MaximumBlockLength: u32 = 2 * 1024; - pub const AvailableBlockRatio: Perbill = Perbill::one(); -} -impl frame_system::Trait for Test { - type BaseCallFilter = (); - type Origin = Origin; - type Index = u64; - type BlockNumber = u64; - type Call = (); - type Hash = H256; - type Hashing = BlakeTwo256; - type AccountId = u64; - type Lookup = IdentityLookup; - type Header = Header; - type Event = TestEvent; - type MaximumBlockWeight = MaximumBlockWeight; - type DbWeight = (); - type BlockExecutionWeight = (); - type ExtrinsicBaseWeight = (); - type MaximumExtrinsicWeight = MaximumBlockWeight; - type MaximumBlockLength = MaximumBlockLength; - type AvailableBlockRatio = AvailableBlockRatio; - type BlockHashCount = BlockHashCount; - type Version = (); - type PalletInfo = (); - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); -} - -impl Trait for Test { - type Balance = u64; - type AssetId = u32; - type Event = TestEvent; -} - -mod generic_asset { - pub use crate::Event; -} - -use frame_system as system; -impl_outer_event! { - pub enum TestEvent for Test { - system, - generic_asset, - } -} - -pub type GenericAsset = Module; - -pub type System = frame_system::Module; - -pub struct ExtBuilder { - asset_id: u32, - next_asset_id: u32, - accounts: Vec, - initial_balance: u64, -} - -// Returns default values for genesis config -impl Default for ExtBuilder { - fn default() -> Self { - Self { - asset_id: 0, - next_asset_id: 1000, - accounts: vec![0], - initial_balance: 0, - } - } -} - -impl ExtBuilder { - // Sets free balance to genesis config - pub fn free_balance(mut self, free_balance: (u32, u64, u64)) -> Self { - self.asset_id = free_balance.0; - self.accounts = vec![free_balance.1]; - self.initial_balance = free_balance.2; - self - } - - pub fn next_asset_id(mut self, asset_id: u32) -> Self { - self.next_asset_id = asset_id; - self - } - - // builds genesis config - pub fn build(self) -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); - - GenesisConfig:: { - assets: vec![self.asset_id], - endowed_accounts: self.accounts, - initial_balance: self.initial_balance, - next_asset_id: self.next_asset_id, - staking_asset_id: 16000, - spending_asset_id: 16001, - }.assimilate_storage(&mut t).unwrap(); - - let mut ext = sp_io::TestExternalities::new(t); - ext.execute_with(|| System::set_block_number(1)); - ext - } -} - -pub fn new_test_ext() -> sp_io::TestExternalities { - frame_system::GenesisConfig::default() - .build_storage::() - .unwrap() - .into() -} From fe7a5f92f2941eea6ef829b752d4a99784a56130 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Tue, 22 Sep 2020 10:10:28 +0200 Subject: [PATCH 06/16] Some work --- frame/support/src/dispatch.rs | 14 +++++++++++--- frame/support/src/traits.rs | 17 +++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index 5446b4a59bd66..6b60eab2b546a 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -29,7 +29,9 @@ pub use crate::weights::{ PaysFee, PostDispatchInfo, WithPostDispatchInfo, }; pub use sp_runtime::{traits::Dispatchable, DispatchError}; -pub use crate::traits::{CallMetadata, GetCallMetadata, GetCallName, UnfilteredDispatchable}; +pub use crate::traits::{ + CallMetadata, GetCallMetadata, GetCallName, UnfilteredDispatchable, GetPalletVersion, +}; /// The return typ of a `Dispatchable` in frame. When returned explicitly from /// a dispatchable function it allows overriding the default `PostDispatchInfo` @@ -1320,7 +1322,9 @@ macro_rules! decl_module { { fn on_runtime_upgrade() -> $return { $crate::sp_tracing::enter_span!("on_runtime_upgrade"); - { $( $impl )* } + let result = { $( $impl )* }; + + result } } }; @@ -1332,7 +1336,11 @@ macro_rules! decl_module { impl<$trait_instance: $trait_name$(, $instance: $instantiable)?> $crate::traits::OnRuntimeUpgrade for $module<$trait_instance$(, $instance)?> where $( $other_where_bounds )* - {} + { + fn on_runtime_upgrade() -> $crate::dispatch::Weight { + 0 + } + } }; (@impl_integrity_test diff --git a/frame/support/src/traits.rs b/frame/support/src/traits.rs index 75fd1a7e2ea35..ffc6ef5b936dc 100644 --- a/frame/support/src/traits.rs +++ b/frame/support/src/traits.rs @@ -1681,6 +1681,23 @@ pub struct PalletVersion { pub patch: u8, } +/// A trait t +pub trait GetPalletVersion { + /// Returns the current version of the pallet. + fn current_version() -> PalletVersion; + + /// Returns the version of the pallet that is stored in storage. + /// + /// Most of the time this will return the exact same version as + /// [`GetPalletVersion::current_version`]. Only when being in + /// a state after a runtime upgrade happened and the pallet did + /// not yet updated its version in storage, this will return a + /// different(the previous, seen from the time of calling) version. + /// + /// See [`PalletVersion`] for more information. + fn storage_version() -> PalletVersion; +} + #[cfg(test)] mod tests { use super::*; From 5c0343da011de4f86f901b2b174c4e78a625aa74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Thu, 24 Sep 2020 11:30:56 +0200 Subject: [PATCH 07/16] Make everything compile --- frame/support/src/dispatch.rs | 57 ++++++++++++++-- frame/support/src/event.rs | 66 ++++++++++--------- frame/support/src/lib.rs | 8 ++- frame/support/src/metadata.rs | 23 +++---- .../src/storage/generator/double_map.rs | 5 +- frame/support/src/storage/generator/map.rs | 5 +- frame/support/src/storage/generator/mod.rs | 9 ++- frame/support/src/traits.rs | 42 +++++++++++- frame/support/src/weights.rs | 6 +- frame/support/test/src/lib.rs | 8 ++- frame/support/test/tests/decl_storage.rs | 54 +++++++-------- .../tests/decl_storage_ui/config_duplicate.rs | 7 +- .../decl_storage_ui/config_duplicate.stderr | 4 +- .../decl_storage_ui/config_get_duplicate.rs | 7 +- .../config_get_duplicate.stderr | 4 +- .../tests/decl_storage_ui/get_duplicate.rs | 7 +- .../decl_storage_ui/get_duplicate.stderr | 4 +- frame/support/test/tests/final_keys.rs | 15 ++--- frame/support/test/tests/genesisconfig.rs | 12 ++-- .../tests/reserved_keyword/on_initialize.rs | 7 +- .../reserved_keyword/on_initialize.stderr | 20 +++--- .../support/test/tests/storage_transaction.rs | 18 ++--- 22 files changed, 233 insertions(+), 155 deletions(-) diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index 880d8eb14f2f5..f95b93b795e97 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -232,11 +232,11 @@ impl Parameter for T where T: Codec + EncodeLike + Clone + Eq + fmt::Debug {} /// # #[macro_use] /// # extern crate frame_support; /// # use frame_support::dispatch; -/// # use frame_system::{self as system, ensure_signed}; +/// # use frame_system::ensure_signed; /// # pub struct DefaultInstance; -/// # pub trait Instance {} +/// # pub trait Instance: 'static {} /// # impl Instance for DefaultInstance {} -/// pub trait Trait: system::Trait {} +/// pub trait Trait: frame_system::Trait {} /// /// decl_module! { /// pub struct Module, I: Instance = DefaultInstance> for enum Call where origin: T::Origin { @@ -1312,6 +1312,7 @@ macro_rules! decl_module { }; (@impl_on_runtime_upgrade + { $system:ident } $module:ident<$trait_instance:ident: $trait_name:ident$(, $instance:ident: $instantiable:path)?>; { $( $other_where_bounds:tt )* } fn on_runtime_upgrade() -> $return:ty { $( $impl:tt )* } @@ -1324,12 +1325,19 @@ macro_rules! decl_module { $crate::sp_tracing::enter_span!($crate::sp_tracing::trace_span!("on_runtime_upgrade")); let result = { $( $impl )* }; - result + let key = $crate::traits::PalletVersion::storage_key::< + <$trait_instance as $system::Trait>::PalletInfo, Self + >().expect("Every active pallet has a name in the runtime; qed"); + let version = $crate::crate_to_pallet_version!(); + $crate::storage::unhashed::put(&key, &$crate::dispatch::Encode::encode(&version)); + + result } } }; (@impl_on_runtime_upgrade + { $system:ident } $module:ident<$trait_instance:ident: $trait_name:ident$(, $instance:ident: $instantiable:path)?>; { $( $other_where_bounds:tt )* } ) => { @@ -1339,6 +1347,13 @@ macro_rules! decl_module { { fn on_runtime_upgrade() -> $crate::dispatch::Weight { $crate::sp_tracing::enter_span!($crate::sp_tracing::trace_span!("on_runtime_upgrade")); + + let key = $crate::traits::PalletVersion::storage_key::< + <$trait_instance as $system::Trait>::PalletInfo, Self + >().expect("Every active pallet has a name in the runtime; qed"); + let version = $crate::crate_to_pallet_version!(); + $crate::storage::unhashed::put(&key, &$crate::dispatch::Encode::encode(&version)); + 0 } } @@ -1661,6 +1676,7 @@ macro_rules! decl_module { $crate::decl_module! { @impl_on_runtime_upgrade + { $system } $mod_type<$trait_instance: $trait_name $(, $instance: $instantiable)?>; { $( $other_where_bounds )* } $( $on_runtime_upgrade )* @@ -1796,6 +1812,29 @@ macro_rules! decl_module { } } + // Implement `GetPalletVersion` for `Module` + impl<$trait_instance: $trait_name $(, $instance: $instantiable)?> $crate::traits::GetPalletVersion + for $mod_type<$trait_instance $(, $instance)?> where $( $other_where_bounds )* + { + fn current_version() -> $crate::traits::PalletVersion { + $crate::crate_to_pallet_version!() + } + + fn storage_version() -> $crate::traits::PalletVersion { + let key = $crate::traits::PalletVersion::storage_key::< + <$trait_instance as $system::Trait>::PalletInfo, Self + >().expect("Every active pallet has a name in the runtime; qed"); + + let value: Option<$crate::traits::PalletVersion> = + $crate::storage::unhashed::get(&key); + + match value { + Some(version) => version, + None => $crate::crate_to_pallet_version!(), + } + } + } + // manual implementation of clone/eq/partialeq because using derive erroneously requires // clone/eq/partialeq from T. impl<$trait_instance: $trait_name $(, $instance: $instantiable)?> $crate::dispatch::Clone @@ -1811,6 +1850,7 @@ macro_rules! decl_module { } } } + impl<$trait_instance: $trait_name $(, $instance: $instantiable)?> $crate::dispatch::PartialEq for $call_type<$trait_instance $(, $instance)?> where $( $other_where_bounds )* { @@ -1833,6 +1873,7 @@ macro_rules! decl_module { } } } + impl<$trait_instance: $trait_name $(, $instance: $instantiable)?> $crate::dispatch::Eq for $call_type<$trait_instance $(, $instance)?> where $( $other_where_bounds )* {} @@ -2373,12 +2414,13 @@ mod tests { pub mod system { use codec::{Encode, Decode}; - pub trait Trait { + pub trait Trait: 'static { type AccountId; type Call; type BaseCallFilter; type Origin: crate::traits::OriginTrait; type BlockNumber: Into; + type PalletInfo: crate::traits::PalletInfo; } #[derive(Clone, PartialEq, Eq, Debug, Encode, Decode)] @@ -2522,6 +2564,7 @@ mod tests { type Call = OuterCall; type BaseCallFilter = (); type BlockNumber = u32; + type PalletInfo = (); } #[test] @@ -2577,7 +2620,9 @@ mod tests { #[test] fn on_runtime_upgrade_should_work() { - assert_eq!( as OnRuntimeUpgrade>::on_runtime_upgrade(), 10); + sp_io::TestExternalities::default().execute_with(|| + assert_eq!( as OnRuntimeUpgrade>::on_runtime_upgrade(), 10) + ); } #[test] diff --git a/frame/support/src/event.rs b/frame/support/src/event.rs index 1184b379f4446..ec6073aeff52f 100644 --- a/frame/support/src/event.rs +++ b/frame/support/src/event.rs @@ -543,13 +543,14 @@ mod tests { use codec::{Encode, Decode}; mod system { - pub trait Trait { + pub trait Trait: 'static { type Origin; type BlockNumber; + type PalletInfo: crate::traits::PalletInfo; } decl_module! { - pub struct Module for enum Call where origin: T::Origin {} + pub struct Module for enum Call where origin: T::Origin, system=self {} } decl_event!( @@ -560,13 +561,14 @@ mod tests { } mod system_renamed { - pub trait Trait { + pub trait Trait: 'static { type Origin; type BlockNumber; + type PalletInfo: crate::traits::PalletInfo; } decl_module! { - pub struct Module for enum Call where origin: T::Origin {} + pub struct Module for enum Call where origin: T::Origin, system=self {} } decl_event!( @@ -577,19 +579,19 @@ mod tests { } mod event_module { - pub trait Trait { - type Origin; + use super::system; + + pub trait Trait: system::Trait { type Balance; - type BlockNumber; } decl_module! { - pub struct Module for enum Call where origin: T::Origin {} + pub struct Module for enum Call where origin: T::Origin, system=system {} } decl_event!( /// Event without renaming the generic parameter `Balance` and `Origin`. - pub enum Event where ::Balance, ::Origin + pub enum Event where ::Balance, ::Origin { /// Hi, I am a comment. TestEvent(Balance, Origin), @@ -600,21 +602,21 @@ mod tests { } mod event_module2 { - pub trait Trait { - type Origin; + use super::system; + + pub trait Trait: system::Trait { type Balance; - type BlockNumber; } decl_module! { - pub struct Module for enum Call where origin: T::Origin {} + pub struct Module for enum Call where origin: T::Origin, system=system {} } decl_event!( /// Event with renamed generic parameter pub enum Event where BalanceRenamed = ::Balance, - OriginRenamed = ::Origin + OriginRenamed = ::Origin { TestEvent(BalanceRenamed), TestOrigin(OriginRenamed), @@ -631,21 +633,21 @@ mod tests { } mod event_module4 { - pub trait Trait { - type Origin; + use super::system; + + pub trait Trait: system::Trait { type Balance; - type BlockNumber; } decl_module! { - pub struct Module for enum Call where origin: T::Origin {} + pub struct Module for enum Call where origin: T::Origin, system=system {} } decl_event!( /// Event finish formatting on an unnamed one with trailing comma pub enum Event where ::Balance, - ::Origin, + ::Origin, { TestEvent(Balance, Origin), } @@ -653,21 +655,21 @@ mod tests { } mod event_module5 { - pub trait Trait { - type Origin; + use super::system; + + pub trait Trait: system::Trait { type Balance; - type BlockNumber; } decl_module! { - pub struct Module for enum Call where origin: T::Origin {} + pub struct Module for enum Call where origin: T::Origin, system=system {} } decl_event!( /// Event finish formatting on an named one with trailing comma pub enum Event where BalanceRenamed = ::Balance, - OriginRenamed = ::Origin, + OriginRenamed = ::Origin, { TestEvent(BalanceRenamed, OriginRenamed), TrailingCommaInArgs( @@ -703,37 +705,37 @@ mod tests { } impl event_module::Trait for TestRuntime { - type Origin = u32; type Balance = u32; - type BlockNumber = u32; } impl event_module2::Trait for TestRuntime { - type Origin = u32; type Balance = u32; - type BlockNumber = u32; } impl system::Trait for TestRuntime { type Origin = u32; type BlockNumber = u32; + type PalletInfo = (); } impl event_module::Trait for TestRuntime2 { - type Origin = u32; type Balance = u32; - type BlockNumber = u32; } impl event_module2::Trait for TestRuntime2 { - type Origin = u32; type Balance = u32; - type BlockNumber = u32; } impl system_renamed::Trait for TestRuntime2 { type Origin = u32; type BlockNumber = u32; + type PalletInfo = (); + } + + impl system::Trait for TestRuntime2 { + type Origin = u32; + type BlockNumber = u32; + type PalletInfo = (); } const EXPECTED_METADATA: OuterEventMetadata = OuterEventMetadata { diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 314ce74a25793..d3bff0f100826 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -279,7 +279,7 @@ pub use frame_support_procedural::{decl_storage, construct_runtime, transactiona /// # Example /// /// ``` -/// #use frame_support::{traits::PalletVersion, crate_to_pallet_version}; +/// # use frame_support::{traits::PalletVersion, crate_to_pallet_version}; /// const Version: PalletVersion = crate_to_pallet_version!(); /// ``` pub use frame_support_procedural::crate_to_pallet_version; @@ -394,9 +394,10 @@ mod tests { use sp_std::{marker::PhantomData, result}; use sp_io::TestExternalities; - pub trait Trait { + pub trait Trait: 'static { type BlockNumber: Codec + EncodeLike + Default; type Origin; + type PalletInfo: crate::traits::PalletInfo; } mod module { @@ -405,7 +406,7 @@ mod tests { use super::Trait; decl_module! { - pub struct Module for enum Call where origin: T::Origin {} + pub struct Module for enum Call where origin: T::Origin, system=self {} } } use self::module::Module; @@ -436,6 +437,7 @@ mod tests { impl Trait for Test { type BlockNumber = u32; type Origin = u32; + type PalletInfo = (); } fn new_test_ext() -> TestExternalities { diff --git a/frame/support/src/metadata.rs b/frame/support/src/metadata.rs index 8d3b5fb527af7..83ace13f4bb7c 100644 --- a/frame/support/src/metadata.rs +++ b/frame/support/src/metadata.rs @@ -27,12 +27,13 @@ pub use frame_metadata::{ /// Example: /// ``` ///# mod module0 { -///# pub trait Trait { +///# pub trait Trait: 'static { ///# type Origin; ///# type BlockNumber; +///# type PalletInfo: frame_support::traits::PalletInfo; ///# } ///# frame_support::decl_module! { -///# pub struct Module for enum Call where origin: T::Origin {} +///# pub struct Module for enum Call where origin: T::Origin, system=self {} ///# } ///# ///# frame_support::decl_storage! { @@ -44,6 +45,7 @@ pub use frame_metadata::{ ///# impl module0::Trait for Runtime { ///# type Origin = u32; ///# type BlockNumber = u32; +///# type PalletInfo = (); ///# } ///# ///# type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic<(), (), (), ()>; @@ -302,7 +304,7 @@ mod tests { } decl_module! { - pub struct Module for enum Call where origin: T::Origin { + pub struct Module for enum Call where origin: T::Origin, system=self { /// Hi, I am a comment. const BlockNumber: T::BlockNumber = 100.into(); const GetType: T::AccountId = T::SomeValue::get().into(); @@ -337,8 +339,9 @@ mod tests { mod event_module { use crate::dispatch::DispatchResult; + use super::system; - pub trait Trait: super::system::Trait { + pub trait Trait: system::Trait { type Balance; } @@ -351,7 +354,7 @@ mod tests { ); decl_module! { - pub struct Module for enum Call where origin: T::Origin { + pub struct Module for enum Call where origin: T::Origin, system=system { type Error = Error; #[weight = 0] @@ -371,10 +374,10 @@ mod tests { } mod event_module2 { - pub trait Trait { - type Origin; + use super::system; + + pub trait Trait: system::Trait { type Balance; - type BlockNumber; } decl_event!( @@ -385,7 +388,7 @@ mod tests { ); decl_module! { - pub struct Module for enum Call where origin: T::Origin {} + pub struct Module for enum Call where origin: T::Origin, system=system {} } crate::decl_storage! { @@ -428,9 +431,7 @@ mod tests { } impl event_module2::Trait for TestRuntime { - type Origin = Origin; type Balance = u32; - type BlockNumber = u32; } crate::parameter_types! { diff --git a/frame/support/src/storage/generator/double_map.rs b/frame/support/src/storage/generator/double_map.rs index 9454ab401da28..f5495092ec63d 100644 --- a/frame/support/src/storage/generator/double_map.rs +++ b/frame/support/src/storage/generator/double_map.rs @@ -425,13 +425,14 @@ mod test_iterators { storage::{generator::StorageDoubleMap, IterableStorageDoubleMap, unhashed}, }; - pub trait Trait { + pub trait Trait: 'static { type Origin; type BlockNumber; + type PalletInfo: crate::traits::PalletInfo; } crate::decl_module! { - pub struct Module for enum Call where origin: T::Origin {} + pub struct Module for enum Call where origin: T::Origin, system=self {} } #[derive(PartialEq, Eq, Clone, Encode, Decode)] diff --git a/frame/support/src/storage/generator/map.rs b/frame/support/src/storage/generator/map.rs index 1c13de52e1640..6ea185cebae2c 100644 --- a/frame/support/src/storage/generator/map.rs +++ b/frame/support/src/storage/generator/map.rs @@ -325,13 +325,14 @@ mod test_iterators { storage::{generator::StorageMap, IterableStorageMap, unhashed}, }; - pub trait Trait { + pub trait Trait: 'static { type Origin; type BlockNumber; + type PalletInfo: crate::traits::PalletInfo; } crate::decl_module! { - pub struct Module for enum Call where origin: T::Origin {} + pub struct Module for enum Call where origin: T::Origin, system=self {} } #[derive(PartialEq, Eq, Clone, Encode, Decode)] diff --git a/frame/support/src/storage/generator/mod.rs b/frame/support/src/storage/generator/mod.rs index 7df7dfd317399..b36c8b7d47b21 100644 --- a/frame/support/src/storage/generator/mod.rs +++ b/frame/support/src/storage/generator/mod.rs @@ -40,19 +40,22 @@ mod tests { use crate::storage::{unhashed, generator::StorageValue, IterableStorageMap}; use crate::{assert_noop, assert_ok}; - struct Runtime {} - pub trait Trait { + struct Runtime; + + pub trait Trait: 'static { type Origin; type BlockNumber; + type PalletInfo: crate::traits::PalletInfo; } impl Trait for Runtime { type Origin = u32; type BlockNumber = u32; + type PalletInfo = (); } decl_module! { - pub struct Module for enum Call where origin: T::Origin {} + pub struct Module for enum Call where origin: T::Origin, system=self {} } crate::decl_storage! { diff --git a/frame/support/src/traits.rs b/frame/support/src/traits.rs index 0ad4a0e75e2f2..43669fb41b34a 100644 --- a/frame/support/src/traits.rs +++ b/frame/support/src/traits.rs @@ -1669,10 +1669,19 @@ impl IsType for T { /// "InstanceNMyModule". pub trait Instance: 'static { /// Unique module prefix. E.g. "InstanceNMyModule" or "MyModule" - const PREFIX: &'static str ; + const PREFIX: &'static str; } +/// The storage key postfix that is used to store the [`PalletVersion`] per pallet. +/// +/// The full storage key is build by using: +/// Twox128([`PalletInfo::name`] ++ [`PALLET_VERSION_STORAGE_POSTFIX`]) +pub const PALLET_VERSION_STORAGE_KEY_POSTFIX: &[u8] = b":__PALLET_VERSION__:"; + /// The version of a pallet. +/// +/// Each pallet version is stored in the state under a fixed key. See +/// [`PALLET_VERSION_STORAGE_KEY_POSTFIX`] for how this key is build. #[derive(RuntimeDebug, Eq, PartialEq, Encode, Decode)] pub struct PalletVersion { /// The major version of the pallet. @@ -1683,7 +1692,31 @@ pub struct PalletVersion { pub patch: u8, } -/// A trait t +impl PalletVersion { + /// Returns the storage key for a pallet version. + /// + /// See [`PALLET_VERSION_STORAGE_KEY_POSTIFX`] on how this key is build. + /// + /// Returns `None` if the given `PI` returned a `None` as name for the given + /// `Pallet`. + pub fn storage_key() -> Option<[u8; 16]> { + let pallet_name = PI::name::()?; + + let mut key = Vec::with_capacity( + pallet_name.as_bytes().len() + PALLET_VERSION_STORAGE_KEY_POSTFIX.len(), + ); + key.extend(pallet_name.as_bytes()); + key.extend(PALLET_VERSION_STORAGE_KEY_POSTFIX); + + Some(sp_io::hashing::twox_128(&key)) + } +} + +/// Provides version information about a pallet. +/// +/// This trait provides two functions for returning the version of a +/// pallet. There is a state where both functions can return distinct versions. +/// See [`GetPalletVersion::storage_version`] for more information about this. pub trait GetPalletVersion { /// Returns the current version of the pallet. fn current_version() -> PalletVersion; @@ -1697,6 +1730,11 @@ pub trait GetPalletVersion { /// different(the previous, seen from the time of calling) version. /// /// See [`PalletVersion`] for more information. + /// + /// # Note + /// + /// If there was no previous version of the pallet stored in the state, + /// this function will return [`GetPalletVersion::current_version`] fn storage_version() -> PalletVersion; } diff --git a/frame/support/src/weights.rs b/frame/support/src/weights.rs index 1d19eeef70d79..74f0773aa541f 100644 --- a/frame/support/src/weights.rs +++ b/frame/support/src/weights.rs @@ -701,11 +701,12 @@ mod tests { use crate::{decl_module, parameter_types, traits::Get}; use super::*; - pub trait Trait { + pub trait Trait: 'static { type Origin; type Balance; type BlockNumber; type DbWeight: Get; + type PalletInfo: crate::traits::PalletInfo; } pub struct TraitImpl {} @@ -722,10 +723,11 @@ mod tests { type BlockNumber = u32; type Balance = u32; type DbWeight = DbWeight; + type PalletInfo = (); } decl_module! { - pub struct Module for enum Call where origin: T::Origin { + pub struct Module for enum Call where origin: T::Origin, system=self { // no arguments, fixed weight #[weight = 1000] fn f00(_origin) { unimplemented!(); } diff --git a/frame/support/test/src/lib.rs b/frame/support/test/src/lib.rs index cf9a54ae2eb16..07a4a4206fdd7 100644 --- a/frame/support/test/src/lib.rs +++ b/frame/support/test/src/lib.rs @@ -26,11 +26,13 @@ mod pallet_version; /// The configuration trait -pub trait Trait { +pub trait Trait: 'static { /// The runtime origin type. - type Origin; + type Origin: codec::Codec + codec::EncodeLike + Default; /// The block number type. - type BlockNumber; + type BlockNumber: codec::Codec + codec::EncodeLike + Default; + /// The information about the pallet setup in the runtime. + type PalletInfo: frame_support::traits::PalletInfo; } frame_support::decl_module! { diff --git a/frame/support/test/tests/decl_storage.rs b/frame/support/test/tests/decl_storage.rs index 800ce459fed35..0ac80129700b4 100644 --- a/frame/support/test/tests/decl_storage.rs +++ b/frame/support/test/tests/decl_storage.rs @@ -22,16 +22,12 @@ mod tests { use frame_support::metadata::*; use sp_io::TestExternalities; use std::marker::PhantomData; - use codec::{Encode, Decode, EncodeLike}; frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=self {} + pub struct Module for enum Call where origin: T::Origin, system=frame_support_test {} } - pub trait Trait { - type Origin: Encode + Decode + EncodeLike + std::default::Default; - type BlockNumber; - } + pub trait Trait: frame_support_test::Trait {} frame_support::decl_storage! { trait Store for Module as TestStorage { @@ -74,7 +70,7 @@ mod tests { pub PUBGETMAPU32MYDEF get(fn pub_map_u32_getter_mydef): map hasher(blake2_128_concat) u32 => String = "pubmap".into(); - COMPLEXTYPE1: ::std::vec::Vec<::Origin>; + COMPLEXTYPE1: ::std::vec::Vec; COMPLEXTYPE2: (Vec)>>, u32); COMPLEXTYPE3: [u32; 25]; } @@ -85,11 +81,14 @@ mod tests { struct TraitImpl {} - impl Trait for TraitImpl { + impl frame_support_test::Trait for TraitImpl { type Origin = u32; type BlockNumber = u32; + type PalletInfo = (); } + impl Trait for TraitImpl {} + const EXPECTED_METADATA: StorageMetadata = StorageMetadata { prefix: DecodeDifferent::Encode("TestStorage"), entries: DecodeDifferent::Encode( @@ -353,7 +352,7 @@ mod tests { StorageEntryMetadata { name: DecodeDifferent::Encode("COMPLEXTYPE1"), modifier: StorageEntryModifier::Default, - ty: StorageEntryType::Plain(DecodeDifferent::Encode("::std::vec::Vec<::Origin>")), + ty: StorageEntryType::Plain(DecodeDifferent::Encode("::std::vec::Vec")), default: DecodeDifferent::Encode( DefaultByteGetter(&__GetByteStructCOMPLEXTYPE1(PhantomData::)) ), @@ -414,13 +413,10 @@ mod tests { #[cfg(test)] #[allow(dead_code)] mod test2 { - pub trait Trait { - type Origin; - type BlockNumber; - } + pub trait Trait: frame_support_test::Trait {} frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=self {} + pub struct Module for enum Call where origin: T::Origin, system=frame_support_test {} } type PairOf = (T, T); @@ -441,21 +437,22 @@ mod test2 { struct TraitImpl {} - impl Trait for TraitImpl { + impl frame_support_test::Trait for TraitImpl { type Origin = u32; type BlockNumber = u32; + type PalletInfo = (); } + + impl Trait for TraitImpl {} } #[cfg(test)] #[allow(dead_code)] mod test3 { - pub trait Trait { - type Origin; - type BlockNumber; - } + pub trait Trait: frame_support_test::Trait {} + frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=self {} + pub struct Module for enum Call where origin: T::Origin, system=frame_support_test {} } frame_support::decl_storage! { trait Store for Module as Test { @@ -467,10 +464,13 @@ mod test3 { struct TraitImpl {} - impl Trait for TraitImpl { + impl frame_support_test::Trait for TraitImpl { type Origin = u32; type BlockNumber = u32; + type PalletInfo = (); } + + impl Trait for TraitImpl {} } #[cfg(test)] @@ -479,13 +479,10 @@ mod test_append_and_len { use sp_io::TestExternalities; use codec::{Encode, Decode}; - pub trait Trait { - type Origin; - type BlockNumber; - } + pub trait Trait: frame_support_test::Trait {} frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=self {} + pub struct Module for enum Call where origin: T::Origin, system=frame_support_test {} } #[derive(PartialEq, Eq, Clone, Encode, Decode)] @@ -511,11 +508,14 @@ mod test_append_and_len { struct Test {} - impl Trait for Test { + impl frame_support_test::Trait for Test { type Origin = u32; type BlockNumber = u32; + type PalletInfo = (); } + impl Trait for Test {} + #[test] fn default_for_option() { TestExternalities::default().execute_with(|| { diff --git a/frame/support/test/tests/decl_storage_ui/config_duplicate.rs b/frame/support/test/tests/decl_storage_ui/config_duplicate.rs index f4f4ad7d48a97..58923ed19297c 100644 --- a/frame/support/test/tests/decl_storage_ui/config_duplicate.rs +++ b/frame/support/test/tests/decl_storage_ui/config_duplicate.rs @@ -15,13 +15,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -pub trait Trait { - type Origin; - type BlockNumber: codec::Codec + codec::EncodeLike + Default + Clone; -} +pub trait Trait: frame_support_test::Trait {} frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=self {} + pub struct Module for enum Call where origin: T::Origin, system=frame_support_test {} } frame_support::decl_storage!{ diff --git a/frame/support/test/tests/decl_storage_ui/config_duplicate.stderr b/frame/support/test/tests/decl_storage_ui/config_duplicate.stderr index 61f7c0bbe64a5..f6303f277b56b 100644 --- a/frame/support/test/tests/decl_storage_ui/config_duplicate.stderr +++ b/frame/support/test/tests/decl_storage_ui/config_duplicate.stderr @@ -1,5 +1,5 @@ error: `config()`/`get()` with the same name already defined. - --> $DIR/config_duplicate.rs:30:21 + --> $DIR/config_duplicate.rs:27:21 | -30 | pub Value2 config(value): u32; +27 | pub Value2 config(value): u32; | ^^^^^ diff --git a/frame/support/test/tests/decl_storage_ui/config_get_duplicate.rs b/frame/support/test/tests/decl_storage_ui/config_get_duplicate.rs index 3caa2d9c33608..e77dcea404ccb 100644 --- a/frame/support/test/tests/decl_storage_ui/config_get_duplicate.rs +++ b/frame/support/test/tests/decl_storage_ui/config_get_duplicate.rs @@ -15,13 +15,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -pub trait Trait { - type Origin; - type BlockNumber: codec::Codec + codec::EncodeLike + Default + Clone; -} +pub trait Trait: frame_support_test::Trait {} frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=self {} + pub struct Module for enum Call where origin: T::Origin, system=frame_support_test {} } frame_support::decl_storage!{ diff --git a/frame/support/test/tests/decl_storage_ui/config_get_duplicate.stderr b/frame/support/test/tests/decl_storage_ui/config_get_duplicate.stderr index 02e7d41080339..9377b718c0660 100644 --- a/frame/support/test/tests/decl_storage_ui/config_get_duplicate.stderr +++ b/frame/support/test/tests/decl_storage_ui/config_get_duplicate.stderr @@ -1,5 +1,5 @@ error: `config()`/`get()` with the same name already defined. - --> $DIR/config_get_duplicate.rs:30:21 + --> $DIR/config_get_duplicate.rs:27:21 | -30 | pub Value2 config(value): u32; +27 | pub Value2 config(value): u32; | ^^^^^ diff --git a/frame/support/test/tests/decl_storage_ui/get_duplicate.rs b/frame/support/test/tests/decl_storage_ui/get_duplicate.rs index 1c24b3bf28eec..b6ccb7ebb7b7b 100644 --- a/frame/support/test/tests/decl_storage_ui/get_duplicate.rs +++ b/frame/support/test/tests/decl_storage_ui/get_duplicate.rs @@ -15,13 +15,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -pub trait Trait { - type Origin; - type BlockNumber: codec::Codec + codec::EncodeLike + Default + Clone; -} +pub trait Trait: frame_support_test::Trait {} frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=self {} + pub struct Module for enum Call where origin: T::Origin, system=frame_support_test {} } frame_support::decl_storage!{ diff --git a/frame/support/test/tests/decl_storage_ui/get_duplicate.stderr b/frame/support/test/tests/decl_storage_ui/get_duplicate.stderr index d9ce420a6f214..0039b10fb43b6 100644 --- a/frame/support/test/tests/decl_storage_ui/get_duplicate.stderr +++ b/frame/support/test/tests/decl_storage_ui/get_duplicate.stderr @@ -1,5 +1,5 @@ error: `config()`/`get()` with the same name already defined. - --> $DIR/get_duplicate.rs:30:21 + --> $DIR/get_duplicate.rs:27:21 | -30 | pub Value2 get(fn value) config(): u32; +27 | pub Value2 get(fn value) config(): u32; | ^^^^^ diff --git a/frame/support/test/tests/final_keys.rs b/frame/support/test/tests/final_keys.rs index a9f0cdc8f184b..6bd1252825466 100644 --- a/frame/support/test/tests/final_keys.rs +++ b/frame/support/test/tests/final_keys.rs @@ -21,15 +21,10 @@ use frame_support::{StorageDoubleMap, StorageMap, StorageValue, StoragePrefixedM use sp_io::{TestExternalities, hashing::{twox_64, twox_128, blake2_128}}; mod no_instance { - use codec::{Encode, Decode, EncodeLike}; - - pub trait Trait { - type Origin; - type BlockNumber: Encode + Decode + EncodeLike + Default + Clone; - } + pub trait Trait: frame_support_test::Trait {} frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=self {} + pub struct Module for enum Call where origin: T::Origin, system=frame_support_test {} } frame_support::decl_storage!{ @@ -50,13 +45,11 @@ mod no_instance { } mod instance { - use super::no_instance; - - pub trait Trait: super::no_instance::Trait {} + pub trait Trait: frame_support_test::Trait {} frame_support::decl_module! { pub struct Module, I: Instance = DefaultInstance> - for enum Call where origin: T::Origin, system=no_instance {} + for enum Call where origin: T::Origin, system=frame_support_test {} } frame_support::decl_storage!{ diff --git a/frame/support/test/tests/genesisconfig.rs b/frame/support/test/tests/genesisconfig.rs index af8b393800cf9..dd8b6c7e5aebc 100644 --- a/frame/support/test/tests/genesisconfig.rs +++ b/frame/support/test/tests/genesisconfig.rs @@ -15,13 +15,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -pub trait Trait { - type BlockNumber: codec::Codec + codec::EncodeLike + Default; - type Origin; -} +pub trait Trait: frame_support_test::Trait {} frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=self {} + pub struct Module for enum Call where origin: T::Origin, system=frame_support_test {} } frame_support::decl_storage! { @@ -32,11 +29,14 @@ frame_support::decl_storage! { struct Test; -impl Trait for Test { +impl frame_support_test::Trait for Test { type BlockNumber = u32; type Origin = (); + type PalletInfo = (); } +impl Trait for Test {} + #[test] fn init_genesis_config() { GenesisConfig:: { diff --git a/frame/support/test/tests/reserved_keyword/on_initialize.rs b/frame/support/test/tests/reserved_keyword/on_initialize.rs index db71fe9a1e26a..781b72bd04e8c 100644 --- a/frame/support/test/tests/reserved_keyword/on_initialize.rs +++ b/frame/support/test/tests/reserved_keyword/on_initialize.rs @@ -4,10 +4,7 @@ macro_rules! reserved { mod $reserved { pub use frame_support::dispatch; - pub trait Trait { - type Origin; - type BlockNumber: Into; - } + pub trait Trait: frame_support_test::Trait {} pub mod system { use frame_support::dispatch; @@ -18,7 +15,7 @@ macro_rules! reserved { } frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=self { + pub struct Module for enum Call where origin: T::Origin, system=frame_support_test { #[weight = 0] fn $reserved(_origin) -> dispatch::DispatchResult { unreachable!() } } diff --git a/frame/support/test/tests/reserved_keyword/on_initialize.stderr b/frame/support/test/tests/reserved_keyword/on_initialize.stderr index dbe07195e89dd..3df392dee9005 100644 --- a/frame/support/test/tests/reserved_keyword/on_initialize.stderr +++ b/frame/support/test/tests/reserved_keyword/on_initialize.stderr @@ -1,39 +1,39 @@ error: Invalid call fn name: `on_finalize`, name is reserved and doesn't match expected signature, please refer to `decl_module!` documentation to see the appropriate usage, or rename it to an unreserved keyword. - --> $DIR/on_initialize.rs:31:1 + --> $DIR/on_initialize.rs:28:1 | -31 | reserved!(on_finalize on_initialize on_runtime_upgrade offchain_worker deposit_event); +28 | reserved!(on_finalize on_initialize on_runtime_upgrade offchain_worker deposit_event); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) error: Invalid call fn name: `on_initialize`, name is reserved and doesn't match expected signature, please refer to `decl_module!` documentation to see the appropriate usage, or rename it to an unreserved keyword. - --> $DIR/on_initialize.rs:31:1 + --> $DIR/on_initialize.rs:28:1 | -31 | reserved!(on_finalize on_initialize on_runtime_upgrade offchain_worker deposit_event); +28 | reserved!(on_finalize on_initialize on_runtime_upgrade offchain_worker deposit_event); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) error: Invalid call fn name: `on_runtime_upgrade`, name is reserved and doesn't match expected signature, please refer to `decl_module!` documentation to see the appropriate usage, or rename it to an unreserved keyword. - --> $DIR/on_initialize.rs:31:1 + --> $DIR/on_initialize.rs:28:1 | -31 | reserved!(on_finalize on_initialize on_runtime_upgrade offchain_worker deposit_event); +28 | reserved!(on_finalize on_initialize on_runtime_upgrade offchain_worker deposit_event); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) error: Invalid call fn name: `offchain_worker`, name is reserved and doesn't match expected signature, please refer to `decl_module!` documentation to see the appropriate usage, or rename it to an unreserved keyword. - --> $DIR/on_initialize.rs:31:1 + --> $DIR/on_initialize.rs:28:1 | -31 | reserved!(on_finalize on_initialize on_runtime_upgrade offchain_worker deposit_event); +28 | reserved!(on_finalize on_initialize on_runtime_upgrade offchain_worker deposit_event); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) error: Invalid call fn name: `deposit_event`, name is reserved and doesn't match expected signature, please refer to `decl_module!` documentation to see the appropriate usage, or rename it to an unreserved keyword. - --> $DIR/on_initialize.rs:31:1 + --> $DIR/on_initialize.rs:28:1 | -31 | reserved!(on_finalize on_initialize on_runtime_upgrade offchain_worker deposit_event); +28 | reserved!(on_finalize on_initialize on_runtime_upgrade offchain_worker deposit_event); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/frame/support/test/tests/storage_transaction.rs b/frame/support/test/tests/storage_transaction.rs index a7e4a75c27fcb..78610440e4838 100644 --- a/frame/support/test/tests/storage_transaction.rs +++ b/frame/support/test/tests/storage_transaction.rs @@ -15,21 +15,17 @@ // See the License for the specific language governing permissions and // limitations under the License. -use codec::{Encode, Decode, EncodeLike}; use frame_support::{ - assert_ok, assert_noop, dispatch::{DispatchError, DispatchResult}, transactional, StorageMap, StorageValue, - storage::{with_transaction, TransactionOutcome::*}, + assert_ok, assert_noop, transactional, StorageMap, StorageValue, + dispatch::{DispatchError, DispatchResult}, storage::{with_transaction, TransactionOutcome::*}, }; use sp_io::TestExternalities; use sp_std::result; -pub trait Trait { - type Origin; - type BlockNumber: Encode + Decode + EncodeLike + Default + Clone; -} +pub trait Trait: frame_support_test::Trait {} frame_support::decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=self { + pub struct Module for enum Call where origin: T::Origin, system=frame_support_test { #[weight = 0] #[transactional] fn value_commits(_origin, v: u32) { @@ -53,11 +49,15 @@ frame_support::decl_storage!{ } struct Runtime; -impl Trait for Runtime { + +impl frame_support_test::Trait for Runtime { type Origin = u32; type BlockNumber = u32; + type PalletInfo = (); } +impl Trait for Runtime {} + #[test] fn storage_transaction_basic_commit() { TestExternalities::default().execute_with(|| { From 3e18d340515ec43928770052c9e307a78c197b28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Thu, 24 Sep 2020 18:03:51 +0200 Subject: [PATCH 08/16] Adds a test and fixes some bugs --- frame/support/src/dispatch.rs | 6 +- frame/support/test/tests/pallet_version.rs | 170 +++++++++++++++++++++ 2 files changed, 174 insertions(+), 2 deletions(-) create mode 100644 frame/support/test/tests/pallet_version.rs diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index e57925771265c..d1154baccb77b 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -1329,7 +1329,7 @@ macro_rules! decl_module { <$trait_instance as $system::Trait>::PalletInfo, Self >().expect("Every active pallet has a name in the runtime; qed"); let version = $crate::crate_to_pallet_version!(); - $crate::storage::unhashed::put(&key, &$crate::dispatch::Encode::encode(&version)); + $crate::storage::unhashed::put(&key, &version); result } @@ -1352,7 +1352,7 @@ macro_rules! decl_module { <$trait_instance as $system::Trait>::PalletInfo, Self >().expect("Every active pallet has a name in the runtime; qed"); let version = $crate::crate_to_pallet_version!(); - $crate::storage::unhashed::put(&key, &$crate::dispatch::Encode::encode(&version)); + $crate::storage::unhashed::put(&key, &version); 0 } @@ -1812,6 +1812,8 @@ macro_rules! decl_module { } } + // Bring `GetPalletVersion` into scope to make it easily usable. + pub use $crate::traits::GetPalletVersion as _; // Implement `GetPalletVersion` for `Module` impl<$trait_instance: $trait_name $(, $instance: $instantiable)?> $crate::traits::GetPalletVersion for $mod_type<$trait_instance $(, $instance)?> where $( $other_where_bounds )* diff --git a/frame/support/test/tests/pallet_version.rs b/frame/support/test/tests/pallet_version.rs new file mode 100644 index 0000000000000..614475c8074c8 --- /dev/null +++ b/frame/support/test/tests/pallet_version.rs @@ -0,0 +1,170 @@ +// This file is part of Substrate. + +// Copyright (C) 2020 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Tests related to the pallet version. + +#![recursion_limit="128"] + +use codec::{Decode, Encode}; +use sp_runtime::{generic, traits::{BlakeTwo256, Block as _, Verify}}; +use frame_support::{ + traits::{PALLET_VERSION_STORAGE_KEY_POSTFIX, PalletVersion, OnRuntimeUpgrade}, + crate_to_pallet_version, weights::Weight, +}; +use sp_core::{H256, sr25519}; + +mod system; + +/// A version that we will check for in the tests +const SOME_TEST_VERSION: PalletVersion = PalletVersion { major: 3000, minor: 30, patch: 13 }; + +/// Checks that `on_runtime_upgrade` sets the latest pallet version when being called without +/// being provided by the user. +mod module1 { + use super::*; + + pub trait Trait: system::Trait {} + + frame_support::decl_module! { + pub struct Module for enum Call where + origin: ::Origin, + system = system, + {} + } +} + +/// Checks that `on_runtime_upgrade` sets the latest pallet version when being called and also +/// being provided by the user. +mod module2 { + use super::*; + + pub trait Trait: system::Trait {} + + frame_support::decl_module! { + pub struct Module, I: Instance=DefaultInstance> for enum Call where + origin: ::Origin, + system = system + { + fn on_runtime_upgrade() -> Weight { + assert_eq!(crate_to_pallet_version!(), Self::current_version()); + + let version_key = PalletVersion::storage_key::().unwrap(); + let version_value = sp_io::storage::get(&version_key); + + if version_value.is_some() { + assert_eq!(SOME_TEST_VERSION, Self::storage_version()); + } else { + // As the storage version does not exist yet, it should be the same as + // the current version. + assert_eq!(Self::storage_version(), Self::current_version()); + } + + 0 + } + } + } + + frame_support::decl_storage! { + trait Store for Module, I: Instance=DefaultInstance> as Module2 {} + } +} + +impl module1::Trait for Runtime {} +impl module2::Trait for Runtime {} +impl module2::Trait for Runtime {} +impl module2::Trait for Runtime {} + +pub type Signature = sr25519::Signature; +pub type AccountId = ::Signer; +pub type BlockNumber = u64; +pub type Index = u64; + +impl system::Trait for Runtime { + type BaseCallFilter= (); + type Hash = H256; + type Origin = Origin; + type BlockNumber = BlockNumber; + type AccountId = AccountId; + type Event = Event; + type PalletInfo = PalletInfo; + type Call = Call; +} + +frame_support::construct_runtime!( + pub enum Runtime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic + { + System: system::{Module, Call, Event}, + Module1: module1::{Module, Call}, + Module2: module2::{Module, Call}, + Module2_1: module2::::{Module, Call}, + Module2_2: module2::::{Module, Call}, + } +); + +pub type Header = generic::Header; +pub type Block = generic::Block; +pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; + +/// Returns the storage key for `PalletVersion` for the given `pallet`. +fn get_pallet_version_storage_key_for_pallet(pallet: &str) -> [u8; 16] { + let mut key = pallet.as_bytes().to_vec(); + key.extend(PALLET_VERSION_STORAGE_KEY_POSTFIX); + sp_io::hashing::twox_128(&key) +} + +/// Checks the version of the given `pallet`. +/// +/// It is expected that the pallet version can be found in the storage and equals the +/// current crate version. +fn check_pallet_version(pallet: &str) { + let key = get_pallet_version_storage_key_for_pallet(pallet); + let value = sp_io::storage::get(&key).expect("Pallet version exists"); + let version = PalletVersion::decode(&mut &value[..]) + .expect("Pallet version is encoded correctly"); + + assert_eq!(crate_to_pallet_version!(), version); +} + +#[test] +fn on_runtime_upgrade_sets_the_pallet_versions_in_storage() { + sp_io::TestExternalities::new_empty().execute_with(|| { + AllModules::on_runtime_upgrade(); + + check_pallet_version("Module1"); + check_pallet_version("Module2"); + check_pallet_version("Module2_1"); + check_pallet_version("Module2_2"); + }); +} + +#[test] +fn on_runtime_upgrade_overwrites_old_version() { + sp_io::TestExternalities::new_empty().execute_with(|| { + let key = get_pallet_version_storage_key_for_pallet("Module2"); + sp_io::storage::set(&key, &SOME_TEST_VERSION.encode()); + + AllModules::on_runtime_upgrade(); + + check_pallet_version("Module1"); + check_pallet_version("Module2"); + check_pallet_version("Module2_1"); + check_pallet_version("Module2_2"); + }); +} From 8b5adb284cde3c0d6f2e001279cd06173df4d902 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Thu, 24 Sep 2020 21:02:56 +0200 Subject: [PATCH 09/16] Implement ordering for `PalletVersion` --- frame/support/src/traits.rs | 39 ++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/frame/support/src/traits.rs b/frame/support/src/traits.rs index 43669fb41b34a..6fceb4fc1f2b8 100644 --- a/frame/support/src/traits.rs +++ b/frame/support/src/traits.rs @@ -1682,7 +1682,7 @@ pub const PALLET_VERSION_STORAGE_KEY_POSTFIX: &[u8] = b":__PALLET_VERSION__:"; /// /// Each pallet version is stored in the state under a fixed key. See /// [`PALLET_VERSION_STORAGE_KEY_POSTFIX`] for how this key is build. -#[derive(RuntimeDebug, Eq, PartialEq, Encode, Decode)] +#[derive(RuntimeDebug, Eq, PartialEq, Encode, Decode, Ord)] pub struct PalletVersion { /// The major version of the pallet. pub major: u16, @@ -1693,6 +1693,15 @@ pub struct PalletVersion { } impl PalletVersion { + /// Creates a new instance of `Self`. + pub fn new(major: u16, minor: u8, patch: u8) -> Self { + Self { + major, + minor, + patch, + } + } + /// Returns the storage key for a pallet version. /// /// See [`PALLET_VERSION_STORAGE_KEY_POSTIFX`] on how this key is build. @@ -1712,6 +1721,20 @@ impl PalletVersion { } } +impl sp_std::cmp::PartialOrd for PalletVersion { + fn partial_cmp(&self, other: &Self) -> Option { + let res = self.major + .cmp(&other.major) + .then_with(|| + self.minor + .cmp(&other.minor) + .then_with(|| self.patch.cmp(&other.patch) + )); + + Some(res) + } +} + /// Provides version information about a pallet. /// /// This trait provides two functions for returning the version of a @@ -1759,4 +1782,18 @@ mod tests { assert_eq!(<(Test, Test)>::on_initialize(0), 20); assert_eq!(<(Test, Test)>::on_runtime_upgrade(), 40); } + + #[test] + fn check_pallet_version_ordering() { + let version = PalletVersion::new(1, 0, 0); + assert!(version > PalletVersion::new(0, 1, 2)); + assert!(version == PalletVersion::new(1, 0, 0)); + assert!(version < PalletVersion::new(1, 0, 1)); + assert!(version < PalletVersion::new(1, 1, 0)); + + let version = PalletVersion::new(2, 50, 50); + assert!(version < PalletVersion::new(2, 50, 51)); + assert!(version > PalletVersion::new(2, 49, 51)); + assert!(version < PalletVersion::new(3, 49, 51)); + } } From b8182b88a933a6736df33ed24177d4c167d31ce9 Mon Sep 17 00:00:00 2001 From: Alexander Popiak Date: Mon, 28 Sep 2020 15:26:35 +0200 Subject: [PATCH 10/16] Apply suggestions from code review --- frame/support/src/traits.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/frame/support/src/traits.rs b/frame/support/src/traits.rs index 6fceb4fc1f2b8..0e799f00844d6 100644 --- a/frame/support/src/traits.rs +++ b/frame/support/src/traits.rs @@ -1674,14 +1674,14 @@ pub trait Instance: 'static { /// The storage key postfix that is used to store the [`PalletVersion`] per pallet. /// -/// The full storage key is build by using: -/// Twox128([`PalletInfo::name`] ++ [`PALLET_VERSION_STORAGE_POSTFIX`]) +/// The full storage key is built by using: +/// Twox128([`PalletInfo::name`] ++ [`PALLET_VERSION_STORAGE_KEY_POSTFIX`]) pub const PALLET_VERSION_STORAGE_KEY_POSTFIX: &[u8] = b":__PALLET_VERSION__:"; /// The version of a pallet. /// /// Each pallet version is stored in the state under a fixed key. See -/// [`PALLET_VERSION_STORAGE_KEY_POSTFIX`] for how this key is build. +/// [`PALLET_VERSION_STORAGE_KEY_POSTFIX`] for how this key is built. #[derive(RuntimeDebug, Eq, PartialEq, Encode, Decode, Ord)] pub struct PalletVersion { /// The major version of the pallet. @@ -1704,7 +1704,7 @@ impl PalletVersion { /// Returns the storage key for a pallet version. /// - /// See [`PALLET_VERSION_STORAGE_KEY_POSTIFX`] on how this key is build. + /// See [`PALLET_VERSION_STORAGE_KEY_POSTIFX`] on how this key is built. /// /// Returns `None` if the given `PI` returned a `None` as name for the given /// `Pallet`. From 4db05e6878b454cba4d5a16048c643262bfe6d39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Tue, 20 Oct 2020 11:10:26 +0200 Subject: [PATCH 11/16] Review feedback --- frame/support/src/dispatch.rs | 12 +++--------- frame/support/src/traits.rs | 21 +++++++++++---------- frame/support/test/tests/pallet_version.rs | 7 +++---- 3 files changed, 17 insertions(+), 23 deletions(-) diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index b421fc2064365..548d7856847c0 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -1323,7 +1323,7 @@ macro_rules! decl_module { { fn on_runtime_upgrade() -> $return { $crate::sp_tracing::enter_span!($crate::sp_tracing::trace_span!("on_runtime_upgrade")); - let result = { $( $impl )* }; + let result = (|| { $( $impl )* })(); let key = $crate::traits::PalletVersion::storage_key::< <$trait_instance as $system::Trait>::PalletInfo, Self @@ -1822,18 +1822,12 @@ macro_rules! decl_module { $crate::crate_to_pallet_version!() } - fn storage_version() -> $crate::traits::PalletVersion { + fn storage_version() -> Option<$crate::traits::PalletVersion> { let key = $crate::traits::PalletVersion::storage_key::< <$trait_instance as $system::Trait>::PalletInfo, Self >().expect("Every active pallet has a name in the runtime; qed"); - let value: Option<$crate::traits::PalletVersion> = - $crate::storage::unhashed::get(&key); - - match value { - Some(version) => version, - None => $crate::crate_to_pallet_version!(), - } + $crate::storage::unhashed::get(&key) } } diff --git a/frame/support/src/traits.rs b/frame/support/src/traits.rs index fc5fd241b5cfa..af7a7ee3635e7 100644 --- a/frame/support/src/traits.rs +++ b/frame/support/src/traits.rs @@ -1829,7 +1829,7 @@ pub trait IsSubType { /// The storage key postfix that is used to store the [`PalletVersion`] per pallet. /// /// The full storage key is built by using: -/// Twox128([`PalletInfo::name`] ++ [`PALLET_VERSION_STORAGE_KEY_POSTFIX`]) +/// Twox128([`PalletInfo::name`]) ++ Twox128([`PALLET_VERSION_STORAGE_KEY_POSTFIX`]) pub const PALLET_VERSION_STORAGE_KEY_POSTFIX: &[u8] = b":__PALLET_VERSION__:"; /// The version of a pallet. @@ -1862,16 +1862,17 @@ impl PalletVersion { /// /// Returns `None` if the given `PI` returned a `None` as name for the given /// `Pallet`. - pub fn storage_key() -> Option<[u8; 16]> { + pub fn storage_key() -> Option<[u8; 32]> { let pallet_name = PI::name::()?; - let mut key = Vec::with_capacity( - pallet_name.as_bytes().len() + PALLET_VERSION_STORAGE_KEY_POSTFIX.len(), - ); - key.extend(pallet_name.as_bytes()); - key.extend(PALLET_VERSION_STORAGE_KEY_POSTFIX); + let pallet_name = sp_io::hashing::twox_128(pallet_name.as_bytes()); + let postfix = sp_io::hashing::twox_128(PALLET_VERSION_STORAGE_KEY_POSTFIX); - Some(sp_io::hashing::twox_128(&key)) + let mut final_key = [0u8; 32]; + final_key[..16].copy_from_slice(&pallet_name); + final_key[16..].copy_from_slice(&postfix); + + Some(final_key) } } @@ -1911,8 +1912,8 @@ pub trait GetPalletVersion { /// # Note /// /// If there was no previous version of the pallet stored in the state, - /// this function will return [`GetPalletVersion::current_version`] - fn storage_version() -> PalletVersion; + /// this function returns `None`. + fn storage_version() -> Option; } #[cfg(test)] diff --git a/frame/support/test/tests/pallet_version.rs b/frame/support/test/tests/pallet_version.rs index 614475c8074c8..9de87c4feefa0 100644 --- a/frame/support/test/tests/pallet_version.rs +++ b/frame/support/test/tests/pallet_version.rs @@ -66,11 +66,10 @@ mod module2 { let version_value = sp_io::storage::get(&version_key); if version_value.is_some() { - assert_eq!(SOME_TEST_VERSION, Self::storage_version()); + assert_eq!(SOME_TEST_VERSION, Self::storage_version().unwrap()); } else { - // As the storage version does not exist yet, it should be the same as - // the current version. - assert_eq!(Self::storage_version(), Self::current_version()); + // As the storage version does not exist yet, it should be `None`. + assert!(Self::storage_version().is_none()); } 0 From 71ec68cb33f7f14504b178b06544d9998c793c6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Tue, 20 Oct 2020 15:49:13 +0200 Subject: [PATCH 12/16] Update frame/support/src/dispatch.rs Co-authored-by: Guillaume Thiolliere --- frame/support/src/dispatch.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index 548d7856847c0..5b0d59feef9ee 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -1331,7 +1331,11 @@ macro_rules! decl_module { let version = $crate::crate_to_pallet_version!(); $crate::storage::unhashed::put(&key, &version); - result + let additional_write = < + <$trait_instance as $system::Trait>::DbWeight as $crate::traits::Get<_> + >::get().writes(1); + + result.saturating_add(additional_write) } } }; From 2d80e8064c422ba0b4ab2cfe31235b6f1f48023d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Tue, 20 Oct 2020 15:49:22 +0200 Subject: [PATCH 13/16] Update frame/support/src/dispatch.rs Co-authored-by: Guillaume Thiolliere --- frame/support/src/dispatch.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index 5b0d59feef9ee..d953370dc7958 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -1358,7 +1358,9 @@ macro_rules! decl_module { let version = $crate::crate_to_pallet_version!(); $crate::storage::unhashed::put(&key, &version); - 0 + < + <$trait_instance as $system::Trait>::DbWeight as $crate::traits::Get<_> + >::get().writes(1) } } }; From 20155c2dfadf7dda01eced99a4ba3d5dc8bc93c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Tue, 20 Oct 2020 21:57:59 +0200 Subject: [PATCH 14/16] Fix compilation --- frame/support/src/dispatch.rs | 10 ++++++---- frame/support/src/event.rs | 5 +++++ frame/support/src/lib.rs | 2 ++ frame/support/src/metadata.rs | 4 ++++ frame/support/src/storage/generator/double_map.rs | 1 + frame/support/src/storage/generator/map.rs | 1 + frame/support/src/storage/generator/mod.rs | 2 ++ frame/support/test/src/lib.rs | 2 ++ frame/support/test/tests/construct_runtime.rs | 1 + frame/support/test/tests/decl_storage.rs | 4 ++++ frame/support/test/tests/genesisconfig.rs | 1 + frame/support/test/tests/instance.rs | 1 + frame/support/test/tests/issue2219.rs | 1 + frame/support/test/tests/pallet_version.rs | 1 + frame/support/test/tests/storage_transaction.rs | 1 + frame/support/test/tests/system.rs | 5 ++++- 16 files changed, 37 insertions(+), 5 deletions(-) diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index d953370dc7958..b96d6194ebffe 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -1323,7 +1323,7 @@ macro_rules! decl_module { { fn on_runtime_upgrade() -> $return { $crate::sp_tracing::enter_span!($crate::sp_tracing::trace_span!("on_runtime_upgrade")); - let result = (|| { $( $impl )* })(); + let result: $return = (|| { $( $impl )* })(); let key = $crate::traits::PalletVersion::storage_key::< <$trait_instance as $system::Trait>::PalletInfo, Self @@ -2402,16 +2402,16 @@ macro_rules! __check_reserved_fn_name { #[allow(dead_code)] mod tests { use super::*; - use crate::weights::{DispatchInfo, DispatchClass, Pays}; + use crate::weights::{DispatchInfo, DispatchClass, Pays, RuntimeDbWeight}; use crate::traits::{ CallMetadata, GetCallMetadata, GetCallName, OnInitialize, OnFinalize, OnRuntimeUpgrade, - IntegrityTest, + IntegrityTest, Get, }; pub trait Trait: system::Trait + Sized where Self::AccountId: From { } pub mod system { - use codec::{Encode, Decode}; + use super::*; pub trait Trait: 'static { type AccountId; @@ -2420,6 +2420,7 @@ mod tests { type Origin: crate::traits::OriginTrait; type BlockNumber: Into; type PalletInfo: crate::traits::PalletInfo; + type DbWeight: Get; } #[derive(Clone, PartialEq, Eq, Debug, Encode, Decode)] @@ -2564,6 +2565,7 @@ mod tests { type BaseCallFilter = (); type BlockNumber = u32; type PalletInfo = (); + type DbWeight = (); } #[test] diff --git a/frame/support/src/event.rs b/frame/support/src/event.rs index 1b1f6ab4759b6..3538748c30faf 100644 --- a/frame/support/src/event.rs +++ b/frame/support/src/event.rs @@ -555,6 +555,7 @@ mod tests { type Origin; type BlockNumber; type PalletInfo: crate::traits::PalletInfo; + type DbWeight: crate::traits::Get; } decl_module! { @@ -573,6 +574,7 @@ mod tests { type Origin; type BlockNumber; type PalletInfo: crate::traits::PalletInfo; + type DbWeight: crate::traits::Get; } decl_module! { @@ -724,6 +726,7 @@ mod tests { type Origin = u32; type BlockNumber = u32; type PalletInfo = (); + type DbWeight = (); } impl event_module::Trait for TestRuntime2 { @@ -738,12 +741,14 @@ mod tests { type Origin = u32; type BlockNumber = u32; type PalletInfo = (); + type DbWeight = (); } impl system::Trait for TestRuntime2 { type Origin = u32; type BlockNumber = u32; type PalletInfo = (); + type DbWeight = (); } const EXPECTED_METADATA: OuterEventMetadata = OuterEventMetadata { diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 6c9a2fa4c6e00..2380c8127d7af 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -504,6 +504,7 @@ mod tests { type BlockNumber: Codec + EncodeLike + Default; type Origin; type PalletInfo: crate::traits::PalletInfo; + type DbWeight: crate::traits::Get; } mod module { @@ -544,6 +545,7 @@ mod tests { type BlockNumber = u32; type Origin = u32; type PalletInfo = (); + type DbWeight = (); } fn new_test_ext() -> TestExternalities { diff --git a/frame/support/src/metadata.rs b/frame/support/src/metadata.rs index f20f54df14982..79685a7f9bc4c 100644 --- a/frame/support/src/metadata.rs +++ b/frame/support/src/metadata.rs @@ -31,6 +31,7 @@ pub use frame_metadata::{ ///# type Origin; ///# type BlockNumber; ///# type PalletInfo: frame_support::traits::PalletInfo; +///# type DbWeight: crate::traits::Get; ///# } ///# frame_support::decl_module! { ///# pub struct Module for enum Call where origin: T::Origin, system=self {} @@ -46,6 +47,7 @@ pub use frame_metadata::{ ///# type Origin = u32; ///# type BlockNumber = u32; ///# type PalletInfo = (); +///# type DbWeight = (); ///# } ///# ///# type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic<(), (), (), ()>; @@ -304,6 +306,7 @@ mod tests { type BlockNumber: From + Encode; type SomeValue: Get; type PalletInfo: crate::traits::PalletInfo; + type DbWeight: crate::traits::Get; type Call; } @@ -449,6 +452,7 @@ mod tests { type BlockNumber = u32; type SomeValue = SystemValue; type PalletInfo = (); + type DbWeight = (); type Call = Call; } diff --git a/frame/support/src/storage/generator/double_map.rs b/frame/support/src/storage/generator/double_map.rs index f5495092ec63d..cbc62c83de886 100644 --- a/frame/support/src/storage/generator/double_map.rs +++ b/frame/support/src/storage/generator/double_map.rs @@ -429,6 +429,7 @@ mod test_iterators { type Origin; type BlockNumber; type PalletInfo: crate::traits::PalletInfo; + type DbWeight: crate::traits::Get; } crate::decl_module! { diff --git a/frame/support/src/storage/generator/map.rs b/frame/support/src/storage/generator/map.rs index 6ea185cebae2c..601fd4c4a8dd2 100644 --- a/frame/support/src/storage/generator/map.rs +++ b/frame/support/src/storage/generator/map.rs @@ -329,6 +329,7 @@ mod test_iterators { type Origin; type BlockNumber; type PalletInfo: crate::traits::PalletInfo; + type DbWeight: crate::traits::Get; } crate::decl_module! { diff --git a/frame/support/src/storage/generator/mod.rs b/frame/support/src/storage/generator/mod.rs index b36c8b7d47b21..9346718f63481 100644 --- a/frame/support/src/storage/generator/mod.rs +++ b/frame/support/src/storage/generator/mod.rs @@ -46,12 +46,14 @@ mod tests { type Origin; type BlockNumber; type PalletInfo: crate::traits::PalletInfo; + type DbWeight: crate::traits::Get; } impl Trait for Runtime { type Origin = u32; type BlockNumber = u32; type PalletInfo = (); + type DbWeight = (); } decl_module! { diff --git a/frame/support/test/src/lib.rs b/frame/support/test/src/lib.rs index 07a4a4206fdd7..a917c781c065c 100644 --- a/frame/support/test/src/lib.rs +++ b/frame/support/test/src/lib.rs @@ -33,6 +33,8 @@ pub trait Trait: 'static { type BlockNumber: codec::Codec + codec::EncodeLike + Default; /// The information about the pallet setup in the runtime. type PalletInfo: frame_support::traits::PalletInfo; + /// The db weights. + type DbWeight: frame_support::traits::Get; } frame_support::decl_module! { diff --git a/frame/support/test/tests/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index 9a17e44dbef4c..4ff4fc6828604 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -129,6 +129,7 @@ impl system::Trait for Runtime { type Event = Event; type PalletInfo = PalletInfo; type Call = Call; + type DbWeight = (); } frame_support::construct_runtime!( diff --git a/frame/support/test/tests/decl_storage.rs b/frame/support/test/tests/decl_storage.rs index 0ac80129700b4..8d5727ce9104b 100644 --- a/frame/support/test/tests/decl_storage.rs +++ b/frame/support/test/tests/decl_storage.rs @@ -85,6 +85,7 @@ mod tests { type Origin = u32; type BlockNumber = u32; type PalletInfo = (); + type DbWeight = (); } impl Trait for TraitImpl {} @@ -441,6 +442,7 @@ mod test2 { type Origin = u32; type BlockNumber = u32; type PalletInfo = (); + type DbWeight = (); } impl Trait for TraitImpl {} @@ -468,6 +470,7 @@ mod test3 { type Origin = u32; type BlockNumber = u32; type PalletInfo = (); + type DbWeight = (); } impl Trait for TraitImpl {} @@ -512,6 +515,7 @@ mod test_append_and_len { type Origin = u32; type BlockNumber = u32; type PalletInfo = (); + type DbWeight = (); } impl Trait for Test {} diff --git a/frame/support/test/tests/genesisconfig.rs b/frame/support/test/tests/genesisconfig.rs index dd8b6c7e5aebc..f268f11a4dc15 100644 --- a/frame/support/test/tests/genesisconfig.rs +++ b/frame/support/test/tests/genesisconfig.rs @@ -33,6 +33,7 @@ impl frame_support_test::Trait for Test { type BlockNumber = u32; type Origin = (); type PalletInfo = (); + type DbWeight = (); } impl Trait for Test {} diff --git a/frame/support/test/tests/instance.rs b/frame/support/test/tests/instance.rs index e1766082dd806..61df5d4eb8182 100644 --- a/frame/support/test/tests/instance.rs +++ b/frame/support/test/tests/instance.rs @@ -250,6 +250,7 @@ impl system::Trait for Runtime { type Event = Event; type PalletInfo = (); type Call = Call; + type DbWeight = (); } frame_support::construct_runtime!( diff --git a/frame/support/test/tests/issue2219.rs b/frame/support/test/tests/issue2219.rs index 34310c2f5876f..596a3b6ffb25d 100644 --- a/frame/support/test/tests/issue2219.rs +++ b/frame/support/test/tests/issue2219.rs @@ -166,6 +166,7 @@ impl system::Trait for Runtime { type Event = Event; type PalletInfo = (); type Call = Call; + type DbWeight = (); } impl module::Trait for Runtime {} diff --git a/frame/support/test/tests/pallet_version.rs b/frame/support/test/tests/pallet_version.rs index 9de87c4feefa0..5b04600bd55cf 100644 --- a/frame/support/test/tests/pallet_version.rs +++ b/frame/support/test/tests/pallet_version.rs @@ -101,6 +101,7 @@ impl system::Trait for Runtime { type Event = Event; type PalletInfo = PalletInfo; type Call = Call; + type DbWeight = (); } frame_support::construct_runtime!( diff --git a/frame/support/test/tests/storage_transaction.rs b/frame/support/test/tests/storage_transaction.rs index 3bf74b4761ddb..5c687ef05005d 100644 --- a/frame/support/test/tests/storage_transaction.rs +++ b/frame/support/test/tests/storage_transaction.rs @@ -54,6 +54,7 @@ impl frame_support_test::Trait for Runtime { type Origin = u32; type BlockNumber = u32; type PalletInfo = (); + type DbWeight = (); } impl Trait for Runtime {} diff --git a/frame/support/test/tests/system.rs b/frame/support/test/tests/system.rs index a7d4d43c341a9..f30b6e4c2af9d 100644 --- a/frame/support/test/tests/system.rs +++ b/frame/support/test/tests/system.rs @@ -15,7 +15,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support::codec::{Encode, Decode, EncodeLike}; +use frame_support::{ + codec::{Encode, Decode, EncodeLike}, traits::Get, weights::RuntimeDbWeight, +}; pub trait Trait: 'static + Eq + Clone { type Origin: Into, Self::Origin>> @@ -28,6 +30,7 @@ pub trait Trait: 'static + Eq + Clone { type Call; type Event: From>; type PalletInfo: frame_support::traits::PalletInfo; + type DbWeight: Get; } frame_support::decl_module! { From caf173eb51fc74ab0877906b2566e8294c4ded94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Tue, 20 Oct 2020 22:04:57 +0200 Subject: [PATCH 15/16] Fix test --- frame/support/test/tests/pallet_version.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/frame/support/test/tests/pallet_version.rs b/frame/support/test/tests/pallet_version.rs index 5b04600bd55cf..f3f4029b0da53 100644 --- a/frame/support/test/tests/pallet_version.rs +++ b/frame/support/test/tests/pallet_version.rs @@ -123,10 +123,15 @@ pub type Block = generic::Block; pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; /// Returns the storage key for `PalletVersion` for the given `pallet`. -fn get_pallet_version_storage_key_for_pallet(pallet: &str) -> [u8; 16] { - let mut key = pallet.as_bytes().to_vec(); - key.extend(PALLET_VERSION_STORAGE_KEY_POSTFIX); - sp_io::hashing::twox_128(&key) +fn get_pallet_version_storage_key_for_pallet(pallet: &str) -> [u8; 32] { + let pallet_name = sp_io::hashing::twox_128(pallet.as_bytes()); + let postfix = sp_io::hashing::twox_128(PALLET_VERSION_STORAGE_KEY_POSTFIX); + + let mut final_key = [0u8; 32]; + final_key[..16].copy_from_slice(&pallet_name); + final_key[16..].copy_from_slice(&postfix); + + final_key } /// Checks the version of the given `pallet`. From 5e5920e279020f53dd6812b91507b64b2b1b239d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Tue, 20 Oct 2020 23:32:15 +0200 Subject: [PATCH 16/16] Fix doc test --- frame/support/src/metadata.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frame/support/src/metadata.rs b/frame/support/src/metadata.rs index 79685a7f9bc4c..80737e4b13d6f 100644 --- a/frame/support/src/metadata.rs +++ b/frame/support/src/metadata.rs @@ -31,7 +31,7 @@ pub use frame_metadata::{ ///# type Origin; ///# type BlockNumber; ///# type PalletInfo: frame_support::traits::PalletInfo; -///# type DbWeight: crate::traits::Get; +///# type DbWeight: frame_support::traits::Get; ///# } ///# frame_support::decl_module! { ///# pub struct Module for enum Call where origin: T::Origin, system=self {}