diff --git a/frame/benchmarking/src/tests.rs b/frame/benchmarking/src/tests.rs index 80b631bb73668..7e240ee04903a 100644 --- a/frame/benchmarking/src/tests.rs +++ b/frame/benchmarking/src/tests.rs @@ -45,28 +45,21 @@ mod pallet_test { } #[pallet::storage] - #[pallet::getter(fn value)] pub(crate) type Value = StorageValue<_, u32, OptionQuery>; #[pallet::call] impl Pallet { - #[pallet::call_index(0)] - #[pallet::weight(0)] pub fn set_value(origin: OriginFor, n: u32) -> DispatchResult { let _sender = ensure_signed(origin)?; Value::::put(n); Ok(()) } - #[pallet::call_index(1)] - #[pallet::weight(0)] pub fn dummy(origin: OriginFor, _n: u32) -> DispatchResult { let _sender = ensure_none(origin)?; Ok(()) } - #[pallet::call_index(2)] - #[pallet::weight(0)] pub fn always_error(_origin: OriginFor) -> DispatchResult { return Err("I always fail".into()) } diff --git a/frame/benchmarking/src/tests_instance.rs b/frame/benchmarking/src/tests_instance.rs index 92d78b9ecbbe1..d017fc679875e 100644 --- a/frame/benchmarking/src/tests_instance.rs +++ b/frame/benchmarking/src/tests_instance.rs @@ -49,7 +49,6 @@ mod pallet_test { } #[pallet::storage] - #[pallet::getter(fn value)] pub(crate) type Value, I: 'static = ()> = StorageValue<_, u32, OptionQuery>; #[pallet::event] diff --git a/frame/collective/src/tests.rs b/frame/collective/src/tests.rs index 1165ebcec2287..99aa7a57e1604 100644 --- a/frame/collective/src/tests.rs +++ b/frame/collective/src/tests.rs @@ -68,8 +68,6 @@ mod mock_democracy { #[pallet::call] impl Pallet { - #[pallet::call_index(0)] - #[pallet::weight(0)] pub fn external_propose_majority(origin: OriginFor) -> DispatchResult { T::ExternalMajorityOrigin::ensure_origin(origin)?; Self::deposit_event(Event::::ExternalProposed); diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index aad1de11d2c7b..fd76fefadff4b 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -735,51 +735,39 @@ mod tests { #[pallet::call] impl Pallet { - #[pallet::call_index(0)] - #[pallet::weight(100)] pub fn some_function(origin: OriginFor) -> DispatchResult { // NOTE: does not make any different. frame_system::ensure_signed(origin)?; Ok(()) } - #[pallet::call_index(1)] #[pallet::weight((200, DispatchClass::Operational))] pub fn some_root_operation(origin: OriginFor) -> DispatchResult { frame_system::ensure_root(origin)?; Ok(()) } - #[pallet::call_index(2)] - #[pallet::weight(0)] pub fn some_unsigned_message(origin: OriginFor) -> DispatchResult { frame_system::ensure_none(origin)?; Ok(()) } - #[pallet::call_index(3)] - #[pallet::weight(0)] pub fn allowed_unsigned(origin: OriginFor) -> DispatchResult { frame_system::ensure_root(origin)?; Ok(()) } - #[pallet::call_index(4)] - #[pallet::weight(0)] pub fn unallowed_unsigned(origin: OriginFor) -> DispatchResult { frame_system::ensure_root(origin)?; Ok(()) } - #[pallet::call_index(5)] #[pallet::weight((0, DispatchClass::Mandatory))] pub fn inherent_call(origin: OriginFor) -> DispatchResult { frame_system::ensure_none(origin)?; Ok(()) } - #[pallet::call_index(6)] - #[pallet::weight(0)] pub fn calculate_storage_root(_origin: OriginFor) -> DispatchResult { let root = sp_io::storage::root(sp_runtime::StateVersion::V1); sp_io::storage::set("storage_root".as_bytes(), &root); diff --git a/frame/support/test/compile_pass/Cargo.toml b/frame/support/test/compile_pass/Cargo.toml index 4466c24d64f15..353847b4b2b7c 100644 --- a/frame/support/test/compile_pass/Cargo.toml +++ b/frame/support/test/compile_pass/Cargo.toml @@ -14,7 +14,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.2.2", default-features = false, features = ["derive"] } scale-info = { version = "2.5.0", default-features = false, features = ["derive"] } -frame-support = { version = "4.0.0-dev", default-features = false, path = "../../" } +renamed-frame-support = { package = "frame-support", version = "4.0.0-dev", default-features = false, path = "../../" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../../../system" } sp-core = { version = "7.0.0", default-features = false, path = "../../../../primitives/core" } sp-runtime = { version = "7.0.0", default-features = false, path = "../../../../primitives/runtime" } @@ -24,7 +24,7 @@ sp-version = { version = "5.0.0", default-features = false, path = "../../../../ default = ["std"] std = [ "codec/std", - "frame-support/std", + "renamed-frame-support/std", "frame-system/std", "scale-info/std", "sp-core/std", diff --git a/frame/support/test/compile_pass/src/lib.rs b/frame/support/test/compile_pass/src/lib.rs index 7e9fdaff27b03..4eaa657b1e486 100644 --- a/frame/support/test/compile_pass/src/lib.rs +++ b/frame/support/test/compile_pass/src/lib.rs @@ -16,15 +16,13 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +//! Test that `construct_runtime!` also works when `frame-support` is renamed in the `Cargo.toml`. + #![cfg_attr(not(feature = "std"), no_std)] -// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256. -#![recursion_limit = "256"] -//! This crate tests that `construct_runtime!` expands the pallet parts -//! correctly even when frame-support is renamed in Cargo.toml -use frame_support::{ +use renamed_frame_support::{ construct_runtime, parameter_types, - traits::{ConstU16, ConstU32, ConstU64}, + traits::{ConstU16, ConstU32, ConstU64, Everything}, }; use sp_core::{sr25519, H256}; use sp_runtime::{ @@ -54,7 +52,7 @@ parameter_types! { } impl frame_system::Config for Runtime { - type BaseCallFilter = frame_support::traits::Everything; + type BaseCallFilter = Everything; type BlockWeights = (); type BlockLength = (); type Index = u128; diff --git a/frame/support/test/pallet/src/lib.rs b/frame/support/test/pallet/src/lib.rs index 82f12ea954614..2dfc94d83187a 100644 --- a/frame/support/test/pallet/src/lib.rs +++ b/frame/support/test/pallet/src/lib.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Testing pallet macro +//! A basic pallet that can be used to test `construct_runtime!`. // Ensure docs are propagated properly by the macros. #![warn(missing_docs)] @@ -24,10 +24,7 @@ pub use pallet::*; #[frame_support::pallet] pub mod pallet { - #[allow(unused_imports)] use frame_support::pallet_prelude::*; - #[allow(unused_imports)] - use frame_system::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(_); @@ -37,7 +34,7 @@ pub mod pallet { /// I'm the documentation #[pallet::storage] - pub type Value = StorageValue; + pub type Value = StorageValue<_, u32>; #[pallet::genesis_config] #[cfg_attr(feature = "std", derive(Default))] diff --git a/frame/support/test/src/lib.rs b/frame/support/test/src/lib.rs index c0b025380dd45..5dccc88471a7b 100644 --- a/frame/support/test/src/lib.rs +++ b/frame/support/test/src/lib.rs @@ -15,48 +15,113 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Test crate for frame_support. Allow to make use of `frame_support::decl_storage`. -//! See tests directory. +//! Minimal pallet without `frame_system::Config`-super trait. // Make sure we fail compilation on warnings #![warn(missing_docs)] #![deny(warnings)] -/// The configuration trait -pub trait Config: 'static { - /// The runtime origin type. - type RuntimeOrigin: codec::Codec + codec::EncodeLike + Default + scale_info::TypeInfo; - /// The block number type. - type BlockNumber: codec::Codec + codec::EncodeLike + Default + scale_info::TypeInfo; - /// The information about the pallet setup in the runtime. - type PalletInfo: frame_support::traits::PalletInfo; - /// The db weights. - type DbWeight: frame_support::traits::Get; -} +pub use frame_support::dispatch::RawOrigin; -frame_support::decl_module! { - /// Some test module - pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self {} -} +pub use self::pallet::*; + +#[frame_support::pallet(dev_mode)] +pub mod pallet { + use super::*; + use crate::{self as frame_system, pallet_prelude::*}; + use frame_support::pallet_prelude::*; -/// A PalletInfo implementation which just panics. -pub struct PanicPalletInfo; + #[pallet::pallet] + pub struct Pallet(_); -impl frame_support::traits::PalletInfo for PanicPalletInfo { - fn index() -> Option { - unimplemented!("PanicPalletInfo mustn't be triggered by tests"); + /// The configuration trait + #[pallet::config] + #[pallet::disable_frame_system_supertrait_check] + pub trait Config: 'static + Eq + Clone { + /// The block number type. + type BlockNumber: Parameter + Member + Default + MaybeSerializeDeserialize + MaxEncodedLen; + /// The account type. + type AccountId: Parameter + Member + MaxEncodedLen; + /// The basic call filter to use in Origin. + type BaseCallFilter: frame_support::traits::Contains; + /// The runtime origin type. + type RuntimeOrigin: Into, Self::RuntimeOrigin>> + + From>; + /// The runtime call type. + type RuntimeCall; + /// The runtime event type. + type RuntimeEvent: Parameter + + Member + + IsType<::RuntimeEvent> + + From>; + /// The information about the pallet setup in the runtime. + type PalletInfo: frame_support::traits::PalletInfo; + /// The db weights. + type DbWeight: Get; } - fn name() -> Option<&'static str> { - unimplemented!("PanicPalletInfo mustn't be triggered by tests"); + + #[pallet::call] + impl Pallet { + /// A noop call. + pub fn noop(_origin: OriginFor) -> DispatchResult { + Ok(()) + } } - fn module_name() -> Option<&'static str> { - unimplemented!("PanicPalletInfo mustn't be triggered by tests"); + + impl Pallet { + /// A empty method. + pub fn deposit_event(_event: impl Into) {} } - fn crate_version() -> Option { - unimplemented!("PanicPalletInfo mustn't be triggered by tests"); + + /// The origin type. + #[pallet::origin] + pub type Origin = RawOrigin<::AccountId>; + + /// The error type. + #[pallet::error] + pub enum Error { + /// Test error documentation + TestError, + /// Error documentation + /// with multiple lines + AnotherError, + /// Required by construct_runtime + CallFiltered, + } + + /// The event type. + #[pallet::event] + pub enum Event { + /// The extrinsic is successful + ExtrinsicSuccess, + /// The extrinsic is failed + ExtrinsicFailed, + /// The ignored error + Ignore(::BlockNumber), } } +/// Ensure that the origin `o` represents the root. Returns `Ok` or an `Err` otherwise. +pub fn ensure_root(o: OuterOrigin) -> Result<(), &'static str> +where + OuterOrigin: Into, OuterOrigin>>, +{ + o.into().map(|_| ()).map_err(|_| "bad origin: expected to be a root origin") +} + +/// Same semantic as [`frame_system`]. +// Note: we cannot use [`frame_system`] here since the pallet does not depend on +// [`frame_system::Config`]. +pub mod pallet_prelude { + pub use crate::ensure_root; + + /// Type alias for the `Origin` associated type of system config. + pub type OriginFor = ::RuntimeOrigin; + + /// Type alias for the `BlockNumber` associated type of system config. + pub type BlockNumberFor = ::BlockNumber; +} + /// Provides an implementation of [`frame_support::traits::Randomness`] that should only be used in /// tests! pub struct TestRandomness(sp_std::marker::PhantomData); diff --git a/frame/support/test/src/pallet_version.rs b/frame/support/test/src/pallet_version.rs deleted file mode 100644 index b015699685a44..0000000000000 --- a/frame/support/test/src/pallet_version.rs +++ /dev/null @@ -1,29 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use 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!()) -} diff --git a/frame/support/test/tests/benchmark_ui/invalid_origin.rs b/frame/support/test/tests/benchmark_ui/invalid_origin.rs index 81cfc39790969..cfb00e88c00c0 100644 --- a/frame/support/test/tests/benchmark_ui/invalid_origin.rs +++ b/frame/support/test/tests/benchmark_ui/invalid_origin.rs @@ -10,7 +10,7 @@ mod benches { #[benchmark] fn bench() { #[extrinsic_call] - thing(1); + noop(1); } } diff --git a/frame/support/test/tests/benchmark_ui/invalid_origin.stderr b/frame/support/test/tests/benchmark_ui/invalid_origin.stderr index 1818442b679a2..115a8206f58a3 100644 --- a/frame/support/test/tests/benchmark_ui/invalid_origin.stderr +++ b/frame/support/test/tests/benchmark_ui/invalid_origin.stderr @@ -1,11 +1,3 @@ -error[E0599]: no variant or associated item named `new_call_variant_thing` found for enum `frame_support_test::Call` in the current scope - --> tests/benchmark_ui/invalid_origin.rs:6:1 - | -6 | #[benchmarks] - | ^^^^^^^^^^^^^ variant or associated item not found in `Call` - | - = note: this error originates in the attribute macro `benchmarks` (in Nightly builds, run with -Z macro-backtrace for more info) - error[E0277]: the trait bound `::RuntimeOrigin: From<{integer}>` is not satisfied --> tests/benchmark_ui/invalid_origin.rs:6:1 | diff --git a/frame/support/test/tests/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index d0b31d71a6fcb..85e790095eb31 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -24,234 +24,233 @@ use codec::MaxEncodedLen; use frame_support::{parameter_types, traits::PalletInfo as _}; use scale_info::TypeInfo; -use sp_core::{sr25519, H256}; +use sp_core::sr25519; use sp_runtime::{ generic, traits::{BlakeTwo256, Verify}, DispatchError, ModuleError, }; -mod system; - -pub trait Currency {} - parameter_types! { pub static IntegrityTestExec: u32 = 0; } +#[frame_support::pallet(dev_mode)] mod module1 { - use super::*; + use self::frame_system::pallet_prelude::*; + use frame_support::pallet_prelude::*; + use frame_support_test as frame_system; - pub trait Config: system::Config {} + #[pallet::pallet] + pub struct Pallet(_); - frame_support::decl_module! { - pub struct Module, I: Instance = DefaultInstance> for enum Call - where origin: ::RuntimeOrigin, system=system - { - #[weight = 0] - pub fn fail(_origin) -> frame_support::dispatch::DispatchResult { - Err(Error::::Something.into()) - } - } + #[pallet::config] + pub trait Config: frame_system::Config { + type RuntimeEvent: From> + + IsType<::RuntimeEvent>; } - #[derive( - Clone, PartialEq, Eq, Debug, codec::Encode, codec::Decode, TypeInfo, MaxEncodedLen, - )] - pub struct Origin(pub core::marker::PhantomData<(T, I)>); - - frame_support::decl_event! { - pub enum Event where - ::AccountId - { - A(AccountId), + #[pallet::call] + impl, I: 'static> Pallet { + pub fn fail(_origin: OriginFor) -> DispatchResult { + Err(Error::::Something.into()) } } - frame_support::decl_error! { - pub enum Error for Module, I: Instance> { - Something - } + #[pallet::origin] + #[derive(Clone, PartialEq, Eq, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)] + #[scale_info(skip_type_params(I))] + pub struct Origin(pub PhantomData<(T, I)>); + + #[pallet::event] + pub enum Event, I: 'static = ()> { + A(::AccountId), } - frame_support::decl_storage! { - trait Store for Module, I: Instance=DefaultInstance> as Module {} + #[pallet::error] + pub enum Error { + Something, } } +#[frame_support::pallet(dev_mode)] mod module2 { + use self::frame_system::pallet_prelude::*; use super::*; + use frame_support::pallet_prelude::*; + use frame_support_test as frame_system; - pub trait Config: system::Config {} + #[pallet::pallet] + pub struct Pallet(_); - frame_support::decl_module! { - pub struct Module for enum Call - where origin: ::RuntimeOrigin, system=system - { - #[weight = 0] - pub fn fail(_origin) -> frame_support::dispatch::DispatchResult { - Err(Error::::Something.into()) - } + #[pallet::config] + pub trait Config: frame_system::Config { + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + } - fn integrity_test() { - IntegrityTestExec::mutate(|i| *i += 1); - } + #[pallet::hooks] + impl Hooks> for Pallet { + fn integrity_test() { + IntegrityTestExec::mutate(|i| *i += 1); } } - #[derive( - Clone, PartialEq, Eq, Debug, codec::Encode, codec::Decode, TypeInfo, MaxEncodedLen, - )] - pub struct Origin; - - frame_support::decl_event! { - pub enum Event { - A, + #[pallet::call] + impl Pallet { + pub fn fail(_origin: OriginFor) -> DispatchResult { + Err(Error::::Something.into()) } } - frame_support::decl_error! { - pub enum Error for Module { - Something - } + #[pallet::origin] + #[derive(Clone, PartialEq, Eq, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)] + pub struct Origin; + + #[pallet::event] + pub enum Event { + A, } - frame_support::decl_storage! { - trait Store for Module as Module {} + #[pallet::error] + pub enum Error { + Something, } } mod nested { use super::*; + #[frame_support::pallet(dev_mode)] pub mod module3 { + use self::frame_system::pallet_prelude::*; use super::*; + use frame_support::pallet_prelude::*; + use frame_support_test as frame_system; + + #[pallet::pallet] + pub struct Pallet(_); - pub trait Config: system::Config {} + #[pallet::config] + pub trait Config: frame_system::Config { + type RuntimeEvent: From> + + IsType<::RuntimeEvent>; + } - frame_support::decl_module! { - pub struct Module for enum Call - where origin: ::RuntimeOrigin, system=system - { - #[weight = 0] - pub fn fail(_origin) -> frame_support::dispatch::DispatchResult { - Err(Error::::Something.into()) - } + #[pallet::hooks] + impl Hooks> for Pallet { + fn integrity_test() { + IntegrityTestExec::mutate(|i| *i += 1); + } + } - fn integrity_test() { - IntegrityTestExec::mutate(|i| *i += 1); - } + #[pallet::call] + impl Pallet { + pub fn fail(_origin: OriginFor) -> DispatchResult { + Err(Error::::Something.into()) } } - #[derive( - Clone, PartialEq, Eq, Debug, codec::Encode, codec::Decode, TypeInfo, MaxEncodedLen, - )] + #[pallet::origin] + #[derive(Clone, PartialEq, Eq, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)] pub struct Origin; - frame_support::decl_event! { - pub enum Event { - A, - } + #[pallet::event] + pub enum Event { + A, } - frame_support::decl_error! { - pub enum Error for Module { - Something - } + #[pallet::error] + pub enum Error { + Something, } - frame_support::decl_storage! { - trait Store for Module as Module {} - add_extra_genesis { - build(|_config| {}) - } + #[pallet::genesis_config] + #[derive(Default)] + pub struct GenesisConfig {} + + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) {} } } } +#[frame_support::pallet(dev_mode)] pub mod module3 { + use self::frame_system::pallet_prelude::*; use super::*; + use frame_support::pallet_prelude::*; + use frame_support_test as frame_system; - pub trait Config: system::Config {} + #[pallet::pallet] + pub struct Pallet(_); - frame_support::decl_module! { - pub struct Module for enum Call - where origin: ::RuntimeOrigin, system=system - { - #[weight = 0] - pub fn fail(_origin) -> frame_support::dispatch::DispatchResult { - Err(Error::::Something.into()) - } - #[weight = 0] - pub fn aux_1(_origin, #[compact] _data: u32) -> frame_support::dispatch::DispatchResult { - unreachable!() - } - #[weight = 0] - pub fn aux_2(_origin, _data: i32, #[compact] _data2: u32) -> frame_support::dispatch::DispatchResult { - unreachable!() - } - #[weight = 0] - fn aux_3(_origin, _data: i32, _data2: String) -> frame_support::dispatch::DispatchResult { - unreachable!() - } - #[weight = 3] - fn aux_4(_origin) -> frame_support::dispatch::DispatchResult { unreachable!() } - #[weight = (5, frame_support::dispatch::DispatchClass::Operational)] - fn operational(_origin) { unreachable!() } + #[pallet::config] + pub trait Config: frame_system::Config { + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + } + + #[pallet::call] + impl Pallet { + pub fn fail(_origin: OriginFor) -> DispatchResult { + Err(Error::::Something.into()) + } + pub fn aux_1(_origin: OriginFor, #[pallet::compact] _data: u32) -> DispatchResult { + unreachable!() + } + pub fn aux_2( + _origin: OriginFor, + _data: i32, + #[pallet::compact] _data2: u32, + ) -> DispatchResult { + unreachable!() + } + #[pallet::weight(0)] + pub fn aux_3(_origin: OriginFor, _data: i32, _data2: String) -> DispatchResult { + unreachable!() + } + #[pallet::weight(3)] + pub fn aux_4(_origin: OriginFor) -> DispatchResult { + unreachable!() + } + #[pallet::weight((5, DispatchClass::Operational))] + pub fn operational(_origin: OriginFor) -> DispatchResult { + unreachable!() } } - #[derive( - Clone, PartialEq, Eq, Debug, codec::Encode, codec::Decode, TypeInfo, MaxEncodedLen, - )] - pub struct Origin(pub core::marker::PhantomData); + #[pallet::origin] + #[derive(Clone, PartialEq, Eq, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)] + pub struct Origin(pub PhantomData); - frame_support::decl_event! { - pub enum Event { - A, - } + #[pallet::event] + pub enum Event { + A, } - frame_support::decl_error! { - pub enum Error for Module { - Something - } + #[pallet::error] + pub enum Error { + Something, } - frame_support::decl_storage! { - trait Store for Module as Module {} - add_extra_genesis { - build(|_config| {}) - } + #[pallet::genesis_config] + #[derive(Default)] + pub struct GenesisConfig {} + + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) {} } } -impl module1::Config for Runtime {} -impl module2::Config for Runtime {} -impl nested::module3::Config for Runtime {} -impl module3::Config for Runtime {} - +pub type BlockNumber = u64; pub type Signature = sr25519::Signature; pub type AccountId = ::Signer; -pub type BlockNumber = u64; -pub type Index = u64; - -fn test_pub() -> AccountId { - AccountId::from_raw([0; 32]) -} +pub type Header = generic::Header; +pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; +pub type Block = generic::Block; -impl system::Config for Runtime { - type BaseCallFilter = frame_support::traits::Everything; - type Hash = H256; - type RuntimeOrigin = RuntimeOrigin; - type BlockNumber = BlockNumber; - type AccountId = AccountId; - type RuntimeEvent = RuntimeEvent; - type PalletInfo = PalletInfo; - type RuntimeCall = RuntimeCall; - type DbWeight = (); -} +use frame_support_test as system; frame_support::construct_runtime!( pub struct Runtime where @@ -261,12 +260,12 @@ frame_support::construct_runtime!( { System: system::{Pallet, Call, Event, Origin} = 30, Module1_1: module1::::{Pallet, Call, Storage, Event, Origin}, - Module2: module2::{Pallet, Call, Storage, Event, Origin}, + Module2: module2::{Pallet, Call, Storage, Event, Origin}, Module1_2: module1::::{Pallet, Call, Storage, Event, Origin}, - NestedModule3: nested::module3::{Pallet, Call, Config, Storage, Event, Origin}, - Module3: self::module3::{Pallet, Call, Config, Storage, Event, Origin}, - Module1_3: module1::::{Pallet, Storage} = 6, - Module1_4: module1::::{Pallet, Call} = 3, + NestedModule3: nested::module3::{Pallet, Call, Config, Storage, Event, Origin}, + Module3: self::module3::{Pallet, Call, Config, Storage, Event, Origin}, + Module1_3: module1::::{Pallet, Storage, Event } = 6, + Module1_4: module1::::{Pallet, Call, Event } = 3, Module1_5: module1::::{Pallet, Event}, Module1_6: module1::::{Pallet, Call, Storage, Event, Origin} = 1, Module1_7: module1::::{Pallet, Call, Storage, Event, Origin}, @@ -275,9 +274,57 @@ frame_support::construct_runtime!( } ); -pub type Header = generic::Header; -pub type Block = generic::Block; -pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; +impl frame_support_test::Config for Runtime { + type BlockNumber = BlockNumber; + type AccountId = AccountId; + type BaseCallFilter = frame_support::traits::Everything; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type PalletInfo = PalletInfo; + type DbWeight = (); +} + +impl module1::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl module1::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl module1::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl module1::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl module1::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl module1::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl module1::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl module1::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl module1::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl module2::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl nested::module3::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl module3::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} + +fn test_pub() -> AccountId { + AccountId::from_raw([0; 32]) +} #[test] fn check_modules_error_type() { @@ -471,12 +518,12 @@ fn call_codec() { #[test] fn call_compact_attr() { use codec::Encode; - let call: module3::Call = module3::Call::aux_1 { _data: 1 }; + let call: module3::Call = module3::Call::aux_1 { data: 1 }; let encoded = call.encode(); assert_eq!(2, encoded.len()); assert_eq!(vec![1, 4], encoded); - let call: module3::Call = module3::Call::aux_2 { _data: 1, _data2: 2 }; + let call: module3::Call = module3::Call::aux_2 { data: 1, data2: 2 }; let encoded = call.encode(); assert_eq!(6, encoded.len()); assert_eq!(vec![2, 1, 0, 0, 0, 8], encoded); @@ -491,7 +538,7 @@ fn call_encode_is_correct_and_decode_works() { let decoded = module3::Call::::decode(&mut &encoded[..]).unwrap(); assert_eq!(decoded, call); - let call: module3::Call = module3::Call::aux_3 { _data: 32, _data2: "hello".into() }; + let call: module3::Call = module3::Call::aux_3 { data: 32, data2: "hello".into() }; let encoded = call.encode(); assert_eq!(vec![3, 32, 0, 0, 0, 20, 104, 101, 108, 108, 111], encoded); let decoded = module3::Call::::decode(&mut &encoded[..]).unwrap(); @@ -594,70 +641,70 @@ fn test_metadata() { calls: Some(meta_type::>().into()), event: Some(meta_type::>().into()), constants: vec![], - error: None, + error: Some(meta_type::>().into()), index: 30, }, PalletMetadata { name: "Module1_1", - storage: Some(PalletStorageMetadata { prefix: "Instance1Module", entries: vec![] }), + storage: Some(PalletStorageMetadata { prefix: "Module1_1", entries: vec![] }), calls: Some(meta_type::>().into()), event: Some(meta_type::>().into()), constants: vec![], - error: None, + error: Some(meta_type::>().into()), index: 31, }, PalletMetadata { name: "Module2", - storage: Some(PalletStorageMetadata { prefix: "Module", entries: vec![] }), + storage: Some(PalletStorageMetadata { prefix: "Module2", entries: vec![] }), calls: Some(meta_type::>().into()), - event: Some(meta_type::().into()), + event: Some(meta_type::>().into()), constants: vec![], - error: None, + error: Some(meta_type::>().into()), index: 32, }, PalletMetadata { name: "Module1_2", - storage: Some(PalletStorageMetadata { prefix: "Instance2Module", entries: vec![] }), + storage: Some(PalletStorageMetadata { prefix: "Module1_2", entries: vec![] }), calls: Some(meta_type::>().into()), event: Some(meta_type::>().into()), constants: vec![], - error: None, + error: Some(meta_type::>().into()), index: 33, }, PalletMetadata { name: "NestedModule3", - storage: Some(PalletStorageMetadata { prefix: "Module", entries: vec![] }), + storage: Some(PalletStorageMetadata { prefix: "NestedModule3", entries: vec![] }), calls: Some(meta_type::>().into()), - event: Some(meta_type::().into()), + event: Some(meta_type::>().into()), constants: vec![], - error: None, + error: Some(meta_type::>().into()), index: 34, }, PalletMetadata { name: "Module3", - storage: Some(PalletStorageMetadata { prefix: "Module", entries: vec![] }), + storage: Some(PalletStorageMetadata { prefix: "Module3", entries: vec![] }), calls: Some(meta_type::>().into()), - event: Some(meta_type::().into()), + event: Some(meta_type::>().into()), constants: vec![], - error: None, + error: Some(meta_type::>().into()), index: 35, }, PalletMetadata { name: "Module1_3", - storage: Some(PalletStorageMetadata { prefix: "Instance3Module", entries: vec![] }), + storage: Some(PalletStorageMetadata { prefix: "Module1_3", entries: vec![] }), calls: None, - event: None, + event: Some(meta_type::>().into()), constants: vec![], - error: None, + error: Some(meta_type::>().into()), index: 6, }, PalletMetadata { name: "Module1_4", storage: None, calls: Some(meta_type::>().into()), - event: None, + event: Some(meta_type::>().into()), constants: vec![], - error: None, + error: Some(meta_type::>().into()), index: 3, }, PalletMetadata { @@ -666,45 +713,43 @@ fn test_metadata() { calls: None, event: Some(meta_type::>().into()), constants: vec![], - error: None, + error: Some(meta_type::>().into()), index: 4, }, PalletMetadata { name: "Module1_6", - storage: Some(PalletStorageMetadata { prefix: "Instance6Module", entries: vec![] }), + storage: Some(PalletStorageMetadata { prefix: "Module1_6", entries: vec![] }), calls: Some(meta_type::>().into()), event: Some(meta_type::>().into()), constants: vec![], - error: None, + error: Some(meta_type::>().into()), index: 1, }, PalletMetadata { name: "Module1_7", - storage: Some(PalletStorageMetadata { prefix: "Instance7Module", entries: vec![] }), + storage: Some(PalletStorageMetadata { prefix: "Module1_7", entries: vec![] }), calls: Some(meta_type::>().into()), - event: Some(PalletEventMetadata { - ty: meta_type::>(), - }), + event: Some(meta_type::>().into()), constants: vec![], - error: None, + error: Some(meta_type::>().into()), index: 2, }, PalletMetadata { name: "Module1_8", - storage: Some(PalletStorageMetadata { prefix: "Instance8Module", entries: vec![] }), + storage: Some(PalletStorageMetadata { prefix: "Module1_8", entries: vec![] }), calls: Some(meta_type::>().into()), event: Some(meta_type::>().into()), constants: vec![], - error: None, + error: Some(meta_type::>().into()), index: 12, }, PalletMetadata { name: "Module1_9", - storage: Some(PalletStorageMetadata { prefix: "Instance9Module", entries: vec![] }), + storage: Some(PalletStorageMetadata { prefix: "Module1_9", entries: vec![] }), calls: Some(meta_type::>().into()), event: Some(meta_type::>().into()), constants: vec![], - error: None, + error: Some(meta_type::>().into()), index: 13, }, ]; @@ -722,6 +767,7 @@ fn test_metadata() { let expected_metadata: RuntimeMetadataPrefixed = RuntimeMetadataLastVersion::new(pallets, extrinsic, meta_type::()).into(); let actual_metadata = Runtime::metadata(); + pretty_assertions::assert_eq!(actual_metadata, expected_metadata); } diff --git a/frame/support/test/tests/construct_runtime_ui/old_unsupported_pallet_decl.rs b/frame/support/test/tests/construct_runtime_ui/old_unsupported_pallet_decl.rs deleted file mode 100644 index 477ca3cc088a2..0000000000000 --- a/frame/support/test/tests/construct_runtime_ui/old_unsupported_pallet_decl.rs +++ /dev/null @@ -1,26 +0,0 @@ -use frame_support::construct_runtime; - -mod pallet_old { - pub trait Config: frame_system::Config {} - - decl_storage! { - trait Store for Module as Example {} - } - - decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin {} - } - -} -construct_runtime! { - pub struct Runtime where - UncheckedExtrinsic = UncheckedExtrinsic, - Block = Block, - NodeBlock = Block, - { - System: frame_system, - OldPallet: pallet_old, - } -} - -fn main() {} diff --git a/frame/support/test/tests/construct_runtime_ui/old_unsupported_pallet_decl.stderr b/frame/support/test/tests/construct_runtime_ui/old_unsupported_pallet_decl.stderr deleted file mode 100644 index b1338e8920f41..0000000000000 --- a/frame/support/test/tests/construct_runtime_ui/old_unsupported_pallet_decl.stderr +++ /dev/null @@ -1,31 +0,0 @@ -error[E0433]: failed to resolve: could not find `tt_default_parts` in `pallet_old` - --> tests/construct_runtime_ui/old_unsupported_pallet_decl.rs:15:1 - | -15 | / construct_runtime! { -16 | | pub struct Runtime where -17 | | UncheckedExtrinsic = UncheckedExtrinsic, -18 | | Block = Block, -... | -23 | | } -24 | | } - | |_^ could not find `tt_default_parts` in `pallet_old` - | - = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: cannot find macro `decl_storage` in this scope - --> tests/construct_runtime_ui/old_unsupported_pallet_decl.rs:6:2 - | -6 | decl_storage! { - | ^^^^^^^^^^^^ - | - = help: consider importing this macro: - frame_support::decl_storage - -error: cannot find macro `decl_module` in this scope - --> tests/construct_runtime_ui/old_unsupported_pallet_decl.rs:10:2 - | -10 | decl_module! { - | ^^^^^^^^^^^ - | - = help: consider importing this macro: - frame_support::decl_module diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_event_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_event_part.stderr index 1ca64f381b005..daf027a5080cb 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_event_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_event_part.stderr @@ -28,7 +28,9 @@ error[E0412]: cannot find type `Event` in module `pallet` | |_^ not found in `pallet` | = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider importing this enum +help: consider importing one of these items + | +1 | use frame_support_test::Event; | 1 | use frame_system::Event; | diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.stderr index dbade9fed2cff..3e4326d3f7372 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.stderr @@ -28,7 +28,9 @@ error[E0412]: cannot find type `Origin` in module `pallet` | |_^ not found in `pallet` | = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider importing this type alias +help: consider importing one of these items + | +1 | use frame_support_test::Origin; | 1 | use frame_system::Origin; | diff --git a/frame/support/test/tests/decl_module_ui.rs b/frame/support/test/tests/decl_module_ui.rs deleted file mode 100644 index 296ae3e586f54..0000000000000 --- a/frame/support/test/tests/decl_module_ui.rs +++ /dev/null @@ -1,32 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#[rustversion::attr(not(stable), ignore)] -#[cfg(not(feature = "disable-ui-tests"))] -#[test] -fn decl_module_ui() { - // Only run the ui tests when `RUN_UI_TESTS` is set. - if std::env::var("RUN_UI_TESTS").is_err() { - return - } - - // As trybuild is using `cargo check`, we don't need the real WASM binaries. - std::env::set_var("SKIP_WASM_BUILD", "1"); - - let t = trybuild::TestCases::new(); - t.compile_fail("tests/decl_module_ui/*.rs"); -} diff --git a/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_integrity_test.rs b/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_integrity_test.rs deleted file mode 100644 index 0f662b96e2b13..0000000000000 --- a/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_integrity_test.rs +++ /dev/null @@ -1,7 +0,0 @@ -frame_support::decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self { - fn integrity_test() {} - - fn integrity_test() {} - } -} diff --git a/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_integrity_test.stderr b/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_integrity_test.stderr deleted file mode 100644 index 4212707599d41..0000000000000 --- a/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_integrity_test.stderr +++ /dev/null @@ -1,19 +0,0 @@ -error: `integrity_test` can only be passed once as input. - --> tests/decl_module_ui/reserved_keyword_two_times_integrity_test.rs:1:1 - | -1 | / frame_support::decl_module! { -2 | | pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self { -3 | | fn integrity_test() {} -4 | | -5 | | fn integrity_test() {} -6 | | } -7 | | } - | |_^ - | - = note: this error originates in the macro `$crate::decl_module` which comes from the expansion of the macro `frame_support::decl_module` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0601]: `main` function not found in crate `$CRATE` - --> tests/decl_module_ui/reserved_keyword_two_times_integrity_test.rs:7:2 - | -7 | } - | ^ consider adding a `main` function to `$DIR/tests/decl_module_ui/reserved_keyword_two_times_integrity_test.rs` diff --git a/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_on_initialize.rs b/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_on_initialize.rs deleted file mode 100644 index ea0746b1c501c..0000000000000 --- a/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_on_initialize.rs +++ /dev/null @@ -1,13 +0,0 @@ -frame_support::decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self { - fn on_initialize() -> Weight { - 0 - } - - fn on_initialize() -> Weight { - 0 - } - } -} - -fn main() {} diff --git a/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_on_initialize.stderr b/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_on_initialize.stderr deleted file mode 100644 index 94bde853e4cc8..0000000000000 --- a/frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_on_initialize.stderr +++ /dev/null @@ -1,13 +0,0 @@ -error: `on_initialize` can only be passed once as input. - --> tests/decl_module_ui/reserved_keyword_two_times_on_initialize.rs:1:1 - | -1 | / frame_support::decl_module! { -2 | | pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self { -3 | | fn on_initialize() -> Weight { -4 | | 0 -... | -10 | | } -11 | | } - | |_^ - | - = note: this error originates in the macro `$crate::decl_module` which comes from the expansion of the macro `frame_support::decl_module` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/frame/support/test/tests/decl_storage.rs b/frame/support/test/tests/decl_storage.rs deleted file mode 100644 index bee1dc83d5589..0000000000000 --- a/frame/support/test/tests/decl_storage.rs +++ /dev/null @@ -1,881 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#[cfg(test)] -// Do not complain about unused `dispatch` and `dispatch_aux`. -#[allow(dead_code)] -mod tests { - use frame_support::metadata_ir::*; - use sp_io::TestExternalities; - - frame_support::decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin, system=frame_support_test {} - } - - pub trait Config: frame_support_test::Config { - type Origin2: codec::Codec - + codec::EncodeLike - + Default - + codec::MaxEncodedLen - + scale_info::TypeInfo; - } - - frame_support::decl_storage! { - generate_storage_info - trait Store for Module as TestStorage { - // non-getters: pub / $default - - /// Hello, this is doc! - U32: Option; - pub PUBU32: Option; - U32MYDEF: Option; - pub PUBU32MYDEF: Option; - - // getters: pub / $default - // we need at least one type which uses T, otherwise GenesisConfig will complain. - GETU32 get(fn u32_getter): T::Origin2; - pub PUBGETU32 get(fn pub_u32_getter): u32; - GETU32WITHCONFIG get(fn u32_getter_with_config) config(): u32; - pub PUBGETU32WITHCONFIG get(fn pub_u32_getter_with_config) config(): u32; - GETU32MYDEF get(fn u32_getter_mydef): Option; - pub PUBGETU32MYDEF get(fn pub_u32_getter_mydef) config(): u32 = 3; - GETU32WITHCONFIGMYDEF get(fn u32_getter_with_config_mydef) config(): u32 = 2; - pub PUBGETU32WITHCONFIGMYDEF get(fn pub_u32_getter_with_config_mydef) config(): u32 = 1; - PUBGETU32WITHCONFIGMYDEFOPT get(fn pub_u32_getter_with_config_mydef_opt) config(): Option; - - GetU32WithBuilder get(fn u32_with_builder) build(|_| 1): u32; - GetOptU32WithBuilderSome get(fn opt_u32_with_builder_some) build(|_| Some(1)): Option; - GetOptU32WithBuilderNone get(fn opt_u32_with_builder_none) build(|_| None): Option; - - // map non-getters: pub / $default - MAPU32 max_values(3): map hasher(blake2_128_concat) u32 => Option<[u8; 4]>; - pub PUBMAPU32: map hasher(blake2_128_concat) u32 => Option<[u8; 4]>; - - // map getters: pub / $default - GETMAPU32 get(fn map_u32_getter): map hasher(blake2_128_concat) u32 => [u8; 4]; - pub PUBGETMAPU32 get(fn pub_map_u32_getter): map hasher(blake2_128_concat) u32 => [u8; 4]; - GETMAPU32MYDEF get(fn map_u32_getter_mydef): - map hasher(blake2_128_concat) u32 => [u8; 4] = *b"mapd"; - pub PUBGETMAPU32MYDEF get(fn pub_map_u32_getter_mydef): - map hasher(blake2_128_concat) u32 => [u8; 4] = *b"pubm"; - - DOUBLEMAP max_values(3): double_map - hasher(blake2_128_concat) u32, hasher(blake2_128_concat) u32 => Option<[u8; 4]>; - - DOUBLEMAP2: double_map - hasher(blake2_128_concat) u32, hasher(blake2_128_concat) u32 => Option<[u8; 4]>; - - COMPLEXTYPE1: (::std::option::Option,); - COMPLEXTYPE2: ([[(u16, Option<()>); 32]; 12], u32); - COMPLEXTYPE3: [u32; 25]; - - NMAP: nmap hasher(blake2_128_concat) u32, hasher(twox_64_concat) u16 => u8; - NMAP2: nmap hasher(blake2_128_concat) u32 => u8; - } - add_extra_genesis { - build(|_| {}); - } - } - - struct TraitImpl {} - - impl frame_support_test::Config for TraitImpl { - type RuntimeOrigin = u32; - type BlockNumber = u32; - type PalletInfo = frame_support_test::PanicPalletInfo; - type DbWeight = (); - } - - impl Config for TraitImpl { - type Origin2 = u32; - } - - fn expected_metadata() -> PalletStorageMetadataIR { - PalletStorageMetadataIR { - prefix: "TestStorage", - entries: vec![ - StorageEntryMetadataIR { - name: "U32", - modifier: StorageEntryModifierIR::Optional, - ty: StorageEntryTypeIR::Plain(scale_info::meta_type::()), - default: vec![0], - docs: vec![" Hello, this is doc!"], - }, - StorageEntryMetadataIR { - name: "PUBU32", - modifier: StorageEntryModifierIR::Optional, - ty: StorageEntryTypeIR::Plain(scale_info::meta_type::()), - default: vec![0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "U32MYDEF", - modifier: StorageEntryModifierIR::Optional, - ty: StorageEntryTypeIR::Plain(scale_info::meta_type::()), - default: vec![0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "PUBU32MYDEF", - modifier: StorageEntryModifierIR::Optional, - ty: StorageEntryTypeIR::Plain(scale_info::meta_type::()), - default: vec![0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "GETU32", - modifier: StorageEntryModifierIR::Default, - ty: StorageEntryTypeIR::Plain(scale_info::meta_type::()), - default: vec![0, 0, 0, 0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "PUBGETU32", - modifier: StorageEntryModifierIR::Default, - ty: StorageEntryTypeIR::Plain(scale_info::meta_type::()), - default: vec![0, 0, 0, 0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "GETU32WITHCONFIG", - modifier: StorageEntryModifierIR::Default, - ty: StorageEntryTypeIR::Plain(scale_info::meta_type::()), - default: vec![0, 0, 0, 0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "PUBGETU32WITHCONFIG", - modifier: StorageEntryModifierIR::Default, - ty: StorageEntryTypeIR::Plain(scale_info::meta_type::()), - default: vec![0, 0, 0, 0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "GETU32MYDEF", - modifier: StorageEntryModifierIR::Optional, - ty: StorageEntryTypeIR::Plain(scale_info::meta_type::()), - default: vec![0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "PUBGETU32MYDEF", - modifier: StorageEntryModifierIR::Default, - ty: StorageEntryTypeIR::Plain(scale_info::meta_type::()), - default: vec![3, 0, 0, 0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "GETU32WITHCONFIGMYDEF", - modifier: StorageEntryModifierIR::Default, - ty: StorageEntryTypeIR::Plain(scale_info::meta_type::()), - default: vec![2, 0, 0, 0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "PUBGETU32WITHCONFIGMYDEF", - modifier: StorageEntryModifierIR::Default, - ty: StorageEntryTypeIR::Plain(scale_info::meta_type::()), - default: vec![1, 0, 0, 0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "PUBGETU32WITHCONFIGMYDEFOPT", - modifier: StorageEntryModifierIR::Optional, - ty: StorageEntryTypeIR::Plain(scale_info::meta_type::()), - default: vec![0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "GetU32WithBuilder", - modifier: StorageEntryModifierIR::Default, - ty: StorageEntryTypeIR::Plain(scale_info::meta_type::()), - default: vec![0, 0, 0, 0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "GetOptU32WithBuilderSome", - modifier: StorageEntryModifierIR::Optional, - ty: StorageEntryTypeIR::Plain(scale_info::meta_type::()), - default: vec![0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "GetOptU32WithBuilderNone", - modifier: StorageEntryModifierIR::Optional, - ty: StorageEntryTypeIR::Plain(scale_info::meta_type::()), - default: vec![0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "MAPU32", - modifier: StorageEntryModifierIR::Optional, - ty: StorageEntryTypeIR::Map { - hashers: vec![StorageHasherIR::Blake2_128Concat], - key: scale_info::meta_type::(), - value: scale_info::meta_type::<[u8; 4]>(), - }, - default: vec![0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "PUBMAPU32", - modifier: StorageEntryModifierIR::Optional, - ty: StorageEntryTypeIR::Map { - hashers: vec![StorageHasherIR::Blake2_128Concat], - key: scale_info::meta_type::(), - value: scale_info::meta_type::<[u8; 4]>(), - }, - default: vec![0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "GETMAPU32", - modifier: StorageEntryModifierIR::Default, - ty: StorageEntryTypeIR::Map { - hashers: vec![StorageHasherIR::Blake2_128Concat], - key: scale_info::meta_type::(), - value: scale_info::meta_type::<[u8; 4]>(), - }, - default: vec![0, 0, 0, 0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "PUBGETMAPU32", - modifier: StorageEntryModifierIR::Default, - ty: StorageEntryTypeIR::Map { - hashers: vec![StorageHasherIR::Blake2_128Concat], - key: scale_info::meta_type::(), - value: scale_info::meta_type::<[u8; 4]>(), - }, - default: vec![0, 0, 0, 0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "GETMAPU32MYDEF", - modifier: StorageEntryModifierIR::Default, - ty: StorageEntryTypeIR::Map { - hashers: vec![StorageHasherIR::Blake2_128Concat], - key: scale_info::meta_type::(), - value: scale_info::meta_type::<[u8; 4]>(), - }, - default: vec![109, 97, 112, 100], // "map" - docs: vec![], - }, - StorageEntryMetadataIR { - name: "PUBGETMAPU32MYDEF", - modifier: StorageEntryModifierIR::Default, - ty: StorageEntryTypeIR::Map { - hashers: vec![StorageHasherIR::Blake2_128Concat], - key: scale_info::meta_type::(), - value: scale_info::meta_type::<[u8; 4]>(), - }, - default: vec![112, 117, 98, 109], // "pubmap" - docs: vec![], - }, - StorageEntryMetadataIR { - name: "DOUBLEMAP", - modifier: StorageEntryModifierIR::Optional, - ty: StorageEntryTypeIR::Map { - hashers: vec![ - StorageHasherIR::Blake2_128Concat, - StorageHasherIR::Blake2_128Concat, - ], - key: scale_info::meta_type::<(u32, u32)>(), - value: scale_info::meta_type::<[u8; 4]>(), - }, - default: vec![0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "DOUBLEMAP2", - modifier: StorageEntryModifierIR::Optional, - ty: StorageEntryTypeIR::Map { - hashers: vec![ - StorageHasherIR::Blake2_128Concat, - StorageHasherIR::Blake2_128Concat, - ], - key: scale_info::meta_type::<(u32, u32)>(), - value: scale_info::meta_type::<[u8; 4]>(), - }, - default: vec![0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "COMPLEXTYPE1", - modifier: StorageEntryModifierIR::Default, - ty: StorageEntryTypeIR::Plain(scale_info::meta_type::<(Option,)>()), - default: vec![0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "COMPLEXTYPE2", - modifier: StorageEntryModifierIR::Default, - ty: StorageEntryTypeIR::Plain(scale_info::meta_type::<( - [[(u16, Option<()>); 32]; 12], - u32, - )>()), - default: [0u8; 1156].to_vec(), - docs: vec![], - }, - StorageEntryMetadataIR { - name: "COMPLEXTYPE3", - modifier: StorageEntryModifierIR::Default, - ty: StorageEntryTypeIR::Plain(scale_info::meta_type::<[u32; 25]>()), - default: [0u8; 100].to_vec(), - docs: vec![], - }, - StorageEntryMetadataIR { - name: "NMAP", - modifier: StorageEntryModifierIR::Default, - ty: StorageEntryTypeIR::Map { - key: scale_info::meta_type::<(u32, u16)>(), - hashers: vec![ - StorageHasherIR::Blake2_128Concat, - StorageHasherIR::Twox64Concat, - ], - value: scale_info::meta_type::(), - }, - default: vec![0], - docs: vec![], - }, - StorageEntryMetadataIR { - name: "NMAP2", - modifier: StorageEntryModifierIR::Default, - ty: StorageEntryTypeIR::Map { - key: scale_info::meta_type::(), - hashers: vec![StorageHasherIR::Blake2_128Concat], - value: scale_info::meta_type::(), - }, - default: vec![0], - docs: vec![], - }, - ], - } - } - - #[test] - fn storage_info() { - use frame_support::{ - storage::storage_prefix as prefix, - traits::{StorageInfo, StorageInfoTrait}, - }; - - pretty_assertions::assert_eq!( - >::storage_info(), - vec![ - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"U32".to_vec(), - prefix: prefix(b"TestStorage", b"U32").to_vec(), - max_values: Some(1), - max_size: Some(4), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"PUBU32".to_vec(), - prefix: prefix(b"TestStorage", b"PUBU32").to_vec(), - max_values: Some(1), - max_size: Some(4), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"U32MYDEF".to_vec(), - prefix: prefix(b"TestStorage", b"U32MYDEF").to_vec(), - max_values: Some(1), - max_size: Some(4), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"PUBU32MYDEF".to_vec(), - prefix: prefix(b"TestStorage", b"PUBU32MYDEF").to_vec(), - max_values: Some(1), - max_size: Some(4), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"GETU32".to_vec(), - prefix: prefix(b"TestStorage", b"GETU32").to_vec(), - max_values: Some(1), - max_size: Some(4), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"PUBGETU32".to_vec(), - prefix: prefix(b"TestStorage", b"PUBGETU32").to_vec(), - max_values: Some(1), - max_size: Some(4), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"GETU32WITHCONFIG".to_vec(), - prefix: prefix(b"TestStorage", b"GETU32WITHCONFIG").to_vec(), - max_values: Some(1), - max_size: Some(4), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"PUBGETU32WITHCONFIG".to_vec(), - prefix: prefix(b"TestStorage", b"PUBGETU32WITHCONFIG").to_vec(), - max_values: Some(1), - max_size: Some(4), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"GETU32MYDEF".to_vec(), - prefix: prefix(b"TestStorage", b"GETU32MYDEF").to_vec(), - max_values: Some(1), - max_size: Some(4), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"PUBGETU32MYDEF".to_vec(), - prefix: prefix(b"TestStorage", b"PUBGETU32MYDEF").to_vec(), - max_values: Some(1), - max_size: Some(4), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"GETU32WITHCONFIGMYDEF".to_vec(), - prefix: prefix(b"TestStorage", b"GETU32WITHCONFIGMYDEF").to_vec(), - max_values: Some(1), - max_size: Some(4), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"PUBGETU32WITHCONFIGMYDEF".to_vec(), - prefix: prefix(b"TestStorage", b"PUBGETU32WITHCONFIGMYDEF").to_vec(), - max_values: Some(1), - max_size: Some(4), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"PUBGETU32WITHCONFIGMYDEFOPT".to_vec(), - prefix: prefix(b"TestStorage", b"PUBGETU32WITHCONFIGMYDEFOPT").to_vec(), - max_values: Some(1), - max_size: Some(4), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"GetU32WithBuilder".to_vec(), - prefix: prefix(b"TestStorage", b"GetU32WithBuilder").to_vec(), - max_values: Some(1), - max_size: Some(4), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"GetOptU32WithBuilderSome".to_vec(), - prefix: prefix(b"TestStorage", b"GetOptU32WithBuilderSome").to_vec(), - max_values: Some(1), - max_size: Some(4), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"GetOptU32WithBuilderNone".to_vec(), - prefix: prefix(b"TestStorage", b"GetOptU32WithBuilderNone").to_vec(), - max_values: Some(1), - max_size: Some(4), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"MAPU32".to_vec(), - prefix: prefix(b"TestStorage", b"MAPU32").to_vec(), - max_values: Some(3), - max_size: Some(8 + 16), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"PUBMAPU32".to_vec(), - prefix: prefix(b"TestStorage", b"PUBMAPU32").to_vec(), - max_values: None, - max_size: Some(8 + 16), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"GETMAPU32".to_vec(), - prefix: prefix(b"TestStorage", b"GETMAPU32").to_vec(), - max_values: None, - max_size: Some(8 + 16), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"PUBGETMAPU32".to_vec(), - prefix: prefix(b"TestStorage", b"PUBGETMAPU32").to_vec(), - max_values: None, - max_size: Some(8 + 16), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"GETMAPU32MYDEF".to_vec(), - prefix: prefix(b"TestStorage", b"GETMAPU32MYDEF").to_vec(), - max_values: None, - max_size: Some(8 + 16), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"PUBGETMAPU32MYDEF".to_vec(), - prefix: prefix(b"TestStorage", b"PUBGETMAPU32MYDEF").to_vec(), - max_values: None, - max_size: Some(8 + 16), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"DOUBLEMAP".to_vec(), - prefix: prefix(b"TestStorage", b"DOUBLEMAP").to_vec(), - max_values: Some(3), - max_size: Some(12 + 16 + 16), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"DOUBLEMAP2".to_vec(), - prefix: prefix(b"TestStorage", b"DOUBLEMAP2").to_vec(), - max_values: None, - max_size: Some(12 + 16 + 16), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"COMPLEXTYPE1".to_vec(), - prefix: prefix(b"TestStorage", b"COMPLEXTYPE1").to_vec(), - max_values: Some(1), - max_size: Some(5), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"COMPLEXTYPE2".to_vec(), - prefix: prefix(b"TestStorage", b"COMPLEXTYPE2").to_vec(), - max_values: Some(1), - max_size: Some(1156), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"COMPLEXTYPE3".to_vec(), - prefix: prefix(b"TestStorage", b"COMPLEXTYPE3").to_vec(), - max_values: Some(1), - max_size: Some(100), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"NMAP".to_vec(), - prefix: prefix(b"TestStorage", b"NMAP").to_vec(), - max_values: None, - max_size: Some(16 + 4 + 8 + 2 + 1), - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"NMAP2".to_vec(), - prefix: prefix(b"TestStorage", b"NMAP2").to_vec(), - max_values: None, - max_size: Some(16 + 4 + 1), - }, - ], - ); - } - - #[test] - fn store_metadata() { - let metadata = Module::::storage_metadata(); - pretty_assertions::assert_eq!(expected_metadata(), metadata); - } - - #[test] - fn check_genesis_config() { - let config = GenesisConfig::default(); - assert_eq!(config.u32_getter_with_config, 0u32); - assert_eq!(config.pub_u32_getter_with_config, 0u32); - - assert_eq!(config.pub_u32_getter_mydef, 3u32); - assert_eq!(config.u32_getter_with_config_mydef, 2u32); - assert_eq!(config.pub_u32_getter_with_config_mydef, 1u32); - assert_eq!(config.pub_u32_getter_with_config_mydef_opt, 0u32); - } - - #[test] - fn check_builder_config() { - let config = GenesisConfig::default(); - let storage = config.build_storage().unwrap(); - TestExternalities::from(storage).execute_with(|| { - assert_eq!(Module::::u32_with_builder(), 1); - assert_eq!(Module::::opt_u32_with_builder_some(), Some(1)); - assert_eq!(Module::::opt_u32_with_builder_none(), None); - }) - } -} - -#[cfg(test)] -#[allow(dead_code)] -mod test2 { - pub trait Config: frame_support_test::Config {} - - frame_support::decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin, system=frame_support_test {} - } - - type PairOf = (T, T); - - frame_support::decl_storage! { - trait Store for Module as TestStorage { - SingleDef : u32; - PairDef : PairOf; - Single : Option; - Pair : (u32, u32); - } - add_extra_genesis { - config(_marker) : ::std::marker::PhantomData; - config(extra_field) : u32 = 32; - build(|_| {}); - } - } - - struct TraitImpl {} - - impl frame_support_test::Config for TraitImpl { - type RuntimeOrigin = u32; - type BlockNumber = u32; - type PalletInfo = frame_support_test::PanicPalletInfo; - type DbWeight = (); - } - - impl Config for TraitImpl {} - - #[test] - fn storage_info() { - use frame_support::{ - storage::storage_prefix as prefix, - traits::{StorageInfo, StorageInfoTrait}, - }; - pretty_assertions::assert_eq!( - >::storage_info(), - vec![ - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"SingleDef".to_vec(), - prefix: prefix(b"TestStorage", b"SingleDef").to_vec(), - max_values: Some(1), - max_size: None, - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"PairDef".to_vec(), - prefix: prefix(b"TestStorage", b"PairDef").to_vec(), - max_values: Some(1), - max_size: None, - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"Single".to_vec(), - prefix: prefix(b"TestStorage", b"Single").to_vec(), - max_values: Some(1), - max_size: None, - }, - StorageInfo { - pallet_name: b"TestStorage".to_vec(), - storage_name: b"Pair".to_vec(), - prefix: prefix(b"TestStorage", b"Pair").to_vec(), - max_values: Some(1), - max_size: None, - }, - ], - ); - } -} - -#[cfg(test)] -#[allow(dead_code)] -mod test3 { - pub trait Config: frame_support_test::Config {} - - frame_support::decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin, system=frame_support_test {} - } - frame_support::decl_storage! { - trait Store for Module as Test { - Foo get(fn foo) config(initial_foo): u32; - } - } - - type PairOf = (T, T); - - struct TraitImpl {} - - impl frame_support_test::Config for TraitImpl { - type RuntimeOrigin = u32; - type BlockNumber = u32; - type PalletInfo = frame_support_test::PanicPalletInfo; - type DbWeight = (); - } - - impl Config for TraitImpl {} -} - -#[cfg(test)] -#[allow(dead_code)] -mod test_append_and_len { - use codec::{Decode, Encode}; - use sp_io::TestExternalities; - - pub trait Config: frame_support_test::Config {} - - frame_support::decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin, system=frame_support_test {} - } - - #[derive(PartialEq, Eq, Clone, Encode, Decode, scale_info::TypeInfo)] - struct NoDef(u32); - - frame_support::decl_storage! { - trait Store for Module as Test { - NoDefault: Option; - - JustVec: Vec; - JustVecWithDefault: Vec = vec![6, 9]; - OptionVec: Option>; - - MapVec: map hasher(blake2_128_concat) u32 => Vec; - MapVecWithDefault: map hasher(blake2_128_concat) u32 => Vec = vec![6, 9]; - OptionMapVec: map hasher(blake2_128_concat) u32 => Option>; - - DoubleMapVec: double_map hasher(blake2_128_concat) u32, hasher(blake2_128_concat) u32 => Vec; - DoubleMapVecWithDefault: double_map hasher(blake2_128_concat) u32, hasher(blake2_128_concat) u32 => Vec = vec![6, 9]; - OptionDoubleMapVec: double_map hasher(blake2_128_concat) u32, hasher(blake2_128_concat) u32 => Option>; - } - } - - struct Test {} - - impl frame_support_test::Config for Test { - type RuntimeOrigin = u32; - type BlockNumber = u32; - type PalletInfo = frame_support_test::PanicPalletInfo; - type DbWeight = (); - } - - impl Config for Test {} - - #[test] - fn default_for_option() { - TestExternalities::default().execute_with(|| { - assert_eq!(OptionVec::get(), None); - assert!(JustVec::get().is_empty()); - }); - } - - #[test] - fn append_works() { - TestExternalities::default().execute_with(|| { - for val in &[1, 2, 3, 4, 5] { - MapVec::append(1, val); - } - assert_eq!(MapVec::get(1), vec![1, 2, 3, 4, 5]); - - MapVec::remove(1); - MapVec::append(1, 1); - assert_eq!(MapVec::get(1), vec![1]); - - for val in &[1, 2, 3, 4, 5] { - JustVec::append(val); - } - assert_eq!(JustVec::get(), vec![1, 2, 3, 4, 5]); - - JustVec::kill(); - JustVec::append(1); - assert_eq!(JustVec::get(), vec![1]); - }); - } - - #[test] - fn append_overwrites_invalid_data() { - TestExternalities::default().execute_with(|| { - let key = JustVec::hashed_key(); - // Set it to some invalid value. - frame_support::storage::unhashed::put_raw(&key, b"1"); - assert!(JustVec::get().is_empty()); - assert_eq!(frame_support::storage::unhashed::get_raw(&key), Some(b"1".to_vec())); - - JustVec::append(1); - JustVec::append(2); - assert_eq!(JustVec::get(), vec![1, 2]); - }); - } - - #[test] - fn append_overwrites_default() { - TestExternalities::default().execute_with(|| { - assert_eq!(JustVecWithDefault::get(), vec![6, 9]); - JustVecWithDefault::append(1); - assert_eq!(JustVecWithDefault::get(), vec![1]); - - assert_eq!(MapVecWithDefault::get(0), vec![6, 9]); - MapVecWithDefault::append(0, 1); - assert_eq!(MapVecWithDefault::get(0), vec![1]); - - assert_eq!(OptionVec::get(), None); - OptionVec::append(1); - assert_eq!(OptionVec::get(), Some(vec![1])); - }); - } - - #[test] - fn len_works() { - TestExternalities::default().execute_with(|| { - JustVec::put(&vec![1, 2, 3, 4]); - OptionVec::put(&vec![1, 2, 3, 4, 5]); - MapVec::insert(1, &vec![1, 2, 3, 4, 5, 6]); - DoubleMapVec::insert(0, 1, &vec![1, 2]); - - assert_eq!(JustVec::decode_len().unwrap(), 4); - assert_eq!(OptionVec::decode_len().unwrap(), 5); - assert_eq!(MapVec::decode_len(1).unwrap(), 6); - assert_eq!(DoubleMapVec::decode_len(0, 1).unwrap(), 2); - }); - } - - // `decode_len` should always return `None` for default assigments - // in `decl_storage!`. - #[test] - fn len_works_ignores_default_assignment() { - TestExternalities::default().execute_with(|| { - // vec - assert!(JustVec::get().is_empty()); - assert_eq!(JustVec::decode_len(), None); - - assert_eq!(JustVecWithDefault::get(), vec![6, 9]); - assert_eq!(JustVecWithDefault::decode_len(), None); - - assert_eq!(OptionVec::get(), None); - assert_eq!(OptionVec::decode_len(), None); - - // map - assert!(MapVec::get(0).is_empty()); - assert_eq!(MapVec::decode_len(0), None); - - assert_eq!(MapVecWithDefault::get(0), vec![6, 9]); - assert_eq!(MapVecWithDefault::decode_len(0), None); - - assert_eq!(OptionMapVec::get(0), None); - assert_eq!(OptionMapVec::decode_len(0), None); - - // Double map - assert!(DoubleMapVec::get(0, 0).is_empty()); - assert_eq!(DoubleMapVec::decode_len(0, 1), None); - - assert_eq!(DoubleMapVecWithDefault::get(0, 0), vec![6, 9]); - assert_eq!(DoubleMapVecWithDefault::decode_len(0, 1), None); - - assert_eq!(OptionDoubleMapVec::get(0, 0), None); - assert_eq!(OptionDoubleMapVec::decode_len(0, 1), None); - }); - } -} diff --git a/frame/support/test/tests/decl_storage_ui.rs b/frame/support/test/tests/decl_storage_ui.rs deleted file mode 100644 index 1414c8a994520..0000000000000 --- a/frame/support/test/tests/decl_storage_ui.rs +++ /dev/null @@ -1,32 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#[rustversion::attr(not(stable), ignore)] -#[cfg(not(feature = "disable-ui-tests"))] -#[test] -fn decl_storage_ui() { - // Only run the ui tests when `RUN_UI_TESTS` is set. - if std::env::var("RUN_UI_TESTS").is_err() { - return - } - - // As trybuild is using `cargo check`, we don't need the real WASM binaries. - std::env::set_var("SKIP_WASM_BUILD", "1"); - - let t = trybuild::TestCases::new(); - t.compile_fail("tests/decl_storage_ui/*.rs"); -} diff --git a/frame/support/test/tests/decl_storage_ui/config_duplicate.rs b/frame/support/test/tests/decl_storage_ui/config_duplicate.rs deleted file mode 100644 index a6e1bfad5836b..0000000000000 --- a/frame/support/test/tests/decl_storage_ui/config_duplicate.rs +++ /dev/null @@ -1,31 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -pub trait Config: frame_support_test::Config {} - -frame_support::decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin, system=frame_support_test {} -} - -frame_support::decl_storage!{ - trait Store for Module as FinalKeysNone { - pub Value config(value): u32; - pub Value2 config(value): u32; - } -} - -fn main() {} diff --git a/frame/support/test/tests/decl_storage_ui/config_duplicate.stderr b/frame/support/test/tests/decl_storage_ui/config_duplicate.stderr deleted file mode 100644 index f6303f277b56b..0000000000000 --- a/frame/support/test/tests/decl_storage_ui/config_duplicate.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: `config()`/`get()` with the same name already defined. - --> $DIR/config_duplicate.rs:27:21 - | -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 deleted file mode 100644 index c40dd0e44f11b..0000000000000 --- a/frame/support/test/tests/decl_storage_ui/config_get_duplicate.rs +++ /dev/null @@ -1,31 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -pub trait Config: frame_support_test::Config {} - -frame_support::decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin, system=frame_support_test {} -} - -frame_support::decl_storage!{ - trait Store for Module as FinalKeysNone { - pub Value get(fn value) config(): u32; - pub Value2 config(value): u32; - } -} - -fn main() {} 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 deleted file mode 100644 index 9377b718c0660..0000000000000 --- a/frame/support/test/tests/decl_storage_ui/config_get_duplicate.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: `config()`/`get()` with the same name already defined. - --> $DIR/config_get_duplicate.rs:27:21 - | -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 deleted file mode 100644 index 23c89d276ef39..0000000000000 --- a/frame/support/test/tests/decl_storage_ui/get_duplicate.rs +++ /dev/null @@ -1,31 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -pub trait Config: frame_support_test::Config {} - -frame_support::decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin, system=frame_support_test {} -} - -frame_support::decl_storage!{ - trait Store for Module as FinalKeysNone { - pub Value get(fn value) config(): u32; - pub Value2 get(fn value) config(): u32; - } -} - -fn main() {} diff --git a/frame/support/test/tests/decl_storage_ui/get_duplicate.stderr b/frame/support/test/tests/decl_storage_ui/get_duplicate.stderr deleted file mode 100644 index 0039b10fb43b6..0000000000000 --- a/frame/support/test/tests/decl_storage_ui/get_duplicate.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: `config()`/`get()` with the same name already defined. - --> $DIR/get_duplicate.rs:27:21 - | -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 9e1d6c0876740..610f6532c52d0 100644 --- a/frame/support/test/tests/final_keys.rs +++ b/frame/support/test/tests/final_keys.rs @@ -16,65 +16,166 @@ // limitations under the License. use codec::Encode; -use frame_support::{ - storage::unhashed, StorageDoubleMap, StorageMap, StoragePrefixedMap, StorageValue, -}; +use frame_support::{storage::unhashed, StoragePrefixedMap}; +use sp_core::sr25519; use sp_io::{ hashing::{blake2_128, twox_128, twox_64}, TestExternalities, }; +use sp_runtime::{ + generic, + traits::{BlakeTwo256, Verify}, +}; +#[frame_support::pallet] mod no_instance { - pub trait Config: frame_support_test::Config {} - - frame_support::decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin, system=frame_support_test {} + use super::*; + use frame_support::pallet_prelude::*; + use frame_support_test as frame_system; + + #[pallet::pallet] + pub struct Pallet(PhantomData); + + #[pallet::config] + pub trait Config: frame_system::Config {} + + #[pallet::call] + impl Pallet {} + + #[pallet::storage] + pub type Value = StorageValue<_, u32, ValueQuery>; + + #[pallet::storage] + pub type Map = StorageMap<_, Blake2_128Concat, u32, u32, ValueQuery>; + #[pallet::storage] + pub type Map2 = StorageMap<_, Twox64Concat, u32, u32, ValueQuery>; + + #[pallet::storage] + pub type DoubleMap = + StorageDoubleMap<_, Blake2_128Concat, u32, Blake2_128Concat, u32, u32, ValueQuery>; + #[pallet::storage] + pub type DoubleMap2 = + StorageDoubleMap<_, Twox64Concat, u32, Twox64Concat, u32, u32, ValueQuery>; + + #[pallet::storage] + #[pallet::getter(fn test_generic_value)] + pub type TestGenericValue = StorageValue<_, T::BlockNumber, OptionQuery>; + #[pallet::storage] + #[pallet::getter(fn foo2)] + pub type TestGenericDoubleMap = StorageDoubleMap< + _, + Blake2_128Concat, + u32, + Blake2_128Concat, + T::BlockNumber, + u32, + ValueQuery, + >; + + #[pallet::genesis_config] + pub struct GenesisConfig { + pub value: u32, + pub test_generic_value: T::BlockNumber, + pub test_generic_double_map: Vec<(u32, T::BlockNumber, u32)>, } - frame_support::decl_storage! { - trait Store for Module as FinalKeysNone { - pub Value config(value): u32; - - pub Map: map hasher(blake2_128_concat) u32 => u32; - pub Map2: map hasher(twox_64_concat) u32 => u32; - - pub DoubleMap: double_map hasher(blake2_128_concat) u32, hasher(blake2_128_concat) u32 => u32; - pub DoubleMap2: double_map hasher(twox_64_concat) u32, hasher(twox_64_concat) u32 => u32; + impl Default for GenesisConfig { + fn default() -> Self { + Self { + value: Default::default(), + test_generic_value: Default::default(), + test_generic_double_map: Default::default(), + } + } + } - pub TestGenericValue get(fn test_generic_value) config(): Option; - pub TestGenericDoubleMap get(fn foo2) config(test_generic_double_map): - double_map hasher(blake2_128_concat) u32, hasher(blake2_128_concat) T::BlockNumber => Option; + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) { + >::put(self.value); + >::put(&self.test_generic_value); + for (k1, k2, v) in &self.test_generic_double_map { + >::insert(k1, k2, v); + } } } } +#[frame_support::pallet] mod instance { - pub trait Config: frame_support_test::Config {} - - frame_support::decl_module! { - pub struct Module, I: Instance = DefaultInstance> - for enum Call where origin: T::RuntimeOrigin, system=frame_support_test {} + use super::*; + use frame_support::pallet_prelude::*; + use frame_support_test as frame_system; + + #[pallet::pallet] + pub struct Pallet(PhantomData<(T, I)>); + + #[pallet::config] + pub trait Config: frame_system::Config {} + + #[pallet::call] + impl, I: 'static> Pallet {} + + #[pallet::storage] + pub type Value, I: 'static = ()> = StorageValue<_, u32, ValueQuery>; + + #[pallet::storage] + pub type Map, I: 'static = ()> = + StorageMap<_, Blake2_128Concat, u32, u32, ValueQuery>; + #[pallet::storage] + pub type Map2, I: 'static = ()> = + StorageMap<_, Twox64Concat, u32, u32, ValueQuery>; + + #[pallet::storage] + pub type DoubleMap, I: 'static = ()> = + StorageDoubleMap<_, Blake2_128Concat, u32, Blake2_128Concat, u32, u32, ValueQuery>; + #[pallet::storage] + pub type DoubleMap2, I: 'static = ()> = + StorageDoubleMap<_, Twox64Concat, u32, Twox64Concat, u32, u32, ValueQuery>; + + #[pallet::storage] + #[pallet::getter(fn test_generic_value)] + pub type TestGenericValue, I: 'static = ()> = + StorageValue<_, T::BlockNumber, OptionQuery>; + #[pallet::storage] + #[pallet::getter(fn foo2)] + pub type TestGenericDoubleMap, I: 'static = ()> = StorageDoubleMap< + _, + Blake2_128Concat, + u32, + Blake2_128Concat, + T::BlockNumber, + u32, + ValueQuery, + >; + + #[pallet::genesis_config] + pub struct GenesisConfig, I: 'static = ()> { + pub value: u32, + pub test_generic_value: T::BlockNumber, + pub test_generic_double_map: Vec<(u32, T::BlockNumber, u32)>, + pub phantom: PhantomData, } - frame_support::decl_storage! { - trait Store for Module, I: Instance = DefaultInstance> - as FinalKeysSome - { - pub Value config(value): u32; - - pub Map: map hasher(blake2_128_concat) u32 => u32; - pub Map2: map hasher(twox_64_concat) u32 => u32; - - pub DoubleMap: double_map hasher(blake2_128_concat) u32, hasher(blake2_128_concat) u32 => u32; - pub DoubleMap2: double_map hasher(twox_64_concat) u32, hasher(twox_64_concat) u32 => u32; - - pub TestGenericValue get(fn test_generic_value) config(): Option; - pub TestGenericDoubleMap get(fn foo2) config(test_generic_double_map): - double_map hasher(blake2_128_concat) u32, hasher(blake2_128_concat) T::BlockNumber => Option; + impl, I: 'static> Default for GenesisConfig { + fn default() -> Self { + Self { + value: Default::default(), + test_generic_value: Default::default(), + test_generic_double_map: Default::default(), + phantom: Default::default(), + } } - add_extra_genesis { - // See `decl_storage` limitation. - config(phantom): core::marker::PhantomData; + } + + #[pallet::genesis_build] + impl, I: 'static> GenesisBuild for GenesisConfig { + fn build(&self) { + >::put(self.value); + >::put(&self.test_generic_value); + for (k1, k2, v) in &self.test_generic_double_map { + >::insert(k1, k2, v); + } } } } @@ -91,107 +192,144 @@ fn blake2_128_concat(d: &[u8]) -> Vec { v } +pub type BlockNumber = u32; +pub type Signature = sr25519::Signature; +pub type AccountId = ::Signer; +pub type Header = generic::Header; +pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; +pub type Block = generic::Block; + +frame_support::construct_runtime!( + pub enum Runtime + where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_support_test, + FinalKeysNone: no_instance, + FinalKeysSome: instance, + Instance2FinalKeysSome: instance::, + } +); + +impl frame_support_test::Config for Runtime { + type BlockNumber = BlockNumber; + type AccountId = AccountId; + type BaseCallFilter = frame_support::traits::Everything; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type PalletInfo = PalletInfo; + type DbWeight = (); +} + +impl no_instance::Config for Runtime {} + +impl instance::Config for Runtime {} +impl instance::Config for Runtime {} + #[test] fn final_keys_no_instance() { TestExternalities::default().execute_with(|| { - no_instance::Value::put(1); + >::put(1); let k = [twox_128(b"FinalKeysNone"), twox_128(b"Value")].concat(); assert_eq!(unhashed::get::(&k), Some(1u32)); - no_instance::Map::insert(1, 2); + >::insert(1, 2); let mut k = [twox_128(b"FinalKeysNone"), twox_128(b"Map")].concat(); k.extend(1u32.using_encoded(blake2_128_concat)); assert_eq!(unhashed::get::(&k), Some(2u32)); - assert_eq!(&k[..32], &::final_prefix()); + assert_eq!(&k[..32], &>::final_prefix()); - no_instance::Map2::insert(1, 2); + >::insert(1, 2); let mut k = [twox_128(b"FinalKeysNone"), twox_128(b"Map2")].concat(); k.extend(1u32.using_encoded(twox_64_concat)); assert_eq!(unhashed::get::(&k), Some(2u32)); - assert_eq!(&k[..32], &::final_prefix()); + assert_eq!(&k[..32], &>::final_prefix()); - no_instance::DoubleMap::insert(&1, &2, &3); + >::insert(&1, &2, &3); let mut k = [twox_128(b"FinalKeysNone"), twox_128(b"DoubleMap")].concat(); k.extend(1u32.using_encoded(blake2_128_concat)); k.extend(2u32.using_encoded(blake2_128_concat)); assert_eq!(unhashed::get::(&k), Some(3u32)); - assert_eq!(&k[..32], &::final_prefix()); + assert_eq!(&k[..32], &>::final_prefix()); - no_instance::DoubleMap2::insert(&1, &2, &3); + >::insert(&1, &2, &3); let mut k = [twox_128(b"FinalKeysNone"), twox_128(b"DoubleMap2")].concat(); k.extend(1u32.using_encoded(twox_64_concat)); k.extend(2u32.using_encoded(twox_64_concat)); assert_eq!(unhashed::get::(&k), Some(3u32)); - assert_eq!(&k[..32], &::final_prefix()); + assert_eq!(&k[..32], &>::final_prefix()); }); } #[test] fn final_keys_default_instance() { TestExternalities::default().execute_with(|| { - >::put(1); + >::put(1); let k = [twox_128(b"FinalKeysSome"), twox_128(b"Value")].concat(); assert_eq!(unhashed::get::(&k), Some(1u32)); - >::insert(1, 2); + >::insert(1, 2); let mut k = [twox_128(b"FinalKeysSome"), twox_128(b"Map")].concat(); k.extend(1u32.using_encoded(blake2_128_concat)); assert_eq!(unhashed::get::(&k), Some(2u32)); - assert_eq!(&k[..32], &>::final_prefix()); + assert_eq!(&k[..32], &>::final_prefix()); - >::insert(1, 2); + >::insert(1, 2); let mut k = [twox_128(b"FinalKeysSome"), twox_128(b"Map2")].concat(); k.extend(1u32.using_encoded(twox_64_concat)); assert_eq!(unhashed::get::(&k), Some(2u32)); - assert_eq!(&k[..32], &>::final_prefix()); + assert_eq!(&k[..32], &>::final_prefix()); - >::insert(&1, &2, &3); + >::insert(&1, &2, &3); let mut k = [twox_128(b"FinalKeysSome"), twox_128(b"DoubleMap")].concat(); k.extend(1u32.using_encoded(blake2_128_concat)); k.extend(2u32.using_encoded(blake2_128_concat)); assert_eq!(unhashed::get::(&k), Some(3u32)); - assert_eq!(&k[..32], &>::final_prefix()); + assert_eq!(&k[..32], &>::final_prefix()); - >::insert(&1, &2, &3); + >::insert(&1, &2, &3); let mut k = [twox_128(b"FinalKeysSome"), twox_128(b"DoubleMap2")].concat(); k.extend(1u32.using_encoded(twox_64_concat)); k.extend(2u32.using_encoded(twox_64_concat)); assert_eq!(unhashed::get::(&k), Some(3u32)); - assert_eq!(&k[..32], &>::final_prefix()); + assert_eq!(&k[..32], &>::final_prefix()); }); } #[test] fn final_keys_instance_2() { TestExternalities::default().execute_with(|| { - >::put(1); + >::put(1); let k = [twox_128(b"Instance2FinalKeysSome"), twox_128(b"Value")].concat(); assert_eq!(unhashed::get::(&k), Some(1u32)); - >::insert(1, 2); + >::insert(1, 2); let mut k = [twox_128(b"Instance2FinalKeysSome"), twox_128(b"Map")].concat(); k.extend(1u32.using_encoded(blake2_128_concat)); assert_eq!(unhashed::get::(&k), Some(2u32)); - assert_eq!(&k[..32], &>::final_prefix()); + assert_eq!(&k[..32], &>::final_prefix()); - >::insert(1, 2); + >::insert(1, 2); let mut k = [twox_128(b"Instance2FinalKeysSome"), twox_128(b"Map2")].concat(); k.extend(1u32.using_encoded(twox_64_concat)); assert_eq!(unhashed::get::(&k), Some(2u32)); - assert_eq!(&k[..32], &>::final_prefix()); + assert_eq!(&k[..32], &>::final_prefix()); - >::insert(&1, &2, &3); + >::insert(&1, &2, &3); let mut k = [twox_128(b"Instance2FinalKeysSome"), twox_128(b"DoubleMap")].concat(); k.extend(1u32.using_encoded(blake2_128_concat)); k.extend(2u32.using_encoded(blake2_128_concat)); assert_eq!(unhashed::get::(&k), Some(3u32)); - assert_eq!(&k[..32], &>::final_prefix()); + assert_eq!(&k[..32], &>::final_prefix()); - >::insert(&1, &2, &3); + >::insert(&1, &2, &3); let mut k = [twox_128(b"Instance2FinalKeysSome"), twox_128(b"DoubleMap2")].concat(); k.extend(1u32.using_encoded(twox_64_concat)); k.extend(2u32.using_encoded(twox_64_concat)); assert_eq!(unhashed::get::(&k), Some(3u32)); - assert_eq!(&k[..32], &>::final_prefix()); + assert_eq!(&k[..32], &>::final_prefix()); }); } diff --git a/frame/support/test/tests/genesisconfig.rs b/frame/support/test/tests/genesisconfig.rs index 869641df87060..48904baf1ad62 100644 --- a/frame/support/test/tests/genesisconfig.rs +++ b/frame/support/test/tests/genesisconfig.rs @@ -15,30 +15,86 @@ // See the License for the specific language governing permissions and // limitations under the License. -pub trait Config: frame_support_test::Config {} +use sp_core::sr25519; +use sp_runtime::{ + generic, + traits::{BlakeTwo256, Verify}, +}; -frame_support::decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin, system=frame_support_test {} -} +#[frame_support::pallet] +pub mod pallet { + use super::*; + use frame_support::pallet_prelude::*; + use frame_support_test as frame_system; + + #[pallet::pallet] + pub struct Pallet(PhantomData); + + #[pallet::config] + pub trait Config: frame_system::Config {} -frame_support::decl_storage! { - trait Store for Module as Test { - pub AppendableDM config(t): double_map hasher(identity) u32, hasher(identity) T::BlockNumber => Vec; + #[pallet::call] + impl Pallet {} + + #[pallet::storage] + #[pallet::unbounded] + pub type AppendableDM = + StorageDoubleMap<_, Identity, u32, Identity, T::BlockNumber, Vec>; + + #[pallet::genesis_config] + pub struct GenesisConfig { + pub t: Vec<(u32, T::BlockNumber, Vec)>, + } + + impl Default for GenesisConfig { + fn default() -> Self { + Self { t: Default::default() } + } + } + + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) { + for (k1, k2, v) in &self.t { + >::insert(k1, k2, v); + } + } } } -struct Test; +pub type BlockNumber = u32; +pub type Signature = sr25519::Signature; +pub type AccountId = ::Signer; +pub type Header = generic::Header; +pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; +pub type Block = generic::Block; + +frame_support::construct_runtime!( + pub enum Test + where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_support_test, + MyPallet: pallet, + } +); impl frame_support_test::Config for Test { - type BlockNumber = u32; - type RuntimeOrigin = (); - type PalletInfo = frame_support_test::PanicPalletInfo; + type BlockNumber = BlockNumber; + type AccountId = AccountId; + type BaseCallFilter = frame_support::traits::Everything; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type PalletInfo = PalletInfo; type DbWeight = (); } -impl Config for Test {} +impl pallet::Config for Test {} #[test] fn init_genesis_config() { - GenesisConfig::::default(); + pallet::GenesisConfig::::default(); } diff --git a/frame/support/test/tests/instance.rs b/frame/support/test/tests/instance.rs index 9b08e175b1ca8..5d17a40f8c408 100644 --- a/frame/support/test/tests/instance.rs +++ b/frame/support/test/tests/instance.rs @@ -17,111 +17,111 @@ #![recursion_limit = "128"] -use codec::{Codec, Decode, Encode, EncodeLike, MaxEncodedLen}; use frame_support::{ inherent::{InherentData, InherentIdentifier, MakeFatalError, ProvideInherent}, metadata_ir::{ PalletStorageMetadataIR, StorageEntryMetadataIR, StorageEntryModifierIR, StorageEntryTypeIR, StorageHasherIR, }, - traits::{ConstU32, Get}, - Parameter, StorageDoubleMap, StorageMap, StorageValue, + traits::ConstU32, }; -use scale_info::TypeInfo; -use sp_core::{sr25519, H256}; +use sp_core::sr25519; use sp_runtime::{ generic, traits::{BlakeTwo256, Verify}, BuildStorage, }; -mod system; - pub trait Currency {} // Test for: // * No default instance // * Origin, Inherent, Event +#[frame_support::pallet(dev_mode)] mod module1 { + use self::frame_system::pallet_prelude::*; use super::*; - use sp_std::ops::Add; + use frame_support::pallet_prelude::*; + use frame_support_test as frame_system; - pub trait Config: system::Config - where - ::BlockNumber: From, - { - type RuntimeEvent: From> + Into<::RuntimeEvent>; + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::config] + pub trait Config: frame_system::Config { + type RuntimeEvent: From> + + IsType<::RuntimeEvent>; type RuntimeOrigin: From>; type SomeParameter: Get; - type GenericType: Default + Clone + Codec + EncodeLike + TypeInfo; + type GenericType: Parameter + Member + MaybeSerializeDeserialize + Default + MaxEncodedLen; } - frame_support::decl_module! { - pub struct Module, I: Instance> for enum Call where - origin: ::RuntimeOrigin, - system = system, - T::BlockNumber: From - { - fn offchain_worker() {} + #[pallet::call] + impl, I: 'static> Pallet { + #[pallet::weight(0)] + pub fn one(origin: OriginFor) -> DispatchResult { + ensure_root(origin)?; + Self::deposit_event(Event::AnotherVariant(3)); + Ok(()) + } + } - fn deposit_event() = default; + #[pallet::storage] + #[pallet::getter(fn value)] + pub type Value, I: 'static = ()> = StorageValue<_, T::GenericType, ValueQuery>; - #[weight = 0] - fn one(origin) { - system::ensure_root(origin)?; - Self::deposit_event(RawEvent::AnotherVariant(3)); - } - } + #[pallet::storage] + #[pallet::getter(fn map)] + pub type Map, I: 'static = ()> = StorageMap<_, Identity, u32, u64, ValueQuery>; + + #[pallet::genesis_config] + pub struct GenesisConfig, I: 'static = ()> { + pub value: >::GenericType, + pub test: ::BlockNumber, } - frame_support::decl_storage! { - trait Store for Module, I: Instance> as Module1 where - T::BlockNumber: From + std::fmt::Display - { - pub Value config(value): T::GenericType; - pub Map: map hasher(identity) u32 => u64; + impl, I: 'static> Default for GenesisConfig { + fn default() -> Self { + Self { value: Default::default(), test: Default::default() } } + } - add_extra_genesis { - config(test) : T::BlockNumber; - build(|config: &Self| { - println!("{}", config.test); - }); + #[pallet::genesis_build] + impl, I: 'static> GenesisBuild for GenesisConfig + where + T::BlockNumber: std::fmt::Display, + { + fn build(&self) { + >::put(self.value.clone()); + println!("{}", self.test); } } - frame_support::decl_error! { - pub enum Error for Module, I: Instance> where - T::BlockNumber: From, - T::BlockNumber: Add, - T::AccountId: AsRef<[u8]>, - { - /// Test - Test, - } + #[pallet::error] + pub enum Error { + /// Test + Test, } - frame_support::decl_event! { - pub enum Event where Phantom = std::marker::PhantomData { - _Phantom(Phantom), - AnotherVariant(u32), - } + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event, I: 'static = ()> { + _Phantom(PhantomData), + AnotherVariant(u32), } - #[derive( - PartialEq, Eq, Clone, sp_runtime::RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen, - )] - pub enum Origin, I> - where - T::BlockNumber: From, - { + #[pallet::origin] + #[derive(Clone, PartialEq, Eq, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)] + #[scale_info(skip_type_params(I))] + pub enum Origin { Members(u32), - _Phantom(std::marker::PhantomData<(T, I)>), + _Phantom(PhantomData<(T, I)>), } pub const INHERENT_IDENTIFIER: InherentIdentifier = *b"12345678"; - impl, I: Instance> ProvideInherent for Module + #[pallet::inherent] + impl, I: 'static> ProvideInherent for Pallet where T::BlockNumber: From, { @@ -133,10 +133,7 @@ mod module1 { unimplemented!(); } - fn check_inherent( - _: &Self::Call, - _: &InherentData, - ) -> std::result::Result<(), Self::Error> { + fn check_inherent(_: &Self::Call, _: &InherentData) -> Result<(), Self::Error> { unimplemented!(); } @@ -149,51 +146,88 @@ mod module1 { // Test for: // * default instance // * use of no_genesis_config_phantom_data +#[frame_support::pallet] mod module2 { use super::*; + use frame_support::pallet_prelude::*; + use frame_support_test as frame_system; - pub trait Config: system::Config { - type Amount: Parameter + Default; - type RuntimeEvent: From> + Into<::RuntimeEvent>; + #[pallet::pallet] + pub struct Pallet(PhantomData<(T, I)>); + + #[pallet::config] + pub trait Config: frame_system::Config { + type Amount: Parameter + MaybeSerializeDeserialize + Default + MaxEncodedLen; + type RuntimeEvent: From> + + IsType<::RuntimeEvent>; type RuntimeOrigin: From>; } - impl, I: Instance> Currency for Module {} + impl, I: 'static> Currency for Pallet {} - frame_support::decl_module! { - pub struct Module, I: Instance=DefaultInstance> for enum Call where - origin: ::RuntimeOrigin, - system = system - { - fn deposit_event() = default; - } + #[pallet::call] + impl, I: 'static> Pallet {} + + #[pallet::storage] + pub type Value, I: 'static = ()> = StorageValue<_, T::Amount, ValueQuery>; + + #[pallet::storage] + pub type Map, I: 'static = ()> = StorageMap<_, Identity, u64, u64, ValueQuery>; + + #[pallet::storage] + pub type DoubleMap, I: 'static = ()> = + StorageDoubleMap<_, Identity, u64, Identity, u64, u64, ValueQuery>; + + #[pallet::genesis_config] + pub struct GenesisConfig, I: 'static = ()> { + pub value: T::Amount, + pub map: Vec<(u64, u64)>, + pub double_map: Vec<(u64, u64, u64)>, } - frame_support::decl_storage! { - trait Store for Module, I: Instance=DefaultInstance> as Module2 { - pub Value config(value): T::Amount; - pub Map config(map): map hasher(identity) u64 => u64; - pub DoubleMap config(double_map): double_map hasher(identity) u64, hasher(identity) u64 => u64; + impl, I: 'static> Default for GenesisConfig { + fn default() -> Self { + Self { + value: Default::default(), + map: Default::default(), + double_map: Default::default(), + } } } - frame_support::decl_event! { - pub enum Event where Amount = >::Amount { - Variant(Amount), + #[pallet::genesis_build] + impl, I: 'static> GenesisBuild for GenesisConfig + where + T::BlockNumber: std::fmt::Display, + { + fn build(&self) { + >::put(self.value.clone()); + for (k, v) in &self.map { + >::insert(k, v); + } + for (k1, k2, v) in &self.double_map { + >::insert(k1, k2, v); + } } } - #[derive( - PartialEq, Eq, Clone, sp_runtime::RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen, - )] - pub enum Origin, I = DefaultInstance> { + #[pallet::event] + pub enum Event, I: 'static = ()> { + Variant(T::Amount), + } + + #[pallet::origin] + #[derive(Clone, PartialEq, Eq, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)] + #[scale_info(skip_type_params(I))] + pub enum Origin { Members(u32), - _Phantom(std::marker::PhantomData<(T, I)>), + _Phantom(PhantomData<(T, I)>), } pub const INHERENT_IDENTIFIER: InherentIdentifier = *b"12345678"; - impl, I: Instance> ProvideInherent for Module { + #[pallet::inherent] + impl, I: 'static> ProvideInherent for Pallet { type Call = Call; type Error = MakeFatalError<()>; const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER; @@ -202,10 +236,7 @@ mod module2 { unimplemented!(); } - fn check_inherent( - _call: &Self::Call, - _data: &InherentData, - ) -> std::result::Result<(), Self::Error> { + fn check_inherent(_call: &Self::Call, _data: &InherentData) -> Result<(), Self::Error> { unimplemented!(); } @@ -217,19 +248,70 @@ mod module2 { // Test for: // * Depends on multiple instances of a module with instances +#[frame_support::pallet] mod module3 { use super::*; + use frame_support::pallet_prelude::*; + use frame_support_test as frame_system; + + #[pallet::pallet] + pub struct Pallet(PhantomData<(T, I)>); - pub trait Config: - module2::Config + module2::Config + system::Config + #[pallet::config] + pub trait Config: + frame_system::Config + module2::Config + module2::Config { type Currency: Currency; type Currency2: Currency; } - frame_support::decl_module! { - pub struct Module for enum Call where origin: ::RuntimeOrigin, system=system {} + #[pallet::call] + impl, I: 'static> Pallet {} +} + +pub type BlockNumber = u32; +pub type Signature = sr25519::Signature; +pub type AccountId = ::Signer; +pub type Header = generic::Header; +pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; +pub type Block = generic::Block; + +frame_support::construct_runtime!( + pub enum Runtime where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic + { + System: frame_support_test::{Pallet, Call, Event}, + Module1_1: module1::::{ + Pallet, Call, Storage, Event, Config, Origin, Inherent + }, + Module1_2: module1::::{ + Pallet, Call, Storage, Event, Config, Origin, Inherent + }, + Module2: module2::{Pallet, Call, Storage, Event, Config, Origin, Inherent}, + Module2_1: module2::::{ + Pallet, Call, Storage, Event, Config, Origin, Inherent + }, + Module2_2: module2::::{ + Pallet, Call, Storage, Event, Config, Origin, Inherent + }, + Module2_3: module2::::{ + Pallet, Call, Storage, Event, Config, Origin, Inherent + }, + Module3: module3::{Pallet, Call}, } +); + +impl frame_support_test::Config for Runtime { + type BlockNumber = BlockNumber; + type AccountId = AccountId; + type BaseCallFilter = frame_support::traits::Everything; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type PalletInfo = PalletInfo; + type DbWeight = (); } impl module1::Config for Runtime { @@ -269,54 +351,6 @@ impl module3::Config for Runtime { type Currency2 = Module2_3; } -pub type Signature = sr25519::Signature; -pub type AccountId = ::Signer; -pub type BlockNumber = u64; -pub type Index = u64; - -impl system::Config for Runtime { - type BaseCallFilter = frame_support::traits::Everything; - type Hash = H256; - type RuntimeOrigin = RuntimeOrigin; - type BlockNumber = BlockNumber; - type AccountId = AccountId; - type RuntimeEvent = RuntimeEvent; - type PalletInfo = PalletInfo; - type RuntimeCall = RuntimeCall; - type DbWeight = (); -} - -frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic - { - System: system::{Pallet, Call, Event}, - Module1_1: module1::::{ - Pallet, Call, Storage, Event, Config, Origin, Inherent - }, - Module1_2: module1::::{ - Pallet, Call, Storage, Event, Config, Origin, Inherent - }, - Module2: module2::{Pallet, Call, Storage, Event, Config, Origin, Inherent}, - Module2_1: module2::::{ - Pallet, Call, Storage, Event, Config, Origin, Inherent - }, - Module2_2: module2::::{ - Pallet, Call, Storage, Event, Config, Origin, Inherent - }, - Module2_3: module2::::{ - Pallet, Call, Storage, Event, Config, Origin, Inherent - }, - Module3: module3::{Pallet, Call}, - } -); - -pub type Header = generic::Header; -pub type Block = generic::Block; -pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; - fn new_test_ext() -> sp_io::TestExternalities { GenesisConfig { module_1_1: module1::GenesisConfig { value: 3, test: 2 }, @@ -350,14 +384,14 @@ fn storage_instance_independence() { module2::Value::::put(0); module2::Value::::put(0); module2::Value::::put(0); - module2::Map::::insert(0, 0); - module2::Map::::insert(0, 0); - module2::Map::::insert(0, 0); - module2::Map::::insert(0, 0); - module2::DoubleMap::::insert(&0, &0, &0); - module2::DoubleMap::::insert(&0, &0, &0); - module2::DoubleMap::::insert(&0, &0, &0); - module2::DoubleMap::::insert(&0, &0, &0); + module2::Map::::insert(0, 0); + module2::Map::::insert(0, 0); + module2::Map::::insert(0, 0); + module2::Map::::insert(0, 0); + module2::DoubleMap::::insert(&0, &0, &0); + module2::DoubleMap::::insert(&0, &0, &0); + module2::DoubleMap::::insert(&0, &0, &0); + module2::DoubleMap::::insert(&0, &0, &0); }); // 12 storage values. assert_eq!(storage.top.len(), 12); @@ -367,8 +401,8 @@ fn storage_instance_independence() { fn storage_with_instance_basic_operation() { new_test_ext().execute_with(|| { type Value = module2::Value; - type Map = module2::Map; - type DoubleMap = module2::DoubleMap; + type Map = module2::Map; + type DoubleMap = module2::DoubleMap; assert_eq!(Value::exists(), true); assert_eq!(Value::get(), 4); @@ -412,7 +446,7 @@ fn storage_with_instance_basic_operation() { fn expected_metadata() -> PalletStorageMetadataIR { PalletStorageMetadataIR { - prefix: "Instance2Module2", + prefix: "Module2_2", entries: vec![ StorageEntryMetadataIR { name: "Value", diff --git a/frame/support/test/tests/issue2219.rs b/frame/support/test/tests/issue2219.rs index ce16c402da0fd..ff3e0bd951873 100644 --- a/frame/support/test/tests/issue2219.rs +++ b/frame/support/test/tests/issue2219.rs @@ -15,32 +15,28 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support::{ - codec::{Decode, Encode}, - scale_info::TypeInfo, - sp_runtime::{ - generic, - traits::{BlakeTwo256, Verify}, - }, +use sp_core::{sr25519, ConstU64}; +use sp_runtime::{ + generic, + traits::{BlakeTwo256, Verify}, }; -use serde::{Deserialize, Serialize}; -use sp_core::{sr25519, H256}; - -mod system; +#[frame_support::pallet] mod module { use super::*; + use frame_support::pallet_prelude::*; + use frame_support_test as frame_system; pub type Request = - (::AccountId, Role, ::BlockNumber); + (::AccountId, Role, ::BlockNumber); pub type Requests = Vec>; - #[derive(Encode, Decode, Copy, Clone, Eq, PartialEq, Debug, TypeInfo)] + #[derive(Copy, Clone, Eq, PartialEq, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)] pub enum Role { Storage, } - #[derive(Encode, Decode, Copy, Clone, Eq, PartialEq, Debug, TypeInfo)] + #[derive(Copy, Clone, Eq, PartialEq, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)] pub struct RoleParameters { // minimum actors to maintain - if role is unstaking // and remaining actors would be less that this value - prevent or punish for unstaking @@ -83,102 +79,108 @@ mod module { } } - pub trait Config: system::Config + TypeInfo {} - - frame_support::decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin, system=system {} - } - - #[derive(Encode, Decode, Copy, Clone, Serialize, Deserialize)] - pub struct Data { - pub data: T::BlockNumber, - } - - impl Default for Data { - fn default() -> Self { - Self { data: T::BlockNumber::default() } - } + #[pallet::pallet] + pub struct Pallet(PhantomData); + + #[pallet::config] + pub trait Config: frame_system::Config + TypeInfo {} + + #[pallet::call] + impl Pallet {} + + /// requirements to enter and maintain status in roles + #[pallet::storage] + #[pallet::getter(fn parameters)] + pub type Parameters = + StorageMap<_, Blake2_128Concat, Role, RoleParameters, OptionQuery>; + + /// the roles members can enter into + #[pallet::storage] + #[pallet::getter(fn available_roles)] + #[pallet::unbounded] + pub type AvailableRoles = StorageValue<_, Vec, ValueQuery>; + + /// Actors list + #[pallet::storage] + #[pallet::getter(fn actor_account_ids)] + #[pallet::unbounded] + pub type ActorAccountIds = StorageValue<_, Vec>; + + /// actor accounts associated with a role + #[pallet::storage] + #[pallet::getter(fn account_ids_by_role)] + #[pallet::unbounded] + pub type AccountIdsByRole = StorageMap<_, Blake2_128Concat, Role, Vec>; + + /// tokens locked until given block number + #[pallet::storage] + #[pallet::getter(fn bondage)] + pub type Bondage = StorageMap<_, Blake2_128Concat, T::AccountId, T::BlockNumber>; + + /// First step before enter a role is registering intent with a new account/key. + /// This is done by sending a role_entry_request() from the new account. + /// The member must then send a stake() transaction to approve the request and enter the desired + /// role. The account making the request will be bonded and must have + /// sufficient balance to cover the minimum stake for the role. + /// Bonding only occurs after successful entry into a role. + #[pallet::storage] + #[pallet::getter(fn role_entry_requests)] + #[pallet::unbounded] + pub type RoleEntryRequests = StorageValue<_, Requests>; + + /// Entry request expires after this number of blocks + #[pallet::storage] + #[pallet::getter(fn request_life_time)] + pub type RequestLifeTime = StorageValue<_, u64, ValueQuery, ConstU64<0>>; + + #[pallet::genesis_config] + #[derive(Default)] + pub struct GenesisConfig { + pub enable_storage_role: bool, + pub request_life_time: u64, } - frame_support::decl_storage! { - trait Store for Module as Actors { - /// requirements to enter and maintain status in roles - pub Parameters get(fn parameters) build(|config: &GenesisConfig| { - if config.enable_storage_role { - let storage_params: RoleParameters = Default::default(); - vec![(Role::Storage, storage_params)] - } else { - vec![] - } - }): map hasher(blake2_128_concat) Role => Option>; - - /// the roles members can enter into - pub AvailableRoles get(fn available_roles) build(|config: &GenesisConfig| { - if config.enable_storage_role { - vec![(Role::Storage)] - } else { - vec![] - } - }): Vec; - - /// Actors list - pub ActorAccountIds get(fn actor_account_ids) : Vec; - - /// actor accounts associated with a role - pub AccountIdsByRole get(fn account_ids_by_role): - map hasher(blake2_128_concat) Role => Vec; - - /// tokens locked until given block number - pub Bondage get(fn bondage): - map hasher(blake2_128_concat) T::AccountId => T::BlockNumber; - - /// First step before enter a role is registering intent with a new account/key. - /// This is done by sending a role_entry_request() from the new account. - /// The member must then send a stake() transaction to approve the request and enter the desired role. - /// The account making the request will be bonded and must have - /// sufficient balance to cover the minimum stake for the role. - /// Bonding only occurs after successful entry into a role. - pub RoleEntryRequests get(fn role_entry_requests) : Requests; - - /// Entry request expires after this number of blocks - pub RequestLifeTime get(fn request_life_time) config(request_life_time) : u64 = 0; - } - add_extra_genesis { - config(enable_storage_role): bool; + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) { + if self.enable_storage_role { + >::insert(Role::Storage, >::default()); + >::put(vec![Role::Storage]); + } + >::put(self.request_life_time); } } } +pub type BlockNumber = u64; pub type Signature = sr25519::Signature; pub type AccountId = ::Signer; -pub type BlockNumber = u64; -pub type Index = u64; pub type Header = generic::Header; -pub type Block = generic::Block; pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; +pub type Block = generic::Block; -impl system::Config for Runtime { - type BaseCallFilter = frame_support::traits::Everything; - type Hash = H256; - type RuntimeOrigin = RuntimeOrigin; +impl frame_support_test::Config for Runtime { type BlockNumber = BlockNumber; type AccountId = AccountId; + type BaseCallFilter = frame_support::traits::Everything; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type PalletInfo = PalletInfo; - type RuntimeCall = RuntimeCall; type DbWeight = (); } impl module::Config for Runtime {} frame_support::construct_runtime!( - pub struct Runtime where + pub struct Runtime + where Block = Block, NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + UncheckedExtrinsic = UncheckedExtrinsic, { - System: system::{Pallet, Call, Event}, - Module: module::{Pallet, Call, Storage, Config}, + System: frame_support_test, + Module: module, } ); diff --git a/frame/support/test/tests/origin.rs b/frame/support/test/tests/origin.rs index 996b996c8c49c..47451157b352c 100644 --- a/frame/support/test/tests/origin.rs +++ b/frame/support/test/tests/origin.rs @@ -19,120 +19,124 @@ #![recursion_limit = "128"] -use codec::MaxEncodedLen; use frame_support::traits::{Contains, OriginTrait}; -use scale_info::TypeInfo; -use sp_core::{sr25519, H256}; use sp_runtime::{generic, traits::BlakeTwo256}; -mod system; - mod nested { - use super::*; - + #[frame_support::pallet(dev_mode)] pub mod module { + use self::frame_system::pallet_prelude::*; + use frame_support::pallet_prelude::*; + use frame_support_test as frame_system; - use super::*; + #[pallet::pallet] + pub struct Pallet(_); - pub trait Config: system::Config {} + #[pallet::config] + pub trait Config: frame_system::Config { + type RuntimeEvent: From> + + IsType<::RuntimeEvent>; + } - frame_support::decl_module! { - pub struct Module for enum Call - where origin: ::RuntimeOrigin, system=system - { - #[weight = 0] - pub fn fail(_origin) -> frame_support::dispatch::DispatchResult { - Err(Error::::Something.into()) - } + #[pallet::call] + impl Pallet { + pub fn fail(_origin: OriginFor) -> DispatchResult { + Err(Error::::Something.into()) } } - #[derive( - Clone, PartialEq, Eq, Debug, codec::Encode, codec::Decode, TypeInfo, MaxEncodedLen, - )] + #[pallet::origin] + #[derive(Clone, PartialEq, Eq, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)] pub struct Origin; - frame_support::decl_event! { - pub enum Event { - A, - } + #[pallet::event] + pub enum Event { + A, } - frame_support::decl_error! { - pub enum Error for Module { - Something - } + #[pallet::error] + pub enum Error { + Something, } - frame_support::decl_storage! { - trait Store for Module as Module {} - add_extra_genesis { - build(|_config| {}) - } + #[pallet::genesis_config] + #[derive(Default)] + pub struct GenesisConfig {} + + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) {} } } } +#[frame_support::pallet(dev_mode)] pub mod module { - use super::*; + use self::frame_system::pallet_prelude::*; + use frame_support::pallet_prelude::*; + use frame_support_test as frame_system; - pub trait Config: system::Config {} + #[pallet::pallet] + pub struct Pallet(_); - frame_support::decl_module! { - pub struct Module for enum Call - where origin: ::RuntimeOrigin, system=system - { - #[weight = 0] - pub fn fail(_origin) -> frame_support::dispatch::DispatchResult { - Err(Error::::Something.into()) - } - #[weight = 0] - pub fn aux_1(_origin, #[compact] _data: u32) -> frame_support::dispatch::DispatchResult { - unreachable!() - } - #[weight = 0] - pub fn aux_2(_origin, _data: i32, #[compact] _data2: u32) -> frame_support::dispatch::DispatchResult { - unreachable!() - } - #[weight = 0] - fn aux_3(_origin, _data: i32, _data2: String) -> frame_support::dispatch::DispatchResult { - unreachable!() - } - #[weight = 3] - fn aux_4(_origin) -> frame_support::dispatch::DispatchResult { unreachable!() } - #[weight = (5, frame_support::dispatch::DispatchClass::Operational)] - fn operational(_origin) { unreachable!() } + #[pallet::config] + pub trait Config: frame_system::Config { + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + } + + #[pallet::call] + impl Pallet { + pub fn fail(_origin: OriginFor) -> DispatchResult { + Err(Error::::Something.into()) + } + pub fn aux_1(_origin: OriginFor, #[pallet::compact] _data: u32) -> DispatchResult { + unreachable!() + } + pub fn aux_2( + _origin: OriginFor, + _data: i32, + #[pallet::compact] _data2: u32, + ) -> DispatchResult { + unreachable!() + } + #[pallet::weight(0)] + pub fn aux_3(_origin: OriginFor, _data: i32, _data2: String) -> DispatchResult { + unreachable!() + } + #[pallet::weight(3)] + pub fn aux_4(_origin: OriginFor) -> DispatchResult { + unreachable!() + } + #[pallet::weight((5, DispatchClass::Operational))] + pub fn operational(_origin: OriginFor) -> DispatchResult { + unreachable!() } } - #[derive( - Clone, PartialEq, Eq, Debug, codec::Encode, codec::Decode, TypeInfo, MaxEncodedLen, - )] - pub struct Origin(pub core::marker::PhantomData); + #[pallet::origin] + #[derive(Clone, PartialEq, Eq, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)] + pub struct Origin(pub PhantomData); - frame_support::decl_event! { - pub enum Event { - A, - } + #[pallet::event] + pub enum Event { + A, } - frame_support::decl_error! { - pub enum Error for Module { - Something - } + #[pallet::error] + pub enum Error { + Something, } - frame_support::decl_storage! { - trait Store for Module as Module {} - add_extra_genesis { - build(|_config| {}) - } + #[pallet::genesis_config] + #[derive(Default)] + pub struct GenesisConfig {} + + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) {} } } -impl nested::module::Config for RuntimeOriginTest {} -impl module::Config for RuntimeOriginTest {} - pub struct BaseCallFilter; impl Contains for BaseCallFilter { fn contains(c: &RuntimeCall) -> bool { @@ -143,17 +147,11 @@ impl Contains for BaseCallFilter { } } -impl system::Config for RuntimeOriginTest { - type BaseCallFilter = BaseCallFilter; - type Hash = H256; - type RuntimeOrigin = RuntimeOrigin; - type BlockNumber = BlockNumber; - type AccountId = u32; - type RuntimeEvent = RuntimeEvent; - type PalletInfo = PalletInfo; - type RuntimeCall = RuntimeCall; - type DbWeight = (); -} +pub type BlockNumber = u32; +pub type AccountId = u32; +pub type Header = generic::Header; +pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; +pub type Block = generic::Block; frame_support::construct_runtime!( pub enum RuntimeOriginTest where @@ -161,17 +159,29 @@ frame_support::construct_runtime!( NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: system::{Pallet, Event, Origin}, - NestedModule: nested::module::{Pallet, Origin, Call}, - Module: module::{Pallet, Origin, Call}, + System: frame_support_test, + NestedModule: nested::module, + Module: module, } ); -pub type Signature = sr25519::Signature; -pub type BlockNumber = u64; -pub type Header = generic::Header; -pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; -pub type Block = generic::Block; +impl frame_support_test::Config for RuntimeOriginTest { + type BlockNumber = BlockNumber; + type AccountId = AccountId; + type BaseCallFilter = BaseCallFilter; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type PalletInfo = PalletInfo; + type DbWeight = (); +} + +impl nested::module::Config for RuntimeOriginTest { + type RuntimeEvent = RuntimeEvent; +} +impl module::Config for RuntimeOriginTest { + type RuntimeEvent = RuntimeEvent; +} #[test] fn origin_default_filter() { @@ -199,7 +209,7 @@ fn origin_default_filter() { // Now test for root origin and filters: let mut origin = RuntimeOrigin::from(Some(0)); origin.set_caller_from(RuntimeOrigin::root()); - assert!(matches!(origin.caller, OriginCaller::system(system::RawOrigin::Root))); + assert!(matches!(origin.caller, OriginCaller::system(frame_support_test::RawOrigin::Root))); // Root origin bypass all filter. assert_eq!(origin.filter_call(&accepted_call), true); diff --git a/frame/support/test/tests/pallet_compatibility.rs b/frame/support/test/tests/pallet_compatibility.rs deleted file mode 100644 index 610316ecf1a6f..0000000000000 --- a/frame/support/test/tests/pallet_compatibility.rs +++ /dev/null @@ -1,371 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Old macros don't support the flag `no-metadata-docs` so the result differs when the feature is -// activated. -#![cfg(not(feature = "no-metadata-docs"))] - -use frame_support::traits::{ConstU32, ConstU64}; - -pub trait SomeAssociation { - type A: frame_support::dispatch::Parameter + Default; -} -impl SomeAssociation for u64 { - type A = u64; -} - -mod pallet_old { - use super::SomeAssociation; - use frame_support::{ - decl_error, decl_event, decl_module, decl_storage, traits::Get, weights::Weight, Parameter, - }; - use frame_system::ensure_root; - - pub trait Config: frame_system::Config { - type SomeConst: Get; - type Balance: Parameter - + codec::HasCompact - + From - + Into - + Default - + SomeAssociation; - type RuntimeEvent: From> + Into<::RuntimeEvent>; - } - - decl_storage! { - trait Store for Module as Example { - /// Some documentation - Dummy get(fn dummy) config(): Option; - Bar get(fn bar) config(): map hasher(blake2_128_concat) T::AccountId => T::Balance; - Foo get(fn foo) config(): T::Balance = 3.into(); - Double get(fn double): double_map - hasher(blake2_128_concat) u32, - hasher(twox_64_concat) u64 - => ::A; - } - } - - decl_event!( - pub enum Event - where - Balance = ::Balance, - { - /// Dummy event, just here so there's a generic type that's used. - Dummy(Balance), - } - ); - - decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin { - type Error = Error; - fn deposit_event() = default; - const SomeConst: T::Balance = T::SomeConst::get(); - - #[weight = >::into(new_value.clone())] - fn set_dummy(origin, #[compact] new_value: T::Balance) { - ensure_root(origin)?; - - >::put(&new_value); - Self::deposit_event(RawEvent::Dummy(new_value)); - } - - fn on_initialize(_n: T::BlockNumber) -> Weight { - >::put(T::Balance::from(10)); - Weight::from_parts(10, 0) - } - - fn on_finalize(_n: T::BlockNumber) { - >::put(T::Balance::from(11)); - } - } - } - - decl_error! { - pub enum Error for Module { - /// Some wrong behavior - Wrong, - } - } -} - -#[frame_support::pallet] -pub mod pallet { - use super::SomeAssociation; - use frame_support::{pallet_prelude::*, scale_info}; - use frame_system::{ensure_root, pallet_prelude::*}; - - #[pallet::config] - pub trait Config: frame_system::Config { - type Balance: Parameter - + codec::HasCompact - + From - + Into - + Default - + MaybeSerializeDeserialize - + SomeAssociation - + scale_info::StaticTypeInfo; - #[pallet::constant] - type SomeConst: Get; - type RuntimeEvent: From> + IsType<::RuntimeEvent>; - } - - #[pallet::pallet] - #[pallet::without_storage_info] - pub struct Pallet(_); - - #[pallet::hooks] - impl Hooks for Pallet { - fn on_initialize(_n: T::BlockNumber) -> Weight { - >::put(T::Balance::from(10)); - Weight::from_parts(10, 0) - } - - fn on_finalize(_n: T::BlockNumber) { - >::put(T::Balance::from(11)); - } - } - - #[pallet::call] - impl Pallet { - #[pallet::call_index(0)] - #[pallet::weight(>::into(new_value.clone()))] - pub fn set_dummy( - origin: OriginFor, - #[pallet::compact] new_value: T::Balance, - ) -> DispatchResultWithPostInfo { - ensure_root(origin)?; - - >::put(&new_value); - Self::deposit_event(Event::Dummy(new_value)); - - Ok(().into()) - } - } - - #[pallet::error] - pub enum Error { - /// Some wrong behavior - Wrong, - } - - #[pallet::event] - #[pallet::generate_deposit(fn deposit_event)] - pub enum Event { - /// Dummy event, just here so there's a generic type that's used. - Dummy(T::Balance), - } - - #[pallet::storage] - /// Some documentation - type Dummy = StorageValue<_, T::Balance, OptionQuery>; - - #[pallet::storage] - type Bar = StorageMap<_, Blake2_128Concat, T::AccountId, T::Balance, ValueQuery>; - - #[pallet::type_value] - pub fn OnFooEmpty() -> T::Balance { - 3.into() - } - #[pallet::storage] - type Foo = StorageValue<_, T::Balance, ValueQuery, OnFooEmpty>; - - #[pallet::storage] - type Double = StorageDoubleMap< - _, - Blake2_128Concat, - u32, - Twox64Concat, - u64, - ::A, - ValueQuery, - >; - - #[pallet::genesis_config] - pub struct GenesisConfig { - dummy: Option, - bar: Vec<(T::AccountId, T::Balance)>, - foo: T::Balance, - } - - impl Default for GenesisConfig { - fn default() -> Self { - GenesisConfig { - dummy: Default::default(), - bar: Default::default(), - foo: OnFooEmpty::::get(), - } - } - } - - #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { - fn build(&self) { - if let Some(dummy) = self.dummy.as_ref() { - >::put(dummy); - } - for (k, v) in &self.bar { - >::insert(k, v); - } - >::put(&self.foo); - } - } -} - -impl frame_system::Config for Runtime { - type BaseCallFilter = frame_support::traits::Everything; - type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u32; - type RuntimeCall = RuntimeCall; - type Hash = sp_runtime::testing::H256; - type Hashing = sp_runtime::traits::BlakeTwo256; - type AccountId = u64; - type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; - type RuntimeEvent = RuntimeEvent; - type BlockHashCount = ConstU32<250>; - type BlockWeights = (); - type BlockLength = (); - type DbWeight = (); - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = (); - type OnSetCode = (); - type MaxConsumers = ConstU32<16>; -} -impl pallet::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type SomeConst = ConstU64<10>; - type Balance = u64; -} -impl pallet_old::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type SomeConst = ConstU64<10>; - type Balance = u64; -} - -pub type Header = sp_runtime::generic::Header; -pub type Block = sp_runtime::generic::Block; -pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; - -frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic - { - System: frame_system::{Pallet, Call, Event}, - // NOTE: name Example here is needed in order to have same module prefix - Example: pallet::{Pallet, Call, Event, Config, Storage}, - PalletOld: pallet_old::{Pallet, Call, Event, Config, Storage}, - } -); - -#[cfg(test)] -mod test { - use super::{pallet, pallet_old, Runtime}; - use codec::{Decode, Encode}; - use scale_info::{form::PortableForm, Variant}; - - #[test] - fn metadata() { - let metadata = Runtime::metadata(); - let (pallets, types) = match metadata.1 { - frame_support::metadata::RuntimeMetadata::V14(metadata) => - (metadata.pallets, metadata.types), - _ => unreachable!(), - }; - - let assert_meta_types = |ty_id1, ty_id2| { - let ty1 = types.resolve(ty_id1).map(|ty| ty.type_def.clone()); - let ty2 = types.resolve(ty_id2).map(|ty| ty.type_def.clone()); - pretty_assertions::assert_eq!(ty1, ty2); - }; - - let get_enum_variants = |ty_id| match types.resolve(ty_id).map(|ty| ty.type_def.clone()) { - Some(ty) => match ty { - scale_info::TypeDef::Variant(var) => var.variants, - _ => panic!("Expected variant type"), - }, - _ => panic!("No type found"), - }; - - let assert_enum_variants = |vs1: &[Variant], - vs2: &[Variant]| { - assert_eq!(vs1.len(), vs2.len()); - for i in 0..vs1.len() { - let v1 = &vs2[i]; - let v2 = &vs2[i]; - assert_eq!(v1.fields.len(), v2.fields.len()); - for f in 0..v1.fields.len() { - let f1 = &v1.fields[f]; - let f2 = &v2.fields[f]; - pretty_assertions::assert_eq!(f1.name, f2.name); - pretty_assertions::assert_eq!(f1.ty, f2.ty); - } - } - }; - - pretty_assertions::assert_eq!(pallets[1].storage, pallets[2].storage); - - let calls1 = pallets[1].calls.as_ref().unwrap(); - let calls2 = pallets[2].calls.as_ref().unwrap(); - assert_meta_types(calls1.ty.id, calls2.ty.id); - - // event: check variants and fields but ignore the type name which will be different - let event1_variants = get_enum_variants(pallets[1].event.as_ref().unwrap().ty.id); - let event2_variants = get_enum_variants(pallets[2].event.as_ref().unwrap().ty.id); - assert_enum_variants(&event1_variants, &event2_variants); - - let err1 = get_enum_variants(pallets[1].error.as_ref().unwrap().ty.id) - .iter() - .filter(|v| v.name == "__Ignore") - .cloned() - .collect::>(); - let err2 = get_enum_variants(pallets[2].error.as_ref().unwrap().ty.id) - .iter() - .filter(|v| v.name == "__Ignore") - .cloned() - .collect::>(); - assert_enum_variants(&err1, &err2); - - pretty_assertions::assert_eq!(pallets[1].constants, pallets[2].constants); - } - - #[test] - fn types() { - assert_eq!( - pallet_old::Event::::decode( - &mut &pallet::Event::::Dummy(10).encode()[..] - ) - .unwrap(), - pallet_old::Event::::Dummy(10), - ); - - assert_eq!( - pallet_old::Call::::decode( - &mut &pallet::Call::::set_dummy { new_value: 10 }.encode()[..] - ) - .unwrap(), - pallet_old::Call::::set_dummy { new_value: 10 }, - ); - } -} diff --git a/frame/support/test/tests/pallet_compatibility_instance.rs b/frame/support/test/tests/pallet_compatibility_instance.rs deleted file mode 100644 index 73014d99657c9..0000000000000 --- a/frame/support/test/tests/pallet_compatibility_instance.rs +++ /dev/null @@ -1,371 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Old macros don't support the flag `no-metadata-docs` so the result differs when the feature is -// activated. -#![cfg(not(feature = "no-metadata-docs"))] - -use frame_support::traits::{ConstU32, ConstU64}; - -mod pallet_old { - use frame_support::{ - decl_error, decl_event, decl_module, decl_storage, traits::Get, weights::Weight, Parameter, - }; - use frame_system::ensure_root; - - pub trait Config: frame_system::Config { - type SomeConst: Get; - type Balance: Parameter + codec::HasCompact + From + Into + Default; - type RuntimeEvent: From> + Into<::RuntimeEvent>; - } - - decl_storage! { - trait Store for Module, I: Instance = DefaultInstance> as Example { - /// Some documentation - Dummy get(fn dummy) config(): Option; - Bar get(fn bar) config(): map hasher(blake2_128_concat) T::AccountId => T::Balance; - Foo get(fn foo) config(): T::Balance = 3.into(); - Double get(fn double): - double_map hasher(blake2_128_concat) u32, hasher(twox_64_concat) u64 => u16; - } - } - - decl_event!( - pub enum Event - where - Balance = >::Balance, - { - /// Dummy event, just here so there's a generic type that's used. - Dummy(Balance), - } - ); - - decl_module! { - pub struct Module, I: Instance = DefaultInstance> for enum Call - where origin: T::RuntimeOrigin - { - type Error = Error; - fn deposit_event() = default; - const SomeConst: T::Balance = T::SomeConst::get(); - - #[weight = >::into(new_value.clone())] - fn set_dummy(origin, #[compact] new_value: T::Balance) { - ensure_root(origin)?; - - >::put(&new_value); - Self::deposit_event(RawEvent::Dummy(new_value)); - } - - fn on_initialize(_n: T::BlockNumber) -> Weight { - >::put(T::Balance::from(10)); - Weight::from_parts(10, 0) - } - - fn on_finalize(_n: T::BlockNumber) { - >::put(T::Balance::from(11)); - } - } - } - - decl_error! { - pub enum Error for Module, I: Instance> { - /// Some wrong behavior - Wrong, - } - } -} - -#[frame_support::pallet] -pub mod pallet { - use frame_support::{pallet_prelude::*, scale_info}; - use frame_system::{ensure_root, pallet_prelude::*}; - - #[pallet::config] - pub trait Config: frame_system::Config { - type Balance: Parameter - + codec::HasCompact - + From - + Into - + Default - + MaybeSerializeDeserialize - + scale_info::StaticTypeInfo; - #[pallet::constant] - type SomeConst: Get; - type RuntimeEvent: From> - + IsType<::RuntimeEvent>; - } - - #[pallet::pallet] - #[pallet::without_storage_info] - pub struct Pallet(PhantomData<(T, I)>); - - #[pallet::hooks] - impl, I: 'static> Hooks for Pallet { - fn on_initialize(_n: T::BlockNumber) -> Weight { - >::put(T::Balance::from(10)); - Weight::from_parts(10, 0) - } - - fn on_finalize(_n: T::BlockNumber) { - >::put(T::Balance::from(11)); - } - } - - #[pallet::call] - impl, I: 'static> Pallet { - #[pallet::call_index(0)] - #[pallet::weight(>::into(new_value.clone()))] - pub fn set_dummy( - origin: OriginFor, - #[pallet::compact] new_value: T::Balance, - ) -> DispatchResultWithPostInfo { - ensure_root(origin)?; - - >::put(&new_value); - Self::deposit_event(Event::Dummy(new_value)); - - Ok(().into()) - } - } - - #[pallet::error] - pub enum Error { - /// Some wrong behavior - Wrong, - } - - #[pallet::event] - #[pallet::generate_deposit(fn deposit_event)] - pub enum Event, I: 'static = ()> { - /// Dummy event, just here so there's a generic type that's used. - Dummy(T::Balance), - } - - #[pallet::storage] - /// Some documentation - type Dummy, I: 'static = ()> = StorageValue<_, T::Balance, OptionQuery>; - - #[pallet::storage] - type Bar, I: 'static = ()> = - StorageMap<_, Blake2_128Concat, T::AccountId, T::Balance, ValueQuery>; - - #[pallet::storage] - type Foo, I: 'static = ()> = - StorageValue<_, T::Balance, ValueQuery, OnFooEmpty>; - #[pallet::type_value] - pub fn OnFooEmpty, I: 'static>() -> T::Balance { - 3.into() - } - - #[pallet::storage] - type Double = - StorageDoubleMap<_, Blake2_128Concat, u32, Twox64Concat, u64, u16, ValueQuery>; - - #[pallet::genesis_config] - pub struct GenesisConfig, I: 'static = ()> { - dummy: Option, - bar: Vec<(T::AccountId, T::Balance)>, - foo: T::Balance, - } - - impl, I: 'static> Default for GenesisConfig { - fn default() -> Self { - GenesisConfig { - dummy: Default::default(), - bar: Default::default(), - foo: OnFooEmpty::::get(), - } - } - } - - #[pallet::genesis_build] - impl, I: 'static> GenesisBuild for GenesisConfig { - fn build(&self) { - if let Some(dummy) = self.dummy.as_ref() { - >::put(dummy); - } - for (k, v) in &self.bar { - >::insert(k, v); - } - >::put(&self.foo); - } - } -} - -impl frame_system::Config for Runtime { - type BlockWeights = (); - type BlockLength = (); - type DbWeight = (); - type BaseCallFilter = frame_support::traits::Everything; - type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u32; - type RuntimeCall = RuntimeCall; - type Hash = sp_runtime::testing::H256; - type Hashing = sp_runtime::traits::BlakeTwo256; - type AccountId = u64; - type Lookup = sp_runtime::traits::IdentityLookup; - type Header = Header; - type RuntimeEvent = RuntimeEvent; - type BlockHashCount = ConstU32<250>; - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = (); - type OnSetCode = (); - type MaxConsumers = ConstU32<16>; -} -impl pallet::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type SomeConst = ConstU64<10>; - type Balance = u64; -} -impl pallet::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type SomeConst = ConstU64<10>; - type Balance = u64; -} -impl pallet::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type SomeConst = ConstU64<10>; - type Balance = u64; -} -impl pallet_old::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type SomeConst = ConstU64<10>; - type Balance = u64; -} -impl pallet_old::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type SomeConst = ConstU64<10>; - type Balance = u64; -} -impl pallet_old::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type SomeConst = ConstU64<10>; - type Balance = u64; -} - -pub type Header = sp_runtime::generic::Header; -pub type Block = sp_runtime::generic::Block; -pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; - -frame_support::construct_runtime!( - pub struct Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic - { - System: frame_system::{Pallet, Call, Event}, - Example: pallet::{Pallet, Call, Event, Config, Storage}, - PalletOld: pallet_old::{Pallet, Call, Event, Config, Storage}, - Instance2Example: pallet::::{Pallet, Call, Event, Config, Storage}, - PalletOld2: pallet_old::::{Pallet, Call, Event, Config, Storage}, - Instance3Example: pallet::::{Pallet, Call, Event, Config, Storage}, - PalletOld3: pallet_old::::{Pallet, Call, Event, Config, Storage}, - } -); - -#[cfg(test)] -mod test { - use super::{pallet, pallet_old, Runtime}; - use codec::{Decode, Encode}; - use scale_info::{form::PortableForm, Variant}; - - #[test] - fn metadata() { - let metadata = Runtime::metadata(); - let (pallets, types) = match metadata.1 { - frame_support::metadata::RuntimeMetadata::V14(metadata) => - (metadata.pallets, metadata.types), - _ => unreachable!(), - }; - - let get_enum_variants = |ty_id| match types.resolve(ty_id).map(|ty| ty.type_def.clone()) { - Some(ty) => match ty { - scale_info::TypeDef::Variant(var) => var.variants, - _ => panic!("Expected variant type"), - }, - _ => panic!("No type found"), - }; - - let assert_enum_variants = |vs1: &[Variant], - vs2: &[Variant]| { - assert_eq!(vs1.len(), vs2.len()); - for i in 0..vs1.len() { - let v1 = &vs2[i]; - let v2 = &vs2[i]; - assert_eq!(v1.fields.len(), v2.fields.len()); - for f in 0..v1.fields.len() { - let f1 = &v1.fields[f]; - let f2 = &v2.fields[f]; - pretty_assertions::assert_eq!(f1.name, f2.name); - pretty_assertions::assert_eq!(f1.ty, f2.ty); - } - } - }; - - for i in vec![1, 3, 5].into_iter() { - pretty_assertions::assert_eq!(pallets[i].storage, pallets[i + 1].storage); - - let call1_variants = get_enum_variants(pallets[i].calls.as_ref().unwrap().ty.id); - let call2_variants = get_enum_variants(pallets[i + 1].calls.as_ref().unwrap().ty.id); - assert_enum_variants(&call1_variants, &call2_variants); - - // event: check variants and fields but ignore the type name which will be different - let event1_variants = get_enum_variants(pallets[i].event.as_ref().unwrap().ty.id); - let event2_variants = get_enum_variants(pallets[i + 1].event.as_ref().unwrap().ty.id); - assert_enum_variants(&event1_variants, &event2_variants); - - let err1 = get_enum_variants(pallets[i].error.as_ref().unwrap().ty.id) - .iter() - .filter(|v| v.name == "__Ignore") - .cloned() - .collect::>(); - let err2 = get_enum_variants(pallets[i + 1].error.as_ref().unwrap().ty.id) - .iter() - .filter(|v| v.name == "__Ignore") - .cloned() - .collect::>(); - assert_enum_variants(&err1, &err2); - - pretty_assertions::assert_eq!(pallets[i].constants, pallets[i + 1].constants); - } - } - - #[test] - fn types() { - assert_eq!( - pallet_old::Event::::decode( - &mut &pallet::Event::::Dummy(10).encode()[..] - ) - .unwrap(), - pallet_old::Event::::Dummy(10), - ); - - assert_eq!( - pallet_old::Call::::decode( - &mut &pallet::Call::::set_dummy { new_value: 10 }.encode()[..] - ) - .unwrap(), - pallet_old::Call::::set_dummy { new_value: 10 }, - ); - } -} diff --git a/frame/support/test/tests/pallet_instance.rs b/frame/support/test/tests/pallet_instance.rs index 241492a596993..0747753289af0 100644 --- a/frame/support/test/tests/pallet_instance.rs +++ b/frame/support/test/tests/pallet_instance.rs @@ -18,21 +18,23 @@ use frame_support::{ dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo, Pays, UnfilteredDispatchable}, pallet_prelude::ValueQuery, + parameter_types, storage::unhashed, traits::{ConstU32, GetCallName, OnFinalize, OnGenesis, OnInitialize, OnRuntimeUpgrade}, + weights::Weight, }; use sp_io::{ hashing::{blake2_128, twox_128, twox_64}, TestExternalities, }; use sp_runtime::{DispatchError, ModuleError}; +use sp_std::any::TypeId; #[frame_support::pallet(dev_mode)] pub mod pallet { - use codec::MaxEncodedLen; - use frame_support::{pallet_prelude::*, parameter_types, scale_info}; + use super::*; + use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; - use sp_std::any::TypeId; type BalanceOf = >::Balance; @@ -346,8 +348,6 @@ frame_support::construct_runtime!( } ); -use frame_support::weights::Weight; - #[test] fn call_expand() { let call_foo = pallet::Call::::foo { foo: 3 }; diff --git a/frame/support/test/tests/pallet_with_name_trait_is_valid.rs b/frame/support/test/tests/pallet_with_name_trait_is_valid.rs deleted file mode 100644 index 8cd3c79cc6c08..0000000000000 --- a/frame/support/test/tests/pallet_with_name_trait_is_valid.rs +++ /dev/null @@ -1,158 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -pub trait Trait: frame_system::Config { - type Balance: frame_support::dispatch::Parameter; - /// The overarching event type. - type RuntimeEvent: From> + Into<::RuntimeEvent>; -} - -frame_support::decl_storage! { - trait Store for Module as Example { - Dummy get(fn dummy) config(): Option; - } -} - -frame_support::decl_event!( - pub enum Event - where - B = ::Balance, - { - Dummy(B), - } -); - -frame_support::decl_error!( - pub enum Error for Module { - Dummy, - } -); - -frame_support::decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin { - fn deposit_event() = default; - type Error = Error; - const Foo: u32 = u32::MAX; - - #[weight = 0] - fn accumulate_dummy(_origin, _increase_by: T::Balance) { - unimplemented!(); - } - - fn on_initialize(_n: T::BlockNumber) -> frame_support::weights::Weight { - frame_support::weights::Weight::zero() - } - } -} - -impl sp_runtime::traits::ValidateUnsigned for Module { - type Call = Call; - - fn validate_unsigned( - _source: sp_runtime::transaction_validity::TransactionSource, - _call: &Self::Call, - ) -> sp_runtime::transaction_validity::TransactionValidity { - unimplemented!(); - } -} - -pub const INHERENT_IDENTIFIER: frame_support::inherent::InherentIdentifier = *b"12345678"; - -impl frame_support::inherent::ProvideInherent for Module { - type Call = Call; - type Error = frame_support::inherent::MakeFatalError<()>; - const INHERENT_IDENTIFIER: frame_support::inherent::InherentIdentifier = INHERENT_IDENTIFIER; - - fn create_inherent(_data: &frame_support::inherent::InherentData) -> Option { - unimplemented!(); - } - - fn check_inherent( - _: &Self::Call, - _: &frame_support::inherent::InherentData, - ) -> std::result::Result<(), Self::Error> { - unimplemented!(); - } - - fn is_inherent(_call: &Self::Call) -> bool { - unimplemented!(); - } -} - -#[cfg(test)] -mod tests { - use crate as pallet_test; - - use frame_support::traits::ConstU64; - - type SignedExtra = ( - frame_system::CheckEra, - frame_system::CheckNonce, - frame_system::CheckWeight, - ); - type TestBlock = sp_runtime::generic::Block; - type TestHeader = sp_runtime::generic::Header; - type TestUncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic< - ::AccountId, - ::RuntimeCall, - (), - SignedExtra, - >; - - frame_support::construct_runtime!( - pub struct Runtime where - Block = TestBlock, - NodeBlock = TestBlock, - UncheckedExtrinsic = TestUncheckedExtrinsic - { - System: frame_system::{Pallet, Call, Config, Storage, Event}, - PalletTest: pallet_test::{Pallet, Call, Storage, Event, Config, ValidateUnsigned, Inherent}, - } - ); - - impl frame_system::Config for Runtime { - type BaseCallFilter = frame_support::traits::Everything; - type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u64; - type Hash = sp_core::H256; - type RuntimeCall = RuntimeCall; - type Hashing = sp_runtime::traits::BlakeTwo256; - type AccountId = u64; - type Lookup = sp_runtime::traits::IdentityLookup; - type Header = TestHeader; - type RuntimeEvent = (); - type BlockHashCount = ConstU64<250>; - type DbWeight = (); - type BlockWeights = (); - type BlockLength = (); - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = (); - type OnSetCode = (); - type MaxConsumers = frame_support::traits::ConstU32<16>; - } - - impl pallet_test::Trait for Runtime { - type Balance = u32; - type RuntimeEvent = (); - } -} diff --git a/frame/support/test/tests/storage_layers.rs b/frame/support/test/tests/storage_layers.rs index 82174bf9d7141..3e306834869bb 100644 --- a/frame/support/test/tests/storage_layers.rs +++ b/frame/support/test/tests/storage_layers.rs @@ -16,7 +16,7 @@ // limitations under the License. use frame_support::{ - assert_noop, assert_ok, dispatch::DispatchResult, pallet_prelude::ConstU32, + assert_noop, assert_ok, dispatch::DispatchResult, ensure, pallet_prelude::ConstU32, storage::with_storage_layer, }; use pallet::*; @@ -24,7 +24,8 @@ use sp_io::TestExternalities; #[frame_support::pallet(dev_mode)] pub mod pallet { - use frame_support::{ensure, pallet_prelude::*}; + use super::*; + use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; #[pallet::pallet] @@ -56,48 +57,29 @@ pub mod pallet { } } -pub mod decl_pallet { - pub trait Config: frame_system::Config {} - - frame_support::decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin { - #[weight = 0] - pub fn set_value(_origin, value: u32) { - DeclValue::put(value); - frame_support::ensure!(value != 1, "Revert!"); - } - } - } - - frame_support::decl_storage! { - trait Store for Module as StorageTransactions { - pub DeclValue: u32; - } - } -} - -pub type BlockNumber = u64; +pub type BlockNumber = u32; pub type Index = u64; -pub type Header = sp_runtime::generic::Header; -pub type Block = sp_runtime::generic::Block; +pub type AccountId = u64; +pub type Header = sp_runtime::generic::Header; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; +pub type Block = sp_runtime::generic::Block; impl frame_system::Config for Runtime { + type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); type BlockLength = (); - type DbWeight = (); - type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; - type Index = u64; - type BlockNumber = u32; type RuntimeCall = RuntimeCall; + type Index = Index; + type BlockNumber = BlockNumber; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; - type AccountId = u64; + type AccountId = AccountId; type Lookup = sp_runtime::traits::IdentityLookup; type Header = Header; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU32<250>; + type DbWeight = (); type Version = (); type PalletInfo = PalletInfo; type AccountData = (); @@ -109,19 +91,17 @@ impl frame_system::Config for Runtime { type MaxConsumers = ConstU32<16>; } -impl pallet::Config for Runtime {} - -impl decl_pallet::Config for Runtime {} +impl Config for Runtime {} frame_support::construct_runtime!( - pub struct Runtime where + pub struct Runtime + where Block = Block, NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic + UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system, MyPallet: pallet, - DeclPallet: decl_pallet::{Call, Storage}, } ); @@ -264,23 +244,3 @@ fn storage_layer_in_pallet_call() { assert_noop!(call2.dispatch(RuntimeOrigin::signed(0)), Error::::Revert); }); } - -#[test] -fn storage_layer_in_decl_pallet_call() { - TestExternalities::default().execute_with(|| { - use frame_support::StorageValue; - use sp_runtime::traits::Dispatchable; - - let call1 = RuntimeCall::DeclPallet(decl_pallet::Call::set_value { value: 2 }); - assert_ok!(call1.dispatch(RuntimeOrigin::signed(0))); - assert_eq!(decl_pallet::DeclValue::get(), 2); - - let call2 = RuntimeCall::DeclPallet(decl_pallet::Call::set_value { value: 1 }); - assert_noop!(call2.dispatch(RuntimeOrigin::signed(0)), "Revert!"); - // Calling the function directly also works with storage layers. - assert_noop!( - decl_pallet::Module::::set_value(RuntimeOrigin::signed(1), 1), - "Revert!" - ); - }); -} diff --git a/frame/support/test/tests/storage_transaction.rs b/frame/support/test/tests/storage_transaction.rs index 769ecb29a8db2..5fc4ba7cca6d9 100644 --- a/frame/support/test/tests/storage_transaction.rs +++ b/frame/support/test/tests/storage_transaction.rs @@ -20,46 +20,86 @@ use frame_support::{ assert_noop, assert_ok, assert_storage_noop, - dispatch::{DispatchError, DispatchResult}, + dispatch::DispatchResult, storage::{with_transaction, TransactionOutcome::*}, - transactional, StorageMap, StorageValue, + transactional, }; +use sp_core::sr25519; use sp_io::TestExternalities; -use sp_runtime::TransactionOutcome; -use sp_std::result; +use sp_runtime::{ + generic, + traits::{BlakeTwo256, Verify}, + TransactionOutcome, +}; + +pub use self::pallet::*; + +#[frame_support::pallet] +pub mod pallet { + use self::frame_system::pallet_prelude::*; + use super::*; + use frame_support::pallet_prelude::*; + use frame_support_test as frame_system; -pub trait Config: frame_support_test::Config {} + #[pallet::pallet] + #[pallet::generate_store(pub (super) trait Store)] + pub struct Pallet(_); -frame_support::decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin, system=frame_support_test { - #[weight = 0] + #[pallet::config] + pub trait Config: frame_system::Config {} + + #[pallet::call] + impl Pallet { + #[pallet::weight(0)] #[transactional] - fn value_commits(_origin, v: u32) { - Value::set(v); + pub fn value_commits(_origin: OriginFor, v: u32) -> DispatchResult { + >::set(v); + Ok(()) } - #[weight = 0] + #[pallet::weight(0)] #[transactional] - fn value_rollbacks(_origin, v: u32) -> DispatchResult { - Value::set(v); + pub fn value_rollbacks(_origin: OriginFor, v: u32) -> DispatchResult { + >::set(v); Err(DispatchError::Other("nah")) } } -} -frame_support::decl_storage! { - trait Store for Module as StorageTransactions { - pub Value: u32; - pub Map: map hasher(twox_64_concat) String => u32; - } + #[pallet::storage] + pub type Value = StorageValue<_, u32, ValueQuery>; + + #[pallet::storage] + #[pallet::unbounded] + pub type Map = StorageMap<_, Twox64Concat, String, u32, ValueQuery>; } -struct Runtime; +pub type BlockNumber = u32; +pub type Signature = sr25519::Signature; +pub type AccountId = ::Signer; +pub type Header = generic::Header; +pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; +pub type Block = generic::Block; + +frame_support::construct_runtime!( + pub enum Runtime + where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_support_test, + MyPallet: pallet, + } +); impl frame_support_test::Config for Runtime { - type RuntimeOrigin = u32; - type BlockNumber = u32; - type PalletInfo = frame_support_test::PanicPalletInfo; + type BlockNumber = BlockNumber; + type AccountId = AccountId; + type BaseCallFilter = frame_support::traits::Everything; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type PalletInfo = PalletInfo; type DbWeight = (); } @@ -68,6 +108,9 @@ impl Config for Runtime {} #[test] fn storage_transaction_basic_commit() { TestExternalities::default().execute_with(|| { + type Value = pallet::Value; + type Map = pallet::Map; + assert_eq!(Value::get(), 0); assert!(!Map::contains_key("val0")); @@ -87,6 +130,9 @@ fn storage_transaction_basic_commit() { #[test] fn storage_transaction_basic_rollback() { TestExternalities::default().execute_with(|| { + type Value = pallet::Value; + type Map = pallet::Map; + assert_eq!(Value::get(), 0); assert_eq!(Map::get("val0"), 0); @@ -119,6 +165,9 @@ fn storage_transaction_basic_rollback() { #[test] fn storage_transaction_rollback_then_commit() { TestExternalities::default().execute_with(|| { + type Value = pallet::Value; + type Map = pallet::Map; + Value::set(1); Map::insert("val1", 1); @@ -162,6 +211,9 @@ fn storage_transaction_rollback_then_commit() { #[test] fn storage_transaction_commit_then_rollback() { TestExternalities::default().execute_with(|| { + type Value = pallet::Value; + type Map = pallet::Map; + Value::set(1); Map::insert("val1", 1); @@ -204,19 +256,21 @@ fn storage_transaction_commit_then_rollback() { #[test] fn transactional_annotation() { + type Value = pallet::Value; + fn set_value(v: u32) -> DispatchResult { Value::set(v); Ok(()) } #[transactional] - fn value_commits(v: u32) -> result::Result { + fn value_commits(v: u32) -> Result { set_value(v)?; Ok(v) } #[transactional] - fn value_rollbacks(v: u32) -> result::Result { + fn value_rollbacks(v: u32) -> Result { set_value(v)?; Err("nah")?; Ok(v) @@ -229,14 +283,3 @@ fn transactional_annotation() { assert_noop!(value_rollbacks(3), "nah"); }); } - -#[test] -fn transactional_annotation_in_decl_module() { - TestExternalities::default().execute_with(|| { - let origin = 0; - assert_ok!(>::value_commits(origin, 2)); - assert_eq!(Value::get(), 2); - - assert_noop!(>::value_rollbacks(origin, 3), "nah"); - }); -} diff --git a/frame/support/test/tests/system.rs b/frame/support/test/tests/system.rs deleted file mode 100644 index 1a938ad4e80db..0000000000000 --- a/frame/support/test/tests/system.rs +++ /dev/null @@ -1,81 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use frame_support::{ - codec::{Decode, Encode, EncodeLike}, - traits::Get, - weights::RuntimeDbWeight, -}; - -pub trait Config: 'static + Eq + Clone { - type RuntimeOrigin: Into, Self::RuntimeOrigin>> - + From>; - - type BaseCallFilter: frame_support::traits::Contains; - type BlockNumber: Decode + Encode + EncodeLike + Clone + Default + scale_info::TypeInfo; - type Hash; - type AccountId: Encode + EncodeLike + Decode + scale_info::TypeInfo; - type RuntimeCall; - type RuntimeEvent: From>; - type PalletInfo: frame_support::traits::PalletInfo; - type DbWeight: Get; -} - -frame_support::decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self { - #[weight = 0] - fn noop(_origin) {} - } -} - -impl Module { - pub fn deposit_event(_event: impl Into) {} -} - -frame_support::decl_event!( - pub enum Event - where - BlockNumber = ::BlockNumber, - { - ExtrinsicSuccess, - ExtrinsicFailed, - Ignore(BlockNumber), - } -); - -frame_support::decl_error! { - pub enum Error for Module { - /// Test error documentation - TestError, - /// Error documentation - /// with multiple lines - AnotherError, - // Required by construct_runtime - CallFiltered, - } -} - -pub use frame_support::dispatch::RawOrigin; -pub type Origin = RawOrigin<::AccountId>; - -#[allow(dead_code)] -pub fn ensure_root(o: OuterOrigin) -> Result<(), &'static str> -where - OuterOrigin: Into, OuterOrigin>>, -{ - o.into().map(|_| ()).map_err(|_| "bad origin: expected to be a root origin") -}