From 12a0f532ec4899ff1acd9a5ac7ffbf5ffaf177fa Mon Sep 17 00:00:00 2001 From: koushiro Date: Mon, 3 Oct 2022 15:12:24 +0800 Subject: [PATCH 01/13] frame-support: migrate some tests from decl macros to new pallet attribute macros --- frame/support/src/dispatch.rs | 178 +++++++++----- frame/support/src/lib.rs | 231 ++++++++++++------ .../src/storage/generator/double_map.rs | 44 +--- frame/support/src/storage/generator/map.rs | 44 +--- frame/support/src/storage/generator/mod.rs | 129 ++++++++-- frame/support/src/storage/generator/nmap.rs | 64 ++--- 6 files changed, 416 insertions(+), 274 deletions(-) diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index db2bc90658ee2..6999432154f75 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -3496,111 +3496,177 @@ mod tests { #[allow(dead_code)] mod weight_tests { use super::*; - use sp_core::{parameter_types, Get}; + use sp_core::parameter_types; + use sp_runtime::{generic, traits::BlakeTwo256}; use sp_weights::RuntimeDbWeight; - pub trait Config: 'static { - type RuntimeOrigin; - type Balance; - type BlockNumber; - type DbWeight: Get; - type PalletInfo: crate::traits::PalletInfo; - } + pub use self::frame_system::{Call, Config, Pallet}; - pub struct TraitImpl {} + #[crate::pallet] + pub mod frame_system { + use super::{frame_system, frame_system::pallet_prelude::*}; + pub use crate::dispatch::RawOrigin; + use crate::pallet_prelude::*; - parameter_types! { - pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight { - read: 100, - write: 1000, - }; - } + #[pallet::pallet] + #[pallet::generate_store(pub (super) trait Store)] + pub struct Pallet(PhantomData); - impl Config for TraitImpl { - type RuntimeOrigin = u32; - type BlockNumber = u32; - type Balance = u32; - type DbWeight = DbWeight; - type PalletInfo = crate::tests::PanicPalletInfo; - } + #[pallet::config] + #[pallet::disable_frame_system_supertrait_check] + pub trait Config: 'static { + type BlockNumber: Parameter + Default + MaxEncodedLen; + type AccountId; + type Balance; + type BaseCallFilter: crate::traits::Contains; + type RuntimeOrigin; + type RuntimeCall; + type PalletInfo: crate::traits::PalletInfo; + type DbWeight: Get; + } - decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self { + #[pallet::error] + pub enum Error { + /// Required by construct_runtime + CallFiltered, + } + + #[pallet::origin] + pub type Origin = RawOrigin<::AccountId>; + + #[pallet::call] + impl Pallet { // no arguments, fixed weight - #[weight = 1000] - fn f00(_origin) { unimplemented!(); } + #[pallet::weight(1000)] + pub fn f00(_origin: OriginFor) -> DispatchResult { + unimplemented!(); + } - #[weight = (1000, DispatchClass::Mandatory)] - fn f01(_origin) { unimplemented!(); } + #[pallet::weight((1000, DispatchClass::Mandatory))] + pub fn f01(_origin: OriginFor) -> DispatchResult { + unimplemented!(); + } - #[weight = (1000, Pays::No)] - fn f02(_origin) { unimplemented!(); } + #[pallet::weight((1000, Pays::No))] + pub fn f02(_origin: OriginFor) -> DispatchResult { + unimplemented!(); + } - #[weight = (1000, DispatchClass::Operational, Pays::No)] - fn f03(_origin) { unimplemented!(); } + #[pallet::weight((1000, DispatchClass::Operational, Pays::No))] + pub fn f03(_origin: OriginFor) -> DispatchResult { + unimplemented!(); + } // weight = a x 10 + b - #[weight = ((_a * 10 + _eb * 1) as u64, DispatchClass::Normal, Pays::Yes)] - fn f11(_origin, _a: u32, _eb: u32) { unimplemented!(); } + #[pallet::weight(((_a * 10 + _eb * 1) as u64, DispatchClass::Normal, Pays::Yes))] + pub fn f11(_origin: OriginFor, _a: u32, _eb: u32) -> DispatchResult { + unimplemented!(); + } - #[weight = (0, DispatchClass::Operational, Pays::Yes)] - fn f12(_origin, _a: u32, _eb: u32) { unimplemented!(); } + #[pallet::weight((0, DispatchClass::Operational, Pays::Yes))] + pub fn f12(_origin: OriginFor, _a: u32, _eb: u32) -> DispatchResult { + unimplemented!(); + } - #[weight = T::DbWeight::get().reads(3) + T::DbWeight::get().writes(2) + Weight::from_ref_time(10_000)] - fn f20(_origin) { unimplemented!(); } + #[pallet::weight(T::DbWeight::get().reads(3) + T::DbWeight::get().writes(2) + Weight::from_ref_time(10_000))] + pub fn f20(_origin: OriginFor) -> DispatchResult { + unimplemented!(); + } + + #[pallet::weight(T::DbWeight::get().reads_writes(6, 5) + Weight::from_ref_time(40_000))] + pub fn f21(_origin: OriginFor) -> DispatchResult { + unimplemented!(); + } + } + + pub mod pallet_prelude { + pub type OriginFor = ::RuntimeOrigin; + } + } - #[weight = T::DbWeight::get().reads_writes(6, 5) + Weight::from_ref_time(40_000)] - fn f21(_origin) { unimplemented!(); } + type BlockNumber = u32; + type AccountId = u32; + type Balance = u32; + type Header = generic::Header; + type UncheckedExtrinsic = generic::UncheckedExtrinsic; + type Block = generic::Block; + crate::construct_runtime!( + pub enum Runtime + where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: self::frame_system, } + ); + + parameter_types! { + pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight { + read: 100, + write: 1000, + }; + } + + impl Config for Runtime { + type BlockNumber = BlockNumber; + type AccountId = AccountId; + type Balance = Balance; + type BaseCallFilter = crate::traits::Everything; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type PalletInfo = PalletInfo; + type DbWeight = DbWeight; } #[test] fn weights_are_correct() { - // #[weight = 1000] - let info = Call::::f00 {}.get_dispatch_info(); + // #[pallet::weight(1000)] + let info = Call::::f00 {}.get_dispatch_info(); assert_eq!(info.weight, Weight::from_ref_time(1000)); assert_eq!(info.class, DispatchClass::Normal); assert_eq!(info.pays_fee, Pays::Yes); - // #[weight = (1000, DispatchClass::Mandatory)] - let info = Call::::f01 {}.get_dispatch_info(); + // #[pallet::weight((1000, DispatchClass::Mandatory))] + let info = Call::::f01 {}.get_dispatch_info(); assert_eq!(info.weight, Weight::from_ref_time(1000)); assert_eq!(info.class, DispatchClass::Mandatory); assert_eq!(info.pays_fee, Pays::Yes); - // #[weight = (1000, Pays::No)] - let info = Call::::f02 {}.get_dispatch_info(); + // #[pallet::weight((1000, Pays::No))] + let info = Call::::f02 {}.get_dispatch_info(); assert_eq!(info.weight, Weight::from_ref_time(1000)); assert_eq!(info.class, DispatchClass::Normal); assert_eq!(info.pays_fee, Pays::No); - // #[weight = (1000, DispatchClass::Operational, Pays::No)] - let info = Call::::f03 {}.get_dispatch_info(); + // #[pallet::weight((1000, DispatchClass::Operational, Pays::No))] + let info = Call::::f03 {}.get_dispatch_info(); assert_eq!(info.weight, Weight::from_ref_time(1000)); assert_eq!(info.class, DispatchClass::Operational); assert_eq!(info.pays_fee, Pays::No); - // #[weight = ((_a * 10 + _eb * 1) as Weight, DispatchClass::Normal, Pays::Yes)] - let info = Call::::f11 { _a: 13, _eb: 20 }.get_dispatch_info(); + // #[pallet::weight(((_a * 10 + _eb * 1) as u64, DispatchClass::Normal, Pays::Yes))] + let info = Call::::f11 { a: 13, eb: 20 }.get_dispatch_info(); assert_eq!(info.weight, Weight::from_ref_time(150)); // 13*10 + 20 assert_eq!(info.class, DispatchClass::Normal); assert_eq!(info.pays_fee, Pays::Yes); - // #[weight = (0, DispatchClass::Operational, Pays::Yes)] - let info = Call::::f12 { _a: 10, _eb: 20 }.get_dispatch_info(); + // #[pallet::weight((0, DispatchClass::Operational, Pays::Yes))] + let info = Call::::f12 { a: 10, eb: 20 }.get_dispatch_info(); assert_eq!(info.weight, Weight::from_ref_time(0)); assert_eq!(info.class, DispatchClass::Operational); assert_eq!(info.pays_fee, Pays::Yes); - // #[weight = T::DbWeight::get().reads(3) + T::DbWeight::get().writes(2) + 10_000] - let info = Call::::f20 {}.get_dispatch_info(); + // #[pallet::weight(T::DbWeight::get().reads(3) + T::DbWeight::get().writes(2) + + // Weight::from_ref_time(10_000))] + let info = Call::::f20 {}.get_dispatch_info(); assert_eq!(info.weight, Weight::from_ref_time(12300)); // 100*3 + 1000*2 + 10_1000 assert_eq!(info.class, DispatchClass::Normal); assert_eq!(info.pays_fee, Pays::Yes); - // #[weight = T::DbWeight::get().reads_writes(6, 5) + 40_000] - let info = Call::::f21 {}.get_dispatch_info(); + // #[pallet::weight(T::DbWeight::get().reads_writes(6, 5) + Weight::from_ref_time(40_000))] + let info = Call::::f21 {}.get_dispatch_info(); assert_eq!(info.weight, Weight::from_ref_time(45600)); // 100*6 + 1000*5 + 40_1000 assert_eq!(info.class, DispatchClass::Normal); assert_eq!(info.pays_fee, Pays::Yes); diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 51aa05261dac3..ebe00393b110c 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -821,76 +821,153 @@ pub mod tests { PalletStorageMetadata, StorageEntryMetadata, StorageEntryModifier, StorageEntryType, StorageHasher, }; - use codec::{Codec, EncodeLike}; - use frame_support::traits::CrateVersion; use sp_io::{MultiRemovalResults, TestExternalities}; - use sp_std::result; + use sp_runtime::{generic, traits::BlakeTwo256, BuildStorage}; - /// A PalletInfo implementation which just panics. - pub struct PanicPalletInfo; + pub use self::frame_system::{Config, Pallet}; - impl crate::traits::PalletInfo for PanicPalletInfo { - fn index() -> Option { - unimplemented!("PanicPalletInfo mustn't be triggered by tests"); - } - fn name() -> Option<&'static str> { - unimplemented!("PanicPalletInfo mustn't be triggered by tests"); - } - fn module_name() -> Option<&'static str> { - unimplemented!("PanicPalletInfo mustn't be triggered by tests"); - } - fn crate_version() -> Option { - unimplemented!("PanicPalletInfo mustn't be triggered by tests"); + #[crate::pallet] + pub mod frame_system { + #[allow(unused)] + use super::{frame_system, frame_system::pallet_prelude::*}; + pub use crate::dispatch::RawOrigin; + use crate::pallet_prelude::*; + + #[pallet::pallet] + #[pallet::generate_store(pub (super) trait Store)] + pub struct Pallet(PhantomData); + + #[pallet::config] + #[pallet::disable_frame_system_supertrait_check] + pub trait Config: 'static { + type BlockNumber: Parameter + Default + MaxEncodedLen; + type AccountId; + type BaseCallFilter: crate::traits::Contains; + type RuntimeOrigin; + type RuntimeCall; + type PalletInfo: crate::traits::PalletInfo; + type DbWeight: Get; } - } - pub trait Config: 'static { - type BlockNumber: Codec + EncodeLike + Default + TypeInfo; - type RuntimeOrigin; - type PalletInfo: crate::traits::PalletInfo; - type DbWeight: crate::traits::Get; - } + #[pallet::error] + pub enum Error { + /// Required by construct_runtime + CallFiltered, + } - mod module { - #![allow(dead_code)] + #[pallet::origin] + pub type Origin = RawOrigin<::AccountId>; + + #[pallet::call] + impl Pallet {} + + #[pallet::storage] + pub type Data = StorageMap<_, Twox64Concat, u32, u64, ValueQuery>; + + #[pallet::storage] + pub type OptionLinkedMap = StorageMap<_, Blake2_128Concat, u32, u32, OptionQuery>; + + #[pallet::storage] + #[pallet::getter(fn generic_data)] + pub type GenericData = + StorageMap<_, Identity, T::BlockNumber, T::BlockNumber, ValueQuery>; + + #[pallet::storage] + #[pallet::getter(fn generic_data2)] + pub type GenericData2 = + StorageMap<_, Blake2_128Concat, T::BlockNumber, T::BlockNumber, OptionQuery>; + + #[pallet::storage] + pub type DataDM = + StorageDoubleMap<_, Twox64Concat, u32, Blake2_128Concat, u32, u64, ValueQuery>; + + #[pallet::storage] + pub type GenericDataDM = StorageDoubleMap< + _, + Blake2_128Concat, + T::BlockNumber, + Identity, + T::BlockNumber, + T::BlockNumber, + ValueQuery, + >; + + #[pallet::storage] + pub type GenericData2DM = StorageDoubleMap< + _, + Blake2_128Concat, + T::BlockNumber, + Twox64Concat, + T::BlockNumber, + T::BlockNumber, + OptionQuery, + >; + + #[pallet::storage] + #[pallet::unbounded] + pub type AppendableDM = StorageDoubleMap< + _, + Blake2_128Concat, + u32, + Blake2_128Concat, + T::BlockNumber, + Vec, + ValueQuery, + >; + + #[pallet::genesis_config] + pub struct GenesisConfig { + pub data: Vec<(u32, u64)>, + pub test_config: Vec<(u32, u32, u64)>, + } - use super::Config; + impl Default for GenesisConfig { + fn default() -> Self { + Self { data: vec![(15u32, 42u64)], test_config: vec![(15u32, 16u32, 42u64)] } + } + } - decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self {} + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) { + for (k, v) in &self.data { + >::insert(k, v); + } + for (k1, k2, v) in &self.test_config { + >::insert(k1, k2, v); + } + } } - } - use self::module::Module; - - decl_storage! { - trait Store for Module as Test { - pub Data get(fn data) build(|_| vec![(15u32, 42u64)]): - map hasher(twox_64_concat) u32 => u64; - pub OptionLinkedMap: map hasher(blake2_128_concat) u32 => Option; - pub GenericData get(fn generic_data): - map hasher(identity) T::BlockNumber => T::BlockNumber; - pub GenericData2 get(fn generic_data2): - map hasher(blake2_128_concat) T::BlockNumber => Option; - pub DataDM config(test_config) build(|_| vec![(15u32, 16u32, 42u64)]): - double_map hasher(twox_64_concat) u32, hasher(blake2_128_concat) u32 => u64; - pub GenericDataDM: - double_map hasher(blake2_128_concat) T::BlockNumber, hasher(identity) T::BlockNumber - => T::BlockNumber; - pub GenericData2DM: - double_map hasher(blake2_128_concat) T::BlockNumber, hasher(twox_64_concat) T::BlockNumber - => Option; - pub AppendableDM: - double_map hasher(blake2_128_concat) u32, hasher(blake2_128_concat) T::BlockNumber => Vec; + pub mod pallet_prelude { + pub type OriginFor = ::RuntimeOrigin; } } - struct Test; + type BlockNumber = u32; + type AccountId = u32; + type Header = generic::Header; + type UncheckedExtrinsic = generic::UncheckedExtrinsic; + type Block = generic::Block; + + crate::construct_runtime!( + pub enum Runtime + where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: self::frame_system, + } + ); - impl Config for Test { - type BlockNumber = u32; - type RuntimeOrigin = u32; - type PalletInfo = PanicPalletInfo; + impl Config for Runtime { + type BlockNumber = BlockNumber; + type AccountId = AccountId; + type BaseCallFilter = crate::traits::Everything; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type PalletInfo = PalletInfo; type DbWeight = (); } @@ -898,8 +975,6 @@ pub mod tests { GenesisConfig::default().build_storage().unwrap().into() } - type Map = Data; - trait Sorted { fn sorted(self) -> Self; } @@ -916,15 +991,15 @@ pub mod tests { new_test_ext().execute_with(|| { #[crate::storage_alias] type GenericData2 = StorageMap< - Test, + System, Blake2_128Concat, ::BlockNumber, ::BlockNumber, >; - assert_eq!(Module::::generic_data2(5), None); - GenericData2::::insert(5, 5); - assert_eq!(Module::::generic_data2(5), Some(5)); + assert_eq!(Pallet::::generic_data2(5), None); + GenericData2::::insert(5, 5); + assert_eq!(Pallet::::generic_data2(5), Some(5)); /// Some random docs that ensure that docs are accepted #[crate::storage_alias] @@ -940,6 +1015,8 @@ pub mod tests { #[test] fn map_issue_3318() { new_test_ext().execute_with(|| { + type OptionLinkedMap = self::frame_system::OptionLinkedMap; + OptionLinkedMap::insert(1, 1); assert_eq!(OptionLinkedMap::get(1), Some(1)); OptionLinkedMap::insert(1, 2); @@ -950,6 +1027,8 @@ pub mod tests { #[test] fn map_swap_works() { new_test_ext().execute_with(|| { + type OptionLinkedMap = self::frame_system::OptionLinkedMap; + OptionLinkedMap::insert(0, 0); OptionLinkedMap::insert(1, 1); OptionLinkedMap::insert(2, 2); @@ -979,6 +1058,8 @@ pub mod tests { #[test] fn double_map_swap_works() { new_test_ext().execute_with(|| { + type DataDM = self::frame_system::DataDM; + DataDM::insert(0, 1, 1); DataDM::insert(1, 0, 2); DataDM::insert(1, 1, 3); @@ -1011,6 +1092,8 @@ pub mod tests { #[test] fn map_basic_insert_remove_should_work() { new_test_ext().execute_with(|| { + type Map = self::frame_system::Data; + // initialized during genesis assert_eq!(Map::get(&15u32), 42u64); @@ -1037,6 +1120,8 @@ pub mod tests { #[test] fn map_iteration_should_work() { new_test_ext().execute_with(|| { + type Map = self::frame_system::Data; + assert_eq!(Map::iter().collect::>().sorted(), vec![(15, 42)]); // insert / remove let key = 17u32; @@ -1090,7 +1175,7 @@ pub mod tests { fn double_map_basic_insert_remove_remove_prefix_with_commit_should_work() { let key1 = 17u32; let key2 = 18u32; - type DoubleMap = DataDM; + type DoubleMap = self::frame_system::DataDM; let mut e = new_test_ext(); e.execute_with(|| { // initialized during genesis @@ -1135,7 +1220,7 @@ pub mod tests { new_test_ext().execute_with(|| { let key1 = 17u32; let key2 = 18u32; - type DoubleMap = DataDM; + type DoubleMap = self::frame_system::DataDM; // initialized during genesis assert_eq!(DoubleMap::get(&15u32, &16u32), 42u64); @@ -1183,7 +1268,7 @@ pub mod tests { #[test] fn double_map_append_should_work() { new_test_ext().execute_with(|| { - type DoubleMap = AppendableDM; + type DoubleMap = self::frame_system::AppendableDM; let key1 = 17u32; let key2 = 18u32; @@ -1197,7 +1282,7 @@ pub mod tests { #[test] fn double_map_mutate_exists_should_work() { new_test_ext().execute_with(|| { - type DoubleMap = DataDM; + type DoubleMap = self::frame_system::DataDM; let (key1, key2) = (11, 13); @@ -1214,8 +1299,8 @@ pub mod tests { #[test] fn double_map_try_mutate_exists_should_work() { new_test_ext().execute_with(|| { - type DoubleMap = DataDM; - type TestResult = result::Result<(), &'static str>; + type DoubleMap = self::frame_system::DataDM; + type TestResult = Result<(), &'static str>; let (key1, key2) = (11, 13); @@ -1246,7 +1331,7 @@ pub mod tests { fn expected_metadata() -> PalletStorageMetadata { PalletStorageMetadata { - prefix: "Test", + prefix: "System", entries: vec![ StorageEntryMetadata { name: "Data", @@ -1345,7 +1430,7 @@ pub mod tests { #[test] fn store_metadata() { - let metadata = Module::::storage_metadata(); + let metadata = Pallet::::storage_metadata(); pretty_assertions::assert_eq!(expected_metadata(), metadata); } @@ -1364,12 +1449,6 @@ pub mod tests { assert_eq!(300, StorageParameter::get()); }) } - - parameter_types! { - pub const BlockHashCount: u64 = 250; - pub static Members: Vec = vec![]; - pub const Foo: Option = None; - } } /// Prelude to be used alongside pallet macro, for ease of use. diff --git a/frame/support/src/storage/generator/double_map.rs b/frame/support/src/storage/generator/double_map.rs index c95dcee9d7e5c..db45228c0df3f 100644 --- a/frame/support/src/storage/generator/double_map.rs +++ b/frame/support/src/storage/generator/double_map.rs @@ -507,48 +507,18 @@ where mod test_iterators { use crate::{ hash::StorageHasher, - storage::{generator::StorageDoubleMap, unhashed, IterableStorageDoubleMap}, + storage::{ + generator::{tests::*, StorageDoubleMap}, + unhashed, + }, }; - use codec::{Decode, Encode}; - - pub trait Config: 'static { - type RuntimeOrigin; - type BlockNumber; - type PalletInfo: crate::traits::PalletInfo; - type DbWeight: crate::traits::Get; - } - - crate::decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self {} - } - - #[derive(PartialEq, Eq, Clone, Encode, Decode)] - struct NoDef(u32); - - crate::decl_storage! { - trait Store for Module as Test { - DoubleMap: double_map hasher(blake2_128_concat) u16, hasher(twox_64_concat) u32 => u64; - } - } - - fn key_before_prefix(mut prefix: Vec) -> Vec { - let last = prefix.iter_mut().last().unwrap(); - assert!(*last != 0, "mock function not implemented for this prefix"); - *last -= 1; - prefix - } - - fn key_after_prefix(mut prefix: Vec) -> Vec { - let last = prefix.iter_mut().last().unwrap(); - assert!(*last != 255, "mock function not implemented for this prefix"); - *last += 1; - prefix - } + use codec::Encode; #[test] fn double_map_iter_from() { sp_io::TestExternalities::default().execute_with(|| { use crate::hash::Identity; + type MyModule = self::frame_system::Pallet; #[crate::storage_alias] type MyDoubleMap = StorageDoubleMap; @@ -582,6 +552,8 @@ mod test_iterators { #[test] fn double_map_reversible_reversible_iteration() { sp_io::TestExternalities::default().execute_with(|| { + type DoubleMap = self::frame_system::DoubleMap; + // All map iterator let prefix = DoubleMap::prefix_hash(); diff --git a/frame/support/src/storage/generator/map.rs b/frame/support/src/storage/generator/map.rs index f6c8eaa270bb3..ea225cb91cc9d 100644 --- a/frame/support/src/storage/generator/map.rs +++ b/frame/support/src/storage/generator/map.rs @@ -349,48 +349,18 @@ impl> storage::StorageMap mod test_iterators { use crate::{ hash::StorageHasher, - storage::{generator::StorageMap, unhashed, IterableStorageMap}, + storage::{ + generator::{tests::*, StorageMap}, + unhashed, + }, }; - use codec::{Decode, Encode}; - - pub trait Config: 'static { - type RuntimeOrigin; - type BlockNumber; - type PalletInfo: crate::traits::PalletInfo; - type DbWeight: crate::traits::Get; - } - - crate::decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self {} - } - - #[derive(PartialEq, Eq, Clone, Encode, Decode)] - struct NoDef(u32); - - crate::decl_storage! { - trait Store for Module as Test { - Map: map hasher(blake2_128_concat) u16 => u64; - } - } - - fn key_before_prefix(mut prefix: Vec) -> Vec { - let last = prefix.iter_mut().last().unwrap(); - assert!(*last != 0, "mock function not implemented for this prefix"); - *last -= 1; - prefix - } - - fn key_after_prefix(mut prefix: Vec) -> Vec { - let last = prefix.iter_mut().last().unwrap(); - assert!(*last != 255, "mock function not implemented for this prefix"); - *last += 1; - prefix - } + use codec::Encode; #[test] fn map_iter_from() { sp_io::TestExternalities::default().execute_with(|| { use crate::hash::Identity; + type MyModule = self::frame_system::Pallet; #[crate::storage_alias] type MyMap = StorageMap; @@ -413,6 +383,8 @@ mod test_iterators { #[test] fn map_reversible_reversible_iteration() { sp_io::TestExternalities::default().execute_with(|| { + type Map = self::frame_system::Map; + // All map iterator let prefix = Map::prefix_hash(); diff --git a/frame/support/src/storage/generator/mod.rs b/frame/support/src/storage/generator/mod.rs index 334e9b9e24e86..1bf5ddab27223 100644 --- a/frame/support/src/storage/generator/mod.rs +++ b/frame/support/src/storage/generator/mod.rs @@ -35,47 +35,124 @@ pub use nmap::StorageNMap; pub use value::StorageValue; #[cfg(test)] -#[allow(dead_code)] mod tests { + use codec::Encode; + use sp_io::TestExternalities; + use sp_runtime::{generic, traits::BlakeTwo256, BuildStorage}; + use crate::{ assert_noop, assert_ok, - storage::{generator::StorageValue, unhashed, IterableStorageMap}, + storage::{generator::StorageValue, unhashed}, }; - use codec::Encode; - use sp_io::TestExternalities; - struct Runtime; + #[crate::pallet] + pub mod frame_system { + #[allow(unused)] + use super::{frame_system, frame_system::pallet_prelude::*}; + pub use crate::dispatch::RawOrigin; + use crate::pallet_prelude::*; + + #[pallet::pallet] + #[pallet::generate_store(pub (super) trait Store)] + pub struct Pallet(PhantomData); + + #[pallet::config] + #[pallet::disable_frame_system_supertrait_check] + pub trait Config: 'static { + type BlockNumber; + type AccountId; + type BaseCallFilter: crate::traits::Contains; + type RuntimeOrigin; + type RuntimeCall; + type PalletInfo: crate::traits::PalletInfo; + type DbWeight: Get; + } + + #[pallet::origin] + pub type Origin = RawOrigin<::AccountId>; + + #[pallet::error] + pub enum Error { + /// Required by construct_runtime + CallFiltered, + } + + #[pallet::call] + impl Pallet {} + + #[pallet::storage] + pub type Value = StorageValue<_, (u64, u64), ValueQuery>; - pub trait Config: 'static { - type RuntimeOrigin; - type BlockNumber; - type PalletInfo: crate::traits::PalletInfo; - type DbWeight: crate::traits::Get; + #[pallet::storage] + pub type Map = StorageMap<_, Blake2_128Concat, u16, u64, ValueQuery>; + + #[pallet::storage] + pub type NumberMap = StorageMap<_, Identity, u32, u64, ValueQuery>; + + #[pallet::storage] + pub type DoubleMap = + StorageDoubleMap<_, Blake2_128Concat, u16, Twox64Concat, u32, u64, ValueQuery>; + + #[pallet::storage] + pub type NMap = StorageNMap< + _, + (storage::Key, storage::Key), + u64, + ValueQuery, + >; + + pub mod pallet_prelude { + pub type OriginFor = ::RuntimeOrigin; + } } - impl Config for Runtime { - type RuntimeOrigin = u32; - type BlockNumber = u32; - type PalletInfo = crate::tests::PanicPalletInfo; + type BlockNumber = u32; + type AccountId = u32; + type Header = generic::Header; + type UncheckedExtrinsic = generic::UncheckedExtrinsic; + type Block = generic::Block; + + crate::construct_runtime!( + pub enum Runtime + where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: self::frame_system, + } + ); + + impl self::frame_system::Config for Runtime { + type BlockNumber = BlockNumber; + type AccountId = AccountId; + type BaseCallFilter = crate::traits::Everything; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type PalletInfo = PalletInfo; type DbWeight = (); } - decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self {} + pub fn key_before_prefix(mut prefix: Vec) -> Vec { + let last = prefix.iter_mut().last().unwrap(); + assert_ne!(*last, 0, "mock function not implemented for this prefix"); + *last -= 1; + prefix } - crate::decl_storage! { - trait Store for Module as Runtime { - Value get(fn value) config(): (u64, u64); - NumberMap: map hasher(identity) u32 => u64; - DoubleMap: double_map hasher(identity) u32, hasher(identity) u32 => u64; - } + pub fn key_after_prefix(mut prefix: Vec) -> Vec { + let last = prefix.iter_mut().last().unwrap(); + assert_ne!(*last, 255, "mock function not implemented for this prefix"); + *last += 1; + prefix } #[test] fn value_translate_works() { let t = GenesisConfig::default().build_storage().unwrap(); TestExternalities::new(t).execute_with(|| { + type Value = self::frame_system::Value; + // put the old value `1111u32` in the storage. let key = Value::storage_value_final_key(); unhashed::put_raw(&key, &1111u32.encode()); @@ -96,7 +173,9 @@ mod tests { fn map_translate_works() { let t = GenesisConfig::default().build_storage().unwrap(); TestExternalities::new(t).execute_with(|| { - // start with a map of u32 -> u32. + type NumberMap = self::frame_system::NumberMap; + + // start with a map of u32 -> u64. for i in 0u32..100u32 { unhashed::put(&NumberMap::hashed_key_for(&i), &(i as u64)); } @@ -125,6 +204,10 @@ mod tests { fn try_mutate_works() { let t = GenesisConfig::default().build_storage().unwrap(); TestExternalities::new(t).execute_with(|| { + type Value = self::frame_system::Value; + type NumberMap = self::frame_system::NumberMap; + type DoubleMap = self::frame_system::DoubleMap; + assert_eq!(Value::get(), (0, 0)); assert_eq!(NumberMap::get(0), 0); assert_eq!(DoubleMap::get(0, 0), 0); diff --git a/frame/support/src/storage/generator/nmap.rs b/frame/support/src/storage/generator/nmap.rs index 79f3d72044e28..aa1ab1c839613 100755 --- a/frame/support/src/storage/generator/nmap.rs +++ b/frame/support/src/storage/generator/nmap.rs @@ -455,48 +455,19 @@ impl> mod test_iterators { use crate::{ hash::StorageHasher, - storage::{generator::StorageNMap, unhashed, IterableStorageNMap}, + storage::{ + generator::{tests::*, StorageNMap}, + unhashed, + }, }; - use codec::{Decode, Encode}; - - pub trait Config: 'static { - type RuntimeOrigin; - type BlockNumber; - type PalletInfo: crate::traits::PalletInfo; - type DbWeight: crate::traits::Get; - } - - crate::decl_module! { - pub struct Module for enum Call where origin: T::RuntimeOrigin, system=self {} - } - - #[derive(PartialEq, Eq, Clone, Encode, Decode)] - struct NoDef(u32); - - crate::decl_storage! { - trait Store for Module as Test { - NMap: nmap hasher(blake2_128_concat) u16, hasher(twox_64_concat) u32 => u64; - } - } - - fn key_before_prefix(mut prefix: Vec) -> Vec { - let last = prefix.iter_mut().last().unwrap(); - assert!(*last != 0, "mock function not implemented for this prefix"); - *last -= 1; - prefix - } - - fn key_after_prefix(mut prefix: Vec) -> Vec { - let last = prefix.iter_mut().last().unwrap(); - assert!(*last != 255, "mock function not implemented for this prefix"); - *last += 1; - prefix - } + use codec::Encode; #[test] fn n_map_iter_from() { sp_io::TestExternalities::default().execute_with(|| { use crate::{hash::Identity, storage::Key as NMapKey}; + + type MyModule = self::frame_system::Pallet; #[crate::storage_alias] type MyNMap = StorageNMap< MyModule, @@ -538,22 +509,19 @@ mod test_iterators { #[test] fn n_map_double_map_identical_key() { sp_io::TestExternalities::default().execute_with(|| { + use crate::hash::{Blake2_128Concat, Twox64Concat}; + + type System = self::frame_system::Pallet; + type NMap = self::frame_system::NMap; + NMap::insert((1, 2), 50); let key_hash = NMap::hashed_key_for((1, 2)); { #[crate::storage_alias] - type NMap = StorageDoubleMap< - Test, - crate::Blake2_128Concat, - u16, - crate::Twox64Concat, - u32, - u64, - >; - - let value = NMap::get(1, 2).unwrap(); - assert_eq!(value, 50); + type NMap = StorageDoubleMap; + + assert_eq!(NMap::get(1, 2), Some(50)); assert_eq!(NMap::hashed_key_for(1, 2), key_hash); } }); @@ -562,6 +530,8 @@ mod test_iterators { #[test] fn n_map_reversible_reversible_iteration() { sp_io::TestExternalities::default().execute_with(|| { + type NMap = self::frame_system::NMap; + // All map iterator let prefix = NMap::prefix_hash(); From bab23996844c5887b29e5efb3026a428943a15d4 Mon Sep 17 00:00:00 2001 From: koushiro Date: Mon, 3 Oct 2022 16:14:14 +0800 Subject: [PATCH 02/13] Remove useless type alias --- frame/support/src/storage/generator/double_map.rs | 1 - frame/support/src/storage/generator/map.rs | 1 - frame/support/src/storage/generator/nmap.rs | 2 -- 3 files changed, 4 deletions(-) diff --git a/frame/support/src/storage/generator/double_map.rs b/frame/support/src/storage/generator/double_map.rs index db45228c0df3f..0ff8380e206a3 100644 --- a/frame/support/src/storage/generator/double_map.rs +++ b/frame/support/src/storage/generator/double_map.rs @@ -518,7 +518,6 @@ mod test_iterators { fn double_map_iter_from() { sp_io::TestExternalities::default().execute_with(|| { use crate::hash::Identity; - type MyModule = self::frame_system::Pallet; #[crate::storage_alias] type MyDoubleMap = StorageDoubleMap; diff --git a/frame/support/src/storage/generator/map.rs b/frame/support/src/storage/generator/map.rs index ea225cb91cc9d..43e26a1502627 100644 --- a/frame/support/src/storage/generator/map.rs +++ b/frame/support/src/storage/generator/map.rs @@ -360,7 +360,6 @@ mod test_iterators { fn map_iter_from() { sp_io::TestExternalities::default().execute_with(|| { use crate::hash::Identity; - type MyModule = self::frame_system::Pallet; #[crate::storage_alias] type MyMap = StorageMap; diff --git a/frame/support/src/storage/generator/nmap.rs b/frame/support/src/storage/generator/nmap.rs index aa1ab1c839613..1b195f5c248e9 100755 --- a/frame/support/src/storage/generator/nmap.rs +++ b/frame/support/src/storage/generator/nmap.rs @@ -466,8 +466,6 @@ mod test_iterators { fn n_map_iter_from() { sp_io::TestExternalities::default().execute_with(|| { use crate::{hash::Identity, storage::Key as NMapKey}; - - type MyModule = self::frame_system::Pallet; #[crate::storage_alias] type MyNMap = StorageNMap< MyModule, From debc95110929cabe32a61dc9e6714a8482b019df Mon Sep 17 00:00:00 2001 From: koushiro Date: Mon, 3 Oct 2022 16:20:22 +0800 Subject: [PATCH 03/13] Remove useless type alias --- frame/support/src/storage/generator/nmap.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/frame/support/src/storage/generator/nmap.rs b/frame/support/src/storage/generator/nmap.rs index 1b195f5c248e9..228d8487c6c3b 100755 --- a/frame/support/src/storage/generator/nmap.rs +++ b/frame/support/src/storage/generator/nmap.rs @@ -509,7 +509,6 @@ mod test_iterators { sp_io::TestExternalities::default().execute_with(|| { use crate::hash::{Blake2_128Concat, Twox64Concat}; - type System = self::frame_system::Pallet; type NMap = self::frame_system::NMap; NMap::insert((1, 2), 50); From 52ceba9a22b0d9ae26dfc3446e2a127ad1c0061c Mon Sep 17 00:00:00 2001 From: koushiro Date: Fri, 7 Oct 2022 21:45:07 +0800 Subject: [PATCH 04/13] frame-support-test: migrate old decl_macros to new pallet attribute macros --- frame/support/test/Cargo.toml | 2 +- frame/support/test/pallet/src/lib.rs | 7 +- frame/support/test/src/lib.rs | 117 ++- frame/support/test/src/pallet_version.rs | 29 - frame/support/test/tests/construct_runtime.rs | 446 +++++---- .../test/tests/construct_runtime_ui.rs | 6 +- .../old_unsupported_pallet_decl.rs | 26 - .../old_unsupported_pallet_decl.stderr | 31 - frame/support/test/tests/decl_module_ui.rs | 32 - ...served_keyword_two_times_integrity_test.rs | 7 - ...ed_keyword_two_times_integrity_test.stderr | 19 - ...eserved_keyword_two_times_on_initialize.rs | 13 - ...ved_keyword_two_times_on_initialize.stderr | 13 - frame/support/test/tests/decl_storage.rs | 878 ------------------ frame/support/test/tests/decl_storage_ui.rs | 32 - .../tests/decl_storage_ui/config_duplicate.rs | 31 - .../decl_storage_ui/config_duplicate.stderr | 5 - .../decl_storage_ui/config_get_duplicate.rs | 31 - .../config_get_duplicate.stderr | 5 - .../tests/decl_storage_ui/get_duplicate.rs | 31 - .../decl_storage_ui/get_duplicate.stderr | 5 - frame/support/test/tests/final_keys.rs | 278 ++++-- frame/support/test/tests/genesisconfig.rs | 83 +- frame/support/test/tests/instance.rs | 357 +++---- frame/support/test/tests/issue2219.rs | 170 ++-- frame/support/test/tests/origin.rs | 218 +++-- .../test/tests/pallet_compatibility.rs | 370 -------- .../tests/pallet_compatibility_instance.rs | 370 -------- frame/support/test/tests/pallet_instance.rs | 10 +- .../tests/pallet_with_name_trait_is_valid.rs | 158 ---- frame/support/test/tests/storage_layers.rs | 69 +- .../support/test/tests/storage_transaction.rs | 115 ++- frame/support/test/tests/system.rs | 81 -- 33 files changed, 1123 insertions(+), 2922 deletions(-) delete mode 100644 frame/support/test/src/pallet_version.rs delete mode 100644 frame/support/test/tests/construct_runtime_ui/old_unsupported_pallet_decl.rs delete mode 100644 frame/support/test/tests/construct_runtime_ui/old_unsupported_pallet_decl.stderr delete mode 100644 frame/support/test/tests/decl_module_ui.rs delete mode 100644 frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_integrity_test.rs delete mode 100644 frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_integrity_test.stderr delete mode 100644 frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_on_initialize.rs delete mode 100644 frame/support/test/tests/decl_module_ui/reserved_keyword_two_times_on_initialize.stderr delete mode 100644 frame/support/test/tests/decl_storage.rs delete mode 100644 frame/support/test/tests/decl_storage_ui.rs delete mode 100644 frame/support/test/tests/decl_storage_ui/config_duplicate.rs delete mode 100644 frame/support/test/tests/decl_storage_ui/config_duplicate.stderr delete mode 100644 frame/support/test/tests/decl_storage_ui/config_get_duplicate.rs delete mode 100644 frame/support/test/tests/decl_storage_ui/config_get_duplicate.stderr delete mode 100644 frame/support/test/tests/decl_storage_ui/get_duplicate.rs delete mode 100644 frame/support/test/tests/decl_storage_ui/get_duplicate.stderr delete mode 100644 frame/support/test/tests/pallet_compatibility.rs delete mode 100644 frame/support/test/tests/pallet_compatibility_instance.rs delete mode 100644 frame/support/test/tests/pallet_with_name_trait_is_valid.rs delete mode 100644 frame/support/test/tests/system.rs diff --git a/frame/support/test/Cargo.toml b/frame/support/test/Cargo.toml index d7d3bfc98f3d7..349e4945baf48 100644 --- a/frame/support/test/Cargo.toml +++ b/frame/support/test/Cargo.toml @@ -18,7 +18,7 @@ scale-info = { version = "2.1.1", default-features = false, features = ["derive" sp-arithmetic = { version = "5.0.0", default-features = false, path = "../../../primitives/arithmetic" } sp-io = { version = "6.0.0", path = "../../../primitives/io", default-features = false } sp-state-machine = { version = "0.12.0", optional = true, path = "../../../primitives/state-machine" } -frame-support = { version = "4.0.0-dev", default-features = false, path = "../" } +frame-support = { version = "4.0.0-dev", default-features = false, path = ".." } sp-runtime = { version = "6.0.0", default-features = false, path = "../../../primitives/runtime" } sp-core = { version = "6.0.0", default-features = false, path = "../../../primitives/core" } sp-std = { version = "4.0.0", default-features = false, path = "../../../primitives/std" } diff --git a/frame/support/test/pallet/src/lib.rs b/frame/support/test/pallet/src/lib.rs index 37678e056f3e1..996856c8e6761 100644 --- a/frame/support/test/pallet/src/lib.rs +++ b/frame/support/test/pallet/src/lib.rs @@ -24,20 +24,17 @@ 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(_); + pub struct Pallet(PhantomData); #[pallet::config] pub trait Config: frame_system::Config {} /// 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 0ceeed42ff982..c15a9ac3605f3 100644 --- a/frame/support/test/src/lib.rs +++ b/frame/support/test/src/lib.rs @@ -22,41 +22,106 @@ #![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] +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(PhantomData); -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. + #[pallet::weight(0)] + 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") +} + +/// Prelude to be used alongside pallet macro, for ease of use. +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 096289116c419..0000000000000 --- a/frame/support/test/src/pallet_version.rs +++ /dev/null @@ -1,29 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2020-2022 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -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/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index b1ace12936241..e92dfe4dda752 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -21,240 +21,247 @@ #![recursion_limit = "128"] -use codec::MaxEncodedLen; use frame_support::{ parameter_types, traits::{CrateVersion, 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] mod module1 { - use super::*; - - pub trait Config: system::Config {} - - 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()) - } - } + use self::frame_system::pallet_prelude::*; + use frame_support::pallet_prelude::*; + use frame_support_test as frame_system; + + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(PhantomData<(T, I)>); + + #[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 { + #[pallet::weight(0)] + 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] 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] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(PhantomData); - 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 { + #[pallet::weight(0)] + 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] 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] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(PhantomData); - 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 { + #[pallet::weight(0)] + 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] 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] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(PhantomData); - 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 { + #[pallet::weight(0)] + pub fn fail(_origin: OriginFor) -> DispatchResult { + Err(Error::::Something.into()) + } + #[pallet::weight(0)] + pub fn aux_1(_origin: OriginFor, #[pallet::compact] _data: u32) -> DispatchResult { + unreachable!() + } + #[pallet::weight(0)] + 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 enum Runtime where @@ -264,12 +271,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}, @@ -278,9 +285,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() { @@ -474,12 +529,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); @@ -494,7 +549,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(); @@ -597,70 +652,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 { @@ -669,45 +724,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, }, ]; @@ -725,6 +778,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.rs b/frame/support/test/tests/construct_runtime_ui.rs index 38aa780766835..42fd87ca95c0e 100644 --- a/frame/support/test/tests/construct_runtime_ui.rs +++ b/frame/support/test/tests/construct_runtime_ui.rs @@ -15,19 +15,17 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::env; - #[rustversion::attr(not(stable), ignore)] #[cfg(not(feature = "disable-ui-tests"))] #[test] fn ui() { // Only run the ui tests when `RUN_UI_TESTS` is set. - if env::var("RUN_UI_TESTS").is_err() { + if std::env::var("RUN_UI_TESTS").is_err() { return } // As trybuild is using `cargo check`, we don't need the real WASM binaries. - env::set_var("SKIP_WASM_BUILD", "1"); + std::env::set_var("SKIP_WASM_BUILD", "1"); let t = trybuild::TestCases::new(); t.compile_fail("tests/construct_runtime_ui/*.rs"); 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 5691549c20f34..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 enum 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 f8ec07e00106f..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` - --> $DIR/old_unsupported_pallet_decl.rs:15:1 - | -15 | / construct_runtime! { -16 | | pub enum 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 - --> $DIR/old_unsupported_pallet_decl.rs:6:2 - | -6 | decl_storage! { - | ^^^^^^^^^^^^ - | - = note: consider importing this macro: - frame_support::decl_storage - -error: cannot find macro `decl_module` in this scope - --> $DIR/old_unsupported_pallet_decl.rs:10:2 - | -10 | decl_module! { - | ^^^^^^^^^^^ - | - = note: consider importing this macro: - frame_support::decl_module 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 292451335e7ea..0000000000000 --- a/frame/support/test/tests/decl_module_ui.rs +++ /dev/null @@ -1,32 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2020-2022 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#[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 47ff1c8af8cd2..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` (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 bfefadee99403..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. - --> $DIR/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` (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 a4e420eb454b6..0000000000000 --- a/frame/support/test/tests/decl_storage.rs +++ /dev/null @@ -1,878 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2019-2022 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#[cfg(test)] -// Do not complain about unused `dispatch` and `dispatch_aux`. -#[allow(dead_code)] -mod tests { - use frame_support::metadata::*; - 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() -> PalletStorageMetadata { - PalletStorageMetadata { - prefix: "TestStorage", - entries: vec![ - StorageEntryMetadata { - name: "U32", - modifier: StorageEntryModifier::Optional, - ty: StorageEntryType::Plain(scale_info::meta_type::()), - default: vec![0], - docs: vec![" Hello, this is doc!"], - }, - StorageEntryMetadata { - name: "PUBU32", - modifier: StorageEntryModifier::Optional, - ty: StorageEntryType::Plain(scale_info::meta_type::()), - default: vec![0], - docs: vec![], - }, - StorageEntryMetadata { - name: "U32MYDEF", - modifier: StorageEntryModifier::Optional, - ty: StorageEntryType::Plain(scale_info::meta_type::()), - default: vec![0], - docs: vec![], - }, - StorageEntryMetadata { - name: "PUBU32MYDEF", - modifier: StorageEntryModifier::Optional, - ty: StorageEntryType::Plain(scale_info::meta_type::()), - default: vec![0], - docs: vec![], - }, - StorageEntryMetadata { - name: "GETU32", - modifier: StorageEntryModifier::Default, - ty: StorageEntryType::Plain(scale_info::meta_type::()), - default: vec![0, 0, 0, 0], - docs: vec![], - }, - StorageEntryMetadata { - name: "PUBGETU32", - modifier: StorageEntryModifier::Default, - ty: StorageEntryType::Plain(scale_info::meta_type::()), - default: vec![0, 0, 0, 0], - docs: vec![], - }, - StorageEntryMetadata { - name: "GETU32WITHCONFIG", - modifier: StorageEntryModifier::Default, - ty: StorageEntryType::Plain(scale_info::meta_type::()), - default: vec![0, 0, 0, 0], - docs: vec![], - }, - StorageEntryMetadata { - name: "PUBGETU32WITHCONFIG", - modifier: StorageEntryModifier::Default, - ty: StorageEntryType::Plain(scale_info::meta_type::()), - default: vec![0, 0, 0, 0], - docs: vec![], - }, - StorageEntryMetadata { - name: "GETU32MYDEF", - modifier: StorageEntryModifier::Optional, - ty: StorageEntryType::Plain(scale_info::meta_type::()), - default: vec![0], - docs: vec![], - }, - StorageEntryMetadata { - name: "PUBGETU32MYDEF", - modifier: StorageEntryModifier::Default, - ty: StorageEntryType::Plain(scale_info::meta_type::()), - default: vec![3, 0, 0, 0], - docs: vec![], - }, - StorageEntryMetadata { - name: "GETU32WITHCONFIGMYDEF", - modifier: StorageEntryModifier::Default, - ty: StorageEntryType::Plain(scale_info::meta_type::()), - default: vec![2, 0, 0, 0], - docs: vec![], - }, - StorageEntryMetadata { - name: "PUBGETU32WITHCONFIGMYDEF", - modifier: StorageEntryModifier::Default, - ty: StorageEntryType::Plain(scale_info::meta_type::()), - default: vec![1, 0, 0, 0], - docs: vec![], - }, - StorageEntryMetadata { - name: "PUBGETU32WITHCONFIGMYDEFOPT", - modifier: StorageEntryModifier::Optional, - ty: StorageEntryType::Plain(scale_info::meta_type::()), - default: vec![0], - docs: vec![], - }, - StorageEntryMetadata { - name: "GetU32WithBuilder", - modifier: StorageEntryModifier::Default, - ty: StorageEntryType::Plain(scale_info::meta_type::()), - default: vec![0, 0, 0, 0], - docs: vec![], - }, - StorageEntryMetadata { - name: "GetOptU32WithBuilderSome", - modifier: StorageEntryModifier::Optional, - ty: StorageEntryType::Plain(scale_info::meta_type::()), - default: vec![0], - docs: vec![], - }, - StorageEntryMetadata { - name: "GetOptU32WithBuilderNone", - modifier: StorageEntryModifier::Optional, - ty: StorageEntryType::Plain(scale_info::meta_type::()), - default: vec![0], - docs: vec![], - }, - StorageEntryMetadata { - name: "MAPU32", - modifier: StorageEntryModifier::Optional, - ty: StorageEntryType::Map { - hashers: vec![StorageHasher::Blake2_128Concat], - key: scale_info::meta_type::(), - value: scale_info::meta_type::<[u8; 4]>(), - }, - default: vec![0], - docs: vec![], - }, - StorageEntryMetadata { - name: "PUBMAPU32", - modifier: StorageEntryModifier::Optional, - ty: StorageEntryType::Map { - hashers: vec![StorageHasher::Blake2_128Concat], - key: scale_info::meta_type::(), - value: scale_info::meta_type::<[u8; 4]>(), - }, - default: vec![0], - docs: vec![], - }, - StorageEntryMetadata { - name: "GETMAPU32", - modifier: StorageEntryModifier::Default, - ty: StorageEntryType::Map { - hashers: vec![StorageHasher::Blake2_128Concat], - key: scale_info::meta_type::(), - value: scale_info::meta_type::<[u8; 4]>(), - }, - default: vec![0, 0, 0, 0], - docs: vec![], - }, - StorageEntryMetadata { - name: "PUBGETMAPU32", - modifier: StorageEntryModifier::Default, - ty: StorageEntryType::Map { - hashers: vec![StorageHasher::Blake2_128Concat], - key: scale_info::meta_type::(), - value: scale_info::meta_type::<[u8; 4]>(), - }, - default: vec![0, 0, 0, 0], - docs: vec![], - }, - StorageEntryMetadata { - name: "GETMAPU32MYDEF", - modifier: StorageEntryModifier::Default, - ty: StorageEntryType::Map { - hashers: vec![StorageHasher::Blake2_128Concat], - key: scale_info::meta_type::(), - value: scale_info::meta_type::<[u8; 4]>(), - }, - default: vec![109, 97, 112, 100], // "map" - docs: vec![], - }, - StorageEntryMetadata { - name: "PUBGETMAPU32MYDEF", - modifier: StorageEntryModifier::Default, - ty: StorageEntryType::Map { - hashers: vec![StorageHasher::Blake2_128Concat], - key: scale_info::meta_type::(), - value: scale_info::meta_type::<[u8; 4]>(), - }, - default: vec![112, 117, 98, 109], // "pubmap" - docs: vec![], - }, - StorageEntryMetadata { - name: "DOUBLEMAP", - modifier: StorageEntryModifier::Optional, - ty: StorageEntryType::Map { - hashers: vec![ - StorageHasher::Blake2_128Concat, - StorageHasher::Blake2_128Concat, - ], - key: scale_info::meta_type::<(u32, u32)>(), - value: scale_info::meta_type::<[u8; 4]>(), - }, - default: vec![0], - docs: vec![], - }, - StorageEntryMetadata { - name: "DOUBLEMAP2", - modifier: StorageEntryModifier::Optional, - ty: StorageEntryType::Map { - hashers: vec![ - StorageHasher::Blake2_128Concat, - StorageHasher::Blake2_128Concat, - ], - key: scale_info::meta_type::<(u32, u32)>(), - value: scale_info::meta_type::<[u8; 4]>(), - }, - default: vec![0], - docs: vec![], - }, - StorageEntryMetadata { - name: "COMPLEXTYPE1", - modifier: StorageEntryModifier::Default, - ty: StorageEntryType::Plain(scale_info::meta_type::<(Option,)>()), - default: vec![0], - docs: vec![], - }, - StorageEntryMetadata { - name: "COMPLEXTYPE2", - modifier: StorageEntryModifier::Default, - ty: StorageEntryType::Plain(scale_info::meta_type::<( - [[(u16, Option<()>); 32]; 12], - u32, - )>()), - default: [0u8; 1156].to_vec(), - docs: vec![], - }, - StorageEntryMetadata { - name: "COMPLEXTYPE3", - modifier: StorageEntryModifier::Default, - ty: StorageEntryType::Plain(scale_info::meta_type::<[u32; 25]>()), - default: [0u8; 100].to_vec(), - docs: vec![], - }, - StorageEntryMetadata { - name: "NMAP", - modifier: StorageEntryModifier::Default, - ty: StorageEntryType::Map { - key: scale_info::meta_type::<(u32, u16)>(), - hashers: vec![StorageHasher::Blake2_128Concat, StorageHasher::Twox64Concat], - value: scale_info::meta_type::(), - }, - default: vec![0], - docs: vec![], - }, - StorageEntryMetadata { - name: "NMAP2", - modifier: StorageEntryModifier::Default, - ty: StorageEntryType::Map { - key: scale_info::meta_type::(), - hashers: vec![StorageHasher::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 34dfea8601ab9..0000000000000 --- a/frame/support/test/tests/decl_storage_ui.rs +++ /dev/null @@ -1,32 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2019-2022 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#[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 af74823f64ca6..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) 2019-2022 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -pub 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 8805effd9e725..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) 2019-2022 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -pub 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 5e05887110537..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) 2019-2022 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -pub 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 a7ad88c801001..f3fabdce2d8cb 100644 --- a/frame/support/test/tests/final_keys.rs +++ b/frame/support/test/tests/final_keys.rs @@ -16,65 +16,168 @@ // 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] + #[pallet::generate_store(pub(super) trait Store)] + 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] + #[pallet::generate_store(pub(super) trait Store)] + 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 +194,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 f0094b3188ae1..d6f9d4132359d 100644 --- a/frame/support/test/tests/genesisconfig.rs +++ b/frame/support/test/tests/genesisconfig.rs @@ -15,30 +15,87 @@ // 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] + #[pallet::generate_store(pub(super) trait Store)] + 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 043959b67ee6e..7a011c502a54c 100644 --- a/frame/support/test/tests/instance.rs +++ b/frame/support/test/tests/instance.rs @@ -17,111 +17,112 @@ #![recursion_limit = "128"] -use codec::{Codec, Decode, Encode, EncodeLike, MaxEncodedLen}; use frame_support::{ - inherent::{InherentData, InherentIdentifier, MakeFatalError, ProvideInherent}, + inherent::MakeFatalError, metadata::{ PalletStorageMetadata, StorageEntryMetadata, StorageEntryModifier, StorageEntryType, StorageHasher, }, - 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] 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] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(PhantomData<(T, I)>); + + #[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 +134,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 +147,89 @@ mod module1 { // Test for: // * default instance // * use of no_genesis_config_phantom_data +#[frame_support::pallet] mod module2 { use super::*; - - pub trait Config: system::Config { - type Amount: Parameter + Default; - type RuntimeEvent: From> + Into<::RuntimeEvent>; + use frame_support::pallet_prelude::*; + use frame_support_test as frame_system; + + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + 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 +238,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 +250,71 @@ 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] + #[pallet::generate_store(pub(super) trait Store)] + 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 +354,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 enum 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 +387,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 +404,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 +449,7 @@ fn storage_with_instance_basic_operation() { fn expected_metadata() -> PalletStorageMetadata { PalletStorageMetadata { - prefix: "Instance2Module2", + prefix: "Module2_2", entries: vec![ StorageEntryMetadata { name: "Value", diff --git a/frame/support/test/tests/issue2219.rs b/frame/support/test/tests/issue2219.rs index 5d24d54165c1f..f1984bf4b345c 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,89 +79,95 @@ 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] + #[pallet::generate_store(pub(super) trait Store)] + 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 = (); } @@ -177,8 +179,8 @@ frame_support::construct_runtime!( NodeBlock = Block, 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 f794cd8be1ce0..dcd8e6ed5eb16 100644 --- a/frame/support/test/tests/origin.rs +++ b/frame/support/test/tests/origin.rs @@ -19,120 +19,130 @@ #![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] pub mod module { + use self::frame_system::pallet_prelude::*; + use frame_support::pallet_prelude::*; + use frame_support_test as frame_system; + + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(PhantomData); + + #[pallet::config] + pub trait Config: frame_system::Config { + type RuntimeEvent: From> + + IsType<::RuntimeEvent>; + } - use super::*; - - pub trait Config: system::Config {} - - 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 { + #[pallet::weight(0)] + 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] 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] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(PhantomData); - 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 { + #[pallet::weight(0)] + pub fn fail(_origin: OriginFor) -> DispatchResult { + Err(Error::::Something.into()) + } + #[pallet::weight(0)] + pub fn aux_1(_origin: OriginFor, #[pallet::compact] _data: u32) -> DispatchResult { + unreachable!() + } + #[pallet::weight(0)] + 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 +153,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 +165,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 +215,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 398137d644ee4..0000000000000 --- a/frame/support/test/tests/pallet_compatibility.rs +++ /dev/null @@ -1,370 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2020-2022 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// 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_ref_time(10) - } - - 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_ref_time(10) - } - - fn on_finalize(_n: T::BlockNumber) { - >::put(T::Balance::from(11)); - } - } - - #[pallet::call] - impl Pallet { - #[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 enum 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()); - let ty2 = types.resolve(ty_id2).map(|ty| ty.type_def()); - pretty_assertions::assert_eq!(ty1, ty2); - }; - - let get_enum_variants = |ty_id| match types.resolve(ty_id).map(|ty| ty.type_def()) { - 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 e8b5fe9fa33d4..0000000000000 --- a/frame/support/test/tests/pallet_compatibility_instance.rs +++ /dev/null @@ -1,370 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2020-2022 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// 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_ref_time(10) - } - - 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_ref_time(10) - } - - fn on_finalize(_n: T::BlockNumber) { - >::put(T::Balance::from(11)); - } - } - - #[pallet::call] - impl, I: 'static> Pallet { - #[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 enum 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()) { - 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 7e05e2ecf783b..36e21eb94b307 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] 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 0066420566fe8..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) 2017-2022 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -pub 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 enum 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 6fbbb8ac67bd7..c2286cde29eb5 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,11 +24,12 @@ use sp_io::TestExternalities; #[frame_support::pallet] pub mod pallet { - use frame_support::{ensure, pallet_prelude::*}; + use super::*; + use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; #[pallet::pallet] - pub struct Pallet(_); + pub struct Pallet(PhantomData); #[pallet::config] pub trait Config: frame_system::Config {} @@ -55,48 +56,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 = (); @@ -108,9 +90,7 @@ 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 enum Runtime where @@ -120,7 +100,6 @@ frame_support::construct_runtime!( { System: frame_system, MyPallet: pallet, - DeclPallet: decl_pallet::{Call, Storage}, } ); @@ -263,23 +242,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 6fedd75019e37..97e535b12cacd 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(PhantomData); -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 eff41242917a0..0000000000000 --- a/frame/support/test/tests/system.rs +++ /dev/null @@ -1,81 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2019-2022 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -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") -} From 0b9d1aa53917daf7edc57d25de3defc53ff49eb9 Mon Sep 17 00:00:00 2001 From: Oliver Tale-Yazdi Date: Tue, 25 Apr 2023 12:11:51 +0000 Subject: [PATCH 05/13] fmt Signed-off-by: Oliver Tale-Yazdi --- frame/support/test/src/lib.rs | 3 +-- frame/support/test/tests/issue2219.rs | 5 +++-- frame/support/test/tests/storage_layers.rs | 5 +++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/frame/support/test/src/lib.rs b/frame/support/test/src/lib.rs index 37b99c67adaed..5bee6874ea72d 100644 --- a/frame/support/test/src/lib.rs +++ b/frame/support/test/src/lib.rs @@ -26,7 +26,7 @@ pub use frame_support::dispatch::RawOrigin; pub use self::pallet::*; -#[frame_support::pallet] +#[frame_support::pallet(dev_mode)] pub mod pallet { use super::*; use crate::{self as frame_system, pallet_prelude::*}; @@ -64,7 +64,6 @@ pub mod pallet { #[pallet::call] impl Pallet { /// A noop call. - #[pallet::weight(0)] pub fn noop(_origin: OriginFor) -> DispatchResult { Ok(()) } diff --git a/frame/support/test/tests/issue2219.rs b/frame/support/test/tests/issue2219.rs index aa1e34e01110e..a3f6eeda6ace2 100644 --- a/frame/support/test/tests/issue2219.rs +++ b/frame/support/test/tests/issue2219.rs @@ -174,10 +174,11 @@ impl frame_support_test::Config for Runtime { 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: frame_support_test, Module: module, diff --git a/frame/support/test/tests/storage_layers.rs b/frame/support/test/tests/storage_layers.rs index 3b939e50ef3a6..d7b760388efd2 100644 --- a/frame/support/test/tests/storage_layers.rs +++ b/frame/support/test/tests/storage_layers.rs @@ -94,10 +94,11 @@ impl frame_system::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, From f154148f8bc5d6c3c333365f51b614baee8fa439 Mon Sep 17 00:00:00 2001 From: Oliver Tale-Yazdi Date: Tue, 25 Apr 2023 17:35:20 +0200 Subject: [PATCH 06/13] Fix tests Signed-off-by: Oliver Tale-Yazdi --- frame/support/src/dispatch.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index d074756af817a..c75d75b41a292 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -3531,7 +3531,7 @@ mod tests { // Do not complain about unused `dispatch` and `dispatch_aux`. #[allow(dead_code)] mod weight_tests { - use super::*; + use super::{tests::*, *}; use sp_core::parameter_types; use sp_runtime::{generic, traits::BlakeTwo256}; use sp_weights::RuntimeDbWeight; From 430c880f0e2e6117d596a390b8ba35cad10e1670 Mon Sep 17 00:00:00 2001 From: Oliver Tale-Yazdi Date: Tue, 25 Apr 2023 15:15:34 +0000 Subject: [PATCH 07/13] Fix features Signed-off-by: Oliver Tale-Yazdi --- frame/support/Cargo.toml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/frame/support/Cargo.toml b/frame/support/Cargo.toml index fe068d9360d4e..d8b1b9c248720 100644 --- a/frame/support/Cargo.toml +++ b/frame/support/Cargo.toml @@ -70,7 +70,11 @@ std = [ "log/std", "environmental/std", ] -runtime-benchmarks = [] +runtime-benchmarks = [ + "frame-system/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", + "sp-staking/runtime-benchmarks" +] try-runtime = [] # By default some types have documentation, `no-metadata-docs` allows to reduce the documentation # in the metadata. From e5c0c31f8f1c75db7353b5791b1a766f6c1b7ad0 Mon Sep 17 00:00:00 2001 From: Oliver Tale-Yazdi Date: Tue, 25 Apr 2023 17:56:51 +0200 Subject: [PATCH 08/13] Remove deprecated stuff Signed-off-by: Oliver Tale-Yazdi --- frame/support/test/tests/construct_runtime.rs | 14 +++++--------- frame/support/test/tests/final_keys.rs | 2 -- frame/support/test/tests/genesisconfig.rs | 1 - frame/support/test/tests/instance.rs | 7 ++----- frame/support/test/tests/issue2219.rs | 1 - frame/support/test/tests/origin.rs | 6 ++---- 6 files changed, 9 insertions(+), 22 deletions(-) diff --git a/frame/support/test/tests/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index 670c5b0e458f7..74be864b5cbf1 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -24,7 +24,7 @@ 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}, @@ -35,14 +35,13 @@ parameter_types! { pub static IntegrityTestExec: u32 = 0; } -#[frame_support::pallet] +#[frame_support::pallet(dev_mode)] mod module1 { use self::frame_system::pallet_prelude::*; use frame_support::pallet_prelude::*; use frame_support_test as frame_system; #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(PhantomData<(T, I)>); #[pallet::config] @@ -75,7 +74,7 @@ mod module1 { } } -#[frame_support::pallet] +#[frame_support::pallet(dev_mode)] mod module2 { use self::frame_system::pallet_prelude::*; use super::*; @@ -83,7 +82,6 @@ mod module2 { use frame_support_test as frame_system; #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(PhantomData); #[pallet::config] @@ -124,7 +122,7 @@ mod module2 { mod nested { use super::*; - #[frame_support::pallet] + #[frame_support::pallet(dev_mode)] pub mod module3 { use self::frame_system::pallet_prelude::*; use super::*; @@ -132,7 +130,6 @@ mod nested { use frame_support_test as frame_system; #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(PhantomData); #[pallet::config] @@ -181,7 +178,7 @@ mod nested { } } -#[frame_support::pallet] +#[frame_support::pallet(dev_mode)] pub mod module3 { use self::frame_system::pallet_prelude::*; use super::*; @@ -189,7 +186,6 @@ pub mod module3 { use frame_support_test as frame_system; #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(PhantomData); #[pallet::config] diff --git a/frame/support/test/tests/final_keys.rs b/frame/support/test/tests/final_keys.rs index 330c3a0028355..610f6532c52d0 100644 --- a/frame/support/test/tests/final_keys.rs +++ b/frame/support/test/tests/final_keys.rs @@ -34,7 +34,6 @@ mod no_instance { use frame_support_test as frame_system; #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(PhantomData); #[pallet::config] @@ -109,7 +108,6 @@ mod instance { use frame_support_test as frame_system; #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(PhantomData<(T, I)>); #[pallet::config] diff --git a/frame/support/test/tests/genesisconfig.rs b/frame/support/test/tests/genesisconfig.rs index 114d038bf60f4..48904baf1ad62 100644 --- a/frame/support/test/tests/genesisconfig.rs +++ b/frame/support/test/tests/genesisconfig.rs @@ -28,7 +28,6 @@ pub mod pallet { use frame_support_test as frame_system; #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(PhantomData); #[pallet::config] diff --git a/frame/support/test/tests/instance.rs b/frame/support/test/tests/instance.rs index 321d8efbd7bb4..4f7222e6ec921 100644 --- a/frame/support/test/tests/instance.rs +++ b/frame/support/test/tests/instance.rs @@ -37,7 +37,7 @@ pub trait Currency {} // Test for: // * No default instance // * Origin, Inherent, Event -#[frame_support::pallet] +#[frame_support::pallet(dev_mode)] mod module1 { use self::frame_system::pallet_prelude::*; use super::*; @@ -45,7 +45,6 @@ mod module1 { use frame_support_test as frame_system; #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(PhantomData<(T, I)>); #[pallet::config] @@ -154,7 +153,6 @@ mod module2 { use frame_support_test as frame_system; #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(PhantomData<(T, I)>); #[pallet::config] @@ -257,7 +255,6 @@ mod module3 { use frame_support_test as frame_system; #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(PhantomData<(T, I)>); #[pallet::config] @@ -449,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 a3f6eeda6ace2..ff3e0bd951873 100644 --- a/frame/support/test/tests/issue2219.rs +++ b/frame/support/test/tests/issue2219.rs @@ -80,7 +80,6 @@ mod module { } #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(PhantomData); #[pallet::config] diff --git a/frame/support/test/tests/origin.rs b/frame/support/test/tests/origin.rs index 7b351d30eb1dc..65716a5dd7e7e 100644 --- a/frame/support/test/tests/origin.rs +++ b/frame/support/test/tests/origin.rs @@ -23,14 +23,13 @@ use frame_support::traits::{Contains, OriginTrait}; use sp_runtime::{generic, traits::BlakeTwo256}; mod nested { - #[frame_support::pallet] + #[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; #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(PhantomData); #[pallet::config] @@ -72,14 +71,13 @@ mod nested { } } -#[frame_support::pallet] +#[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; #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet(PhantomData); #[pallet::config] From 37f3f05d1d7e6d9327732d81d568bf811e3c12c3 Mon Sep 17 00:00:00 2001 From: Oliver Tale-Yazdi Date: Tue, 25 Apr 2023 17:59:21 +0000 Subject: [PATCH 09/13] Update UI tests Signed-off-by: Oliver Tale-Yazdi --- frame/support/test/tests/benchmark_ui/invalid_origin.stderr | 5 ++++- .../tests/construct_runtime_ui/undefined_event_part.stderr | 4 +++- .../tests/construct_runtime_ui/undefined_origin_part.stderr | 4 +++- frame/support/test/tests/derive_no_bound_ui/eq.stderr | 5 +---- 4 files changed, 11 insertions(+), 7 deletions(-) diff --git a/frame/support/test/tests/benchmark_ui/invalid_origin.stderr b/frame/support/test/tests/benchmark_ui/invalid_origin.stderr index ab8499d995d47..8bc0550ffbd50 100644 --- a/frame/support/test/tests/benchmark_ui/invalid_origin.stderr +++ b/frame/support/test/tests/benchmark_ui/invalid_origin.stderr @@ -2,7 +2,10 @@ error[E0599]: no variant or associated item named `new_call_variant_thing` found --> tests/benchmark_ui/invalid_origin.rs:6:1 | 6 | #[benchmarks] - | ^^^^^^^^^^^^^ variant or associated item not found in `Call` + | ^^^^^^^^^^^^^ + | | + | variant or associated item not found in `Call` + | help: there is an associated function with a similar name: `new_call_variant_noop` | = note: this error originates in the attribute macro `benchmarks` (in Nightly builds, run with -Z macro-backtrace for more info) 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/derive_no_bound_ui/eq.stderr b/frame/support/test/tests/derive_no_bound_ui/eq.stderr index eb3345eede508..5dd96438e06c7 100644 --- a/frame/support/test/tests/derive_no_bound_ui/eq.stderr +++ b/frame/support/test/tests/derive_no_bound_ui/eq.stderr @@ -6,7 +6,4 @@ error[E0277]: can't compare `Foo` with `Foo` | = help: the trait `PartialEq` is not implemented for `Foo` note: required by a bound in `std::cmp::Eq` - --> $RUST/core/src/cmp.rs - | - | pub trait Eq: PartialEq { - | ^^^^^^^^^^^^^^^ required by this bound in `Eq` + --> /rustc/9eb3afe9ebe9c7d2b84b71002d44f4a0edac95e0/library/core/src/cmp.rs:283:1 From 6c095f934d98ca51c9a097d53bee36513c98925a Mon Sep 17 00:00:00 2001 From: Oliver Tale-Yazdi Date: Tue, 25 Apr 2023 19:22:57 +0000 Subject: [PATCH 10/13] Fix UI test Signed-off-by: Oliver Tale-Yazdi --- frame/support/test/tests/derive_no_bound_ui/eq.stderr | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/frame/support/test/tests/derive_no_bound_ui/eq.stderr b/frame/support/test/tests/derive_no_bound_ui/eq.stderr index 5dd96438e06c7..eb3345eede508 100644 --- a/frame/support/test/tests/derive_no_bound_ui/eq.stderr +++ b/frame/support/test/tests/derive_no_bound_ui/eq.stderr @@ -6,4 +6,7 @@ error[E0277]: can't compare `Foo` with `Foo` | = help: the trait `PartialEq` is not implemented for `Foo` note: required by a bound in `std::cmp::Eq` - --> /rustc/9eb3afe9ebe9c7d2b84b71002d44f4a0edac95e0/library/core/src/cmp.rs:283:1 + --> $RUST/core/src/cmp.rs + | + | pub trait Eq: PartialEq { + | ^^^^^^^^^^^^^^^ required by this bound in `Eq` From 5e63c0fc8c6f1d4beb52b234f76c2d6e3ee4cc58 Mon Sep 17 00:00:00 2001 From: Oliver Tale-Yazdi Date: Fri, 28 Apr 2023 14:32:00 +0000 Subject: [PATCH 11/13] Fix test Signed-off-by: Oliver Tale-Yazdi --- frame/benchmarking/src/tests.rs | 7 ------- frame/benchmarking/src/tests_instance.rs | 1 - frame/collective/src/tests.rs | 2 -- frame/executive/src/lib.rs | 12 ------------ frame/support/test/compile_pass/Cargo.toml | 4 ++-- frame/support/test/compile_pass/src/lib.rs | 12 +++++------- frame/support/test/pallet/src/lib.rs | 2 +- frame/support/test/src/lib.rs | 7 ++++--- .../test/tests/benchmark_ui/invalid_origin.rs | 2 +- frame/support/test/tests/construct_runtime.rs | 6 ------ frame/support/test/tests/origin.rs | 4 ---- 11 files changed, 13 insertions(+), 46 deletions(-) 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 4775133ffa2f6..a54c8e15aaead 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 de6aefdeb8398..8cb3aa5b2c7aa 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)] diff --git a/frame/support/test/src/lib.rs b/frame/support/test/src/lib.rs index 5bee6874ea72d..ca418088ab98c 100644 --- a/frame/support/test/src/lib.rs +++ b/frame/support/test/src/lib.rs @@ -15,8 +15,7 @@ // 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 `frame_system::Config`-super trait pallet. // Make sure we fail compilation on warnings #![warn(missing_docs)] @@ -110,7 +109,9 @@ where o.into().map(|_| ()).map_err(|_| "bad origin: expected to be a root origin") } -/// Prelude to be used alongside pallet macro, for ease of use. +/// 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; 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/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index 74be864b5cbf1..c5e1b615035c1 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -52,7 +52,6 @@ mod module1 { #[pallet::call] impl, I: 'static> Pallet { - #[pallet::weight(0)] pub fn fail(_origin: OriginFor) -> DispatchResult { Err(Error::::Something.into()) } @@ -98,7 +97,6 @@ mod module2 { #[pallet::call] impl Pallet { - #[pallet::weight(0)] pub fn fail(_origin: OriginFor) -> DispatchResult { Err(Error::::Something.into()) } @@ -147,7 +145,6 @@ mod nested { #[pallet::call] impl Pallet { - #[pallet::weight(0)] pub fn fail(_origin: OriginFor) -> DispatchResult { Err(Error::::Something.into()) } @@ -195,15 +192,12 @@ pub mod module3 { #[pallet::call] impl Pallet { - #[pallet::weight(0)] pub fn fail(_origin: OriginFor) -> DispatchResult { Err(Error::::Something.into()) } - #[pallet::weight(0)] pub fn aux_1(_origin: OriginFor, #[pallet::compact] _data: u32) -> DispatchResult { unreachable!() } - #[pallet::weight(0)] pub fn aux_2( _origin: OriginFor, _data: i32, diff --git a/frame/support/test/tests/origin.rs b/frame/support/test/tests/origin.rs index 65716a5dd7e7e..7faa9636be523 100644 --- a/frame/support/test/tests/origin.rs +++ b/frame/support/test/tests/origin.rs @@ -40,7 +40,6 @@ mod nested { #[pallet::call] impl Pallet { - #[pallet::weight(0)] pub fn fail(_origin: OriginFor) -> DispatchResult { Err(Error::::Something.into()) } @@ -87,15 +86,12 @@ pub mod module { #[pallet::call] impl Pallet { - #[pallet::weight(0)] pub fn fail(_origin: OriginFor) -> DispatchResult { Err(Error::::Something.into()) } - #[pallet::weight(0)] pub fn aux_1(_origin: OriginFor, #[pallet::compact] _data: u32) -> DispatchResult { unreachable!() } - #[pallet::weight(0)] pub fn aux_2( _origin: OriginFor, _data: i32, From 32d1898f9dd50f3cf761f39e6e75980c165c970c Mon Sep 17 00:00:00 2001 From: Oliver Tale-Yazdi Date: Fri, 28 Apr 2023 15:13:34 +0000 Subject: [PATCH 12/13] Update UI tests Signed-off-by: Oliver Tale-Yazdi --- .../test/tests/benchmark_ui/invalid_origin.stderr | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/frame/support/test/tests/benchmark_ui/invalid_origin.stderr b/frame/support/test/tests/benchmark_ui/invalid_origin.stderr index 8bc0550ffbd50..115a8206f58a3 100644 --- a/frame/support/test/tests/benchmark_ui/invalid_origin.stderr +++ b/frame/support/test/tests/benchmark_ui/invalid_origin.stderr @@ -1,14 +1,3 @@ -error[E0599]: no variant or associated item named `new_call_variant_thing` found for enum `Call` in the current scope - --> tests/benchmark_ui/invalid_origin.rs:6:1 - | -6 | #[benchmarks] - | ^^^^^^^^^^^^^ - | | - | variant or associated item not found in `Call` - | help: there is an associated function with a similar name: `new_call_variant_noop` - | - = 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 | From d15d4fcfd8ebe0d3624bbdf0bffd4e4a633be675 Mon Sep 17 00:00:00 2001 From: Oliver Tale-Yazdi Date: Mon, 8 May 2023 14:25:09 +0200 Subject: [PATCH 13/13] Cleanup Signed-off-by: Oliver Tale-Yazdi --- frame/support/test/pallet/src/lib.rs | 2 +- frame/support/test/src/lib.rs | 4 ++-- frame/support/test/tests/construct_runtime.rs | 8 ++++---- frame/support/test/tests/instance.rs | 2 +- frame/support/test/tests/origin.rs | 4 ++-- frame/support/test/tests/storage_layers.rs | 2 +- frame/support/test/tests/storage_transaction.rs | 2 +- 7 files changed, 12 insertions(+), 12 deletions(-) diff --git a/frame/support/test/pallet/src/lib.rs b/frame/support/test/pallet/src/lib.rs index 8cb3aa5b2c7aa..2dfc94d83187a 100644 --- a/frame/support/test/pallet/src/lib.rs +++ b/frame/support/test/pallet/src/lib.rs @@ -27,7 +27,7 @@ pub mod pallet { use frame_support::pallet_prelude::*; #[pallet::pallet] - pub struct Pallet(PhantomData); + pub struct Pallet(_); #[pallet::config] pub trait Config: frame_system::Config {} diff --git a/frame/support/test/src/lib.rs b/frame/support/test/src/lib.rs index ca418088ab98c..5dccc88471a7b 100644 --- a/frame/support/test/src/lib.rs +++ b/frame/support/test/src/lib.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Minimal `frame_system::Config`-super trait pallet. +//! Minimal pallet without `frame_system::Config`-super trait. // Make sure we fail compilation on warnings #![warn(missing_docs)] @@ -32,7 +32,7 @@ pub mod pallet { use frame_support::pallet_prelude::*; #[pallet::pallet] - pub struct Pallet(PhantomData); + pub struct Pallet(_); /// The configuration trait #[pallet::config] diff --git a/frame/support/test/tests/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index c5e1b615035c1..85e790095eb31 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -42,7 +42,7 @@ mod module1 { use frame_support_test as frame_system; #[pallet::pallet] - pub struct Pallet(PhantomData<(T, I)>); + pub struct Pallet(_); #[pallet::config] pub trait Config: frame_system::Config { @@ -81,7 +81,7 @@ mod module2 { use frame_support_test as frame_system; #[pallet::pallet] - pub struct Pallet(PhantomData); + pub struct Pallet(_); #[pallet::config] pub trait Config: frame_system::Config { @@ -128,7 +128,7 @@ mod nested { use frame_support_test as frame_system; #[pallet::pallet] - pub struct Pallet(PhantomData); + pub struct Pallet(_); #[pallet::config] pub trait Config: frame_system::Config { @@ -183,7 +183,7 @@ pub mod module3 { use frame_support_test as frame_system; #[pallet::pallet] - pub struct Pallet(PhantomData); + pub struct Pallet(_); #[pallet::config] pub trait Config: frame_system::Config { diff --git a/frame/support/test/tests/instance.rs b/frame/support/test/tests/instance.rs index 4f7222e6ec921..5d17a40f8c408 100644 --- a/frame/support/test/tests/instance.rs +++ b/frame/support/test/tests/instance.rs @@ -45,7 +45,7 @@ mod module1 { use frame_support_test as frame_system; #[pallet::pallet] - pub struct Pallet(PhantomData<(T, I)>); + pub struct Pallet(_); #[pallet::config] pub trait Config: frame_system::Config { diff --git a/frame/support/test/tests/origin.rs b/frame/support/test/tests/origin.rs index 7faa9636be523..47451157b352c 100644 --- a/frame/support/test/tests/origin.rs +++ b/frame/support/test/tests/origin.rs @@ -30,7 +30,7 @@ mod nested { use frame_support_test as frame_system; #[pallet::pallet] - pub struct Pallet(PhantomData); + pub struct Pallet(_); #[pallet::config] pub trait Config: frame_system::Config { @@ -77,7 +77,7 @@ pub mod module { use frame_support_test as frame_system; #[pallet::pallet] - pub struct Pallet(PhantomData); + pub struct Pallet(_); #[pallet::config] pub trait Config: frame_system::Config { diff --git a/frame/support/test/tests/storage_layers.rs b/frame/support/test/tests/storage_layers.rs index d7b760388efd2..3e306834869bb 100644 --- a/frame/support/test/tests/storage_layers.rs +++ b/frame/support/test/tests/storage_layers.rs @@ -29,7 +29,7 @@ pub mod pallet { use frame_system::pallet_prelude::*; #[pallet::pallet] - pub struct Pallet(PhantomData); + pub struct Pallet(_); #[pallet::config] pub trait Config: frame_system::Config {} diff --git a/frame/support/test/tests/storage_transaction.rs b/frame/support/test/tests/storage_transaction.rs index 452ee38995ba2..5fc4ba7cca6d9 100644 --- a/frame/support/test/tests/storage_transaction.rs +++ b/frame/support/test/tests/storage_transaction.rs @@ -43,7 +43,7 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub (super) trait Store)] - pub struct Pallet(PhantomData); + pub struct Pallet(_); #[pallet::config] pub trait Config: frame_system::Config {}