// 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::call_index(0)] #[pallet::weight(>::into(new_value.clone()))] pub fn set_dummy( origin: OriginFor, #[pallet::compact] new_value: T::Balance, ) -> DispatchResultWithPostInfo { ensure_root(origin)?; >::put(&new_value); Self::deposit_event(Event::Dummy(new_value)); Ok(().into()) } } #[pallet::error] pub enum Error { /// Some wrong behavior Wrong, } #[pallet::event] #[pallet::generate_deposit(fn deposit_event)] pub enum Event, I: 'static = ()> { /// Dummy event, just here so there's a generic type that's used. Dummy(T::Balance), } #[pallet::storage] /// Some documentation type Dummy, I: 'static = ()> = StorageValue<_, T::Balance, OptionQuery>; #[pallet::storage] type Bar, I: 'static = ()> = StorageMap<_, Blake2_128Concat, T::AccountId, T::Balance, ValueQuery>; #[pallet::storage] type Foo, I: 'static = ()> = StorageValue<_, T::Balance, ValueQuery, OnFooEmpty>; #[pallet::type_value] pub fn OnFooEmpty, I: 'static>() -> T::Balance { 3.into() } #[pallet::storage] type Double = StorageDoubleMap<_, Blake2_128Concat, u32, Twox64Concat, u64, u16, ValueQuery>; #[pallet::genesis_config] pub struct GenesisConfig, I: 'static = ()> { dummy: Option, bar: Vec<(T::AccountId, T::Balance)>, foo: T::Balance, } impl, I: 'static> Default for GenesisConfig { fn default() -> Self { GenesisConfig { dummy: Default::default(), bar: Default::default(), foo: OnFooEmpty::::get(), } } } #[pallet::genesis_build] impl, I: 'static> GenesisBuild for GenesisConfig { fn build(&self) { if let Some(dummy) = self.dummy.as_ref() { >::put(dummy); } for (k, v) in &self.bar { >::insert(k, v); } >::put(&self.foo); } } } impl frame_system::Config for Runtime { type BlockWeights = (); type BlockLength = (); type DbWeight = (); type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type Index = u64; type BlockNumber = u32; type RuntimeCall = RuntimeCall; type Hash = sp_runtime::testing::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup; type Header = Header; type RuntimeEvent = RuntimeEvent; type BlockHashCount = ConstU32<250>; type Version = (); type PalletInfo = PalletInfo; type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); type OnSetCode = (); type MaxConsumers = ConstU32<16>; } impl pallet::Config for Runtime { type RuntimeEvent = RuntimeEvent; type SomeConst = ConstU64<10>; type Balance = u64; } impl pallet::Config for Runtime { type RuntimeEvent = RuntimeEvent; type SomeConst = ConstU64<10>; type Balance = u64; } impl pallet::Config for Runtime { type RuntimeEvent = RuntimeEvent; type SomeConst = ConstU64<10>; type Balance = u64; } impl pallet_old::Config for Runtime { type RuntimeEvent = RuntimeEvent; type SomeConst = ConstU64<10>; type Balance = u64; } impl pallet_old::Config for Runtime { type RuntimeEvent = RuntimeEvent; type SomeConst = ConstU64<10>; type Balance = u64; } impl pallet_old::Config for Runtime { type RuntimeEvent = RuntimeEvent; type SomeConst = ConstU64<10>; type Balance = u64; } pub type Header = sp_runtime::generic::Header; pub type Block = sp_runtime::generic::Block; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; frame_support::construct_runtime!( pub 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 }, ); } }