diff --git a/substrate/bin/node/executor/tests/basic.rs b/substrate/bin/node/executor/tests/basic.rs index 26c04efe4999177cf14ac032cf310bc2a368ebae..f007ba41ccc6185a03e6c49d6c63fd2e4593c249 100644 --- a/substrate/bin/node/executor/tests/basic.rs +++ b/substrate/bin/node/executor/tests/basic.rs @@ -329,7 +329,7 @@ fn full_native_block_import_works() { let events = vec![ EventRecord { phase: Phase::ApplyExtrinsic(0), - event: Event::frame_system(frame_system::RawEvent::ExtrinsicSuccess( + event: Event::frame_system(frame_system::Event::ExtrinsicSuccess( DispatchInfo { weight: timestamp_weight, class: DispatchClass::Mandatory, ..Default::default() } )), topics: vec![], @@ -350,7 +350,7 @@ fn full_native_block_import_works() { }, EventRecord { phase: Phase::ApplyExtrinsic(1), - event: Event::frame_system(frame_system::RawEvent::ExtrinsicSuccess( + event: Event::frame_system(frame_system::Event::ExtrinsicSuccess( DispatchInfo { weight: transfer_weight, ..Default::default() } )), topics: vec![], @@ -381,7 +381,7 @@ fn full_native_block_import_works() { let events = vec![ EventRecord { phase: Phase::ApplyExtrinsic(0), - event: Event::frame_system(frame_system::RawEvent::ExtrinsicSuccess( + event: Event::frame_system(frame_system::Event::ExtrinsicSuccess( DispatchInfo { weight: timestamp_weight, class: DispatchClass::Mandatory, ..Default::default() } )), topics: vec![], @@ -404,7 +404,7 @@ fn full_native_block_import_works() { }, EventRecord { phase: Phase::ApplyExtrinsic(1), - event: Event::frame_system(frame_system::RawEvent::ExtrinsicSuccess( + event: Event::frame_system(frame_system::Event::ExtrinsicSuccess( DispatchInfo { weight: transfer_weight, ..Default::default() } )), topics: vec![], @@ -427,7 +427,7 @@ fn full_native_block_import_works() { }, EventRecord { phase: Phase::ApplyExtrinsic(2), - event: Event::frame_system(frame_system::RawEvent::ExtrinsicSuccess( + event: Event::frame_system(frame_system::Event::ExtrinsicSuccess( DispatchInfo { weight: transfer_weight, ..Default::default() } )), topics: vec![], diff --git a/substrate/bin/node/executor/tests/fees.rs b/substrate/bin/node/executor/tests/fees.rs index ed354d553448acfd98c750543b2c710a833e6943..9d83610b689dec03e6b7b6739db4dca8524bef1a 100644 --- a/substrate/bin/node/executor/tests/fees.rs +++ b/substrate/bin/node/executor/tests/fees.rs @@ -17,7 +17,7 @@ use codec::{Encode, Joiner}; use frame_support::{ - StorageValue, StorageMap, + StorageValue, traits::Currency, weights::{GetDispatchInfo, constants::ExtrinsicBaseWeight, IdentityFee, WeightToFeePolynomial}, }; diff --git a/substrate/bin/node/executor/tests/submit_transaction.rs b/substrate/bin/node/executor/tests/submit_transaction.rs index c628826c62befee766ebb58a620cb2484a00e9ef..ff483d9ecd8cd9740201796a9cb67ae65519eae7 100644 --- a/substrate/bin/node/executor/tests/submit_transaction.rs +++ b/substrate/bin/node/executor/tests/submit_transaction.rs @@ -217,7 +217,6 @@ fn should_submit_signed_twice_from_all_accounts() { #[test] fn submitted_transaction_should_be_valid() { use codec::Encode; - use frame_support::storage::StorageMap; use sp_runtime::transaction_validity::{TransactionSource, TransactionTag}; use sp_runtime::traits::StaticLookup; diff --git a/substrate/frame/balances/src/tests.rs b/substrate/frame/balances/src/tests.rs index 90e8e0d7cbdcf3dc89308714fb185505b6685cb4..7a1b57a7b4db1e8892c30699bf4483367cce4978 100644 --- a/substrate/frame/balances/src/tests.rs +++ b/substrate/frame/balances/src/tests.rs @@ -737,7 +737,7 @@ macro_rules! decl_tests { assert_eq!( events(), [ - Event::system(system::RawEvent::NewAccount(1)), + Event::system(system::Event::NewAccount(1)), Event::balances(RawEvent::Endowed(1, 100)), Event::balances(RawEvent::BalanceSet(1, 100, 0)), ] @@ -749,7 +749,7 @@ macro_rules! decl_tests { events(), [ Event::balances(RawEvent::DustLost(1, 99)), - Event::system(system::RawEvent::KilledAccount(1)) + Event::system(system::Event::KilledAccount(1)) ] ); }); @@ -766,7 +766,7 @@ macro_rules! decl_tests { assert_eq!( events(), [ - Event::system(system::RawEvent::NewAccount(1)), + Event::system(system::Event::NewAccount(1)), Event::balances(RawEvent::Endowed(1, 100)), Event::balances(RawEvent::BalanceSet(1, 100, 0)), ] @@ -777,7 +777,7 @@ macro_rules! decl_tests { assert_eq!( events(), [ - Event::system(system::RawEvent::KilledAccount(1)) + Event::system(system::Event::KilledAccount(1)) ] ); }); diff --git a/substrate/frame/balances/src/tests_local.rs b/substrate/frame/balances/src/tests_local.rs index 2cbf46709275a066e1fe9dcc7fc2c90c69c3ed42..762ebe871b3e8294009b73c9b9c9fe1a51e5af64 100644 --- a/substrate/frame/balances/src/tests_local.rs +++ b/substrate/frame/balances/src/tests_local.rs @@ -170,7 +170,7 @@ fn emit_events_with_no_existential_deposit_suicide_with_dust() { assert_eq!( events(), [ - Event::system(system::RawEvent::NewAccount(1)), + Event::system(system::Event::NewAccount(1)), Event::balances(RawEvent::Endowed(1, 100)), Event::balances(RawEvent::BalanceSet(1, 100, 0)), ] @@ -187,7 +187,7 @@ fn emit_events_with_no_existential_deposit_suicide_with_dust() { events(), [ Event::balances(RawEvent::DustLost(1, 1)), - Event::system(system::RawEvent::KilledAccount(1)) + Event::system(system::Event::KilledAccount(1)) ] ); }); diff --git a/substrate/frame/contracts/src/tests.rs b/substrate/frame/contracts/src/tests.rs index 965cb7e49a0a4bd7201f02a5fe7813a355de02bc..96bcf99bf8e81e4bafecf5aaf622b07f887b8b82 100644 --- a/substrate/frame/contracts/src/tests.rs +++ b/substrate/frame/contracts/src/tests.rs @@ -475,7 +475,7 @@ fn instantiate_and_call_and_deposit_event() { pretty_assertions::assert_eq!(System::events(), vec![ EventRecord { phase: Phase::Initialization, - event: MetaEvent::system(frame_system::RawEvent::NewAccount(ALICE.clone())), + event: MetaEvent::system(frame_system::Event::NewAccount(ALICE.clone())), topics: vec![], }, EventRecord { @@ -492,7 +492,7 @@ fn instantiate_and_call_and_deposit_event() { }, EventRecord { phase: Phase::Initialization, - event: MetaEvent::system(frame_system::RawEvent::NewAccount(addr.clone())), + event: MetaEvent::system(frame_system::Event::NewAccount(addr.clone())), topics: vec![], }, EventRecord { @@ -653,7 +653,7 @@ fn test_set_rent_code_and_hash() { assert_eq!(System::events(), vec![ EventRecord { phase: Phase::Initialization, - event: MetaEvent::system(frame_system::RawEvent::NewAccount(ALICE)), + event: MetaEvent::system(frame_system::Event::NewAccount(ALICE)), topics: vec![], }, EventRecord { @@ -1235,7 +1235,7 @@ fn restoration(test_different_storage: bool, test_restore_to_with_dirty_storage: assert_eq!(System::events(), vec![ EventRecord { phase: Phase::Initialization, - event: MetaEvent::system(frame_system::RawEvent::NewAccount(ALICE)), + event: MetaEvent::system(frame_system::Event::NewAccount(ALICE)), topics: vec![], }, EventRecord { @@ -1390,7 +1390,7 @@ fn restoration(test_different_storage: bool, test_restore_to_with_dirty_storage: }, EventRecord { phase: Phase::Initialization, - event: MetaEvent::system(frame_system::RawEvent::NewAccount(CHARLIE)), + event: MetaEvent::system(frame_system::Event::NewAccount(CHARLIE)), topics: vec![], }, EventRecord { @@ -1400,7 +1400,7 @@ fn restoration(test_different_storage: bool, test_restore_to_with_dirty_storage: }, EventRecord { phase: Phase::Initialization, - event: MetaEvent::system(frame_system::RawEvent::NewAccount(addr_django.clone())), + event: MetaEvent::system(frame_system::Event::NewAccount(addr_django.clone())), topics: vec![], }, EventRecord { @@ -1440,7 +1440,7 @@ fn restoration(test_different_storage: bool, test_restore_to_with_dirty_storage: assert_eq!(System::events(), vec![ EventRecord { phase: Phase::Initialization, - event: MetaEvent::system(system::RawEvent::KilledAccount(addr_django.clone())), + event: MetaEvent::system(system::Event::KilledAccount(addr_django.clone())), topics: vec![], }, EventRecord { diff --git a/substrate/frame/executive/src/lib.rs b/substrate/frame/executive/src/lib.rs index 05b4b0f982a0b05bd5b5f1fea31651b8f915717d..df1ae17df613fa4cbfa5516d265e376dd3e74290 100644 --- a/substrate/frame/executive/src/lib.rs +++ b/substrate/frame/executive/src/lib.rs @@ -117,7 +117,7 @@ use sp_std::{prelude::*, marker::PhantomData}; use frame_support::{ - StorageValue, StorageMap, weights::{GetDispatchInfo, DispatchInfo, DispatchClass}, + weights::{GetDispatchInfo, DispatchInfo, DispatchClass}, traits::{OnInitialize, OnFinalize, OnRuntimeUpgrade, OffchainWorker}, dispatch::PostDispatchInfo, }; @@ -261,11 +261,11 @@ where /// Returns if the runtime was upgraded since the last time this function was called. fn runtime_upgraded() -> bool { - let last = frame_system::LastRuntimeUpgrade::get(); + let last = frame_system::LastRuntimeUpgrade::<System>::get(); let current = <System::Version as frame_support::traits::Get<_>>::get(); if last.map(|v| v.was_upgraded(¤t)).unwrap_or(true) { - frame_system::LastRuntimeUpgrade::put( + frame_system::LastRuntimeUpgrade::<System>::put( frame_system::LastRuntimeUpgradeInfo::from(current), ); true @@ -998,7 +998,7 @@ mod tests { new_test_ext(1).execute_with(|| { RUNTIME_VERSION.with(|v| *v.borrow_mut() = Default::default()); // It should be added at genesis - assert!(frame_system::LastRuntimeUpgrade::exists()); + assert!(frame_system::LastRuntimeUpgrade::<Runtime>::exists()); assert!(!Executive::runtime_upgraded()); RUNTIME_VERSION.with(|v| *v.borrow_mut() = sp_version::RuntimeVersion { @@ -1008,7 +1008,7 @@ mod tests { assert!(Executive::runtime_upgraded()); assert_eq!( Some(LastRuntimeUpgradeInfo { spec_version: 1.into(), spec_name: "".into() }), - frame_system::LastRuntimeUpgrade::get(), + frame_system::LastRuntimeUpgrade::<Runtime>::get(), ); RUNTIME_VERSION.with(|v| *v.borrow_mut() = sp_version::RuntimeVersion { @@ -1019,7 +1019,7 @@ mod tests { assert!(Executive::runtime_upgraded()); assert_eq!( Some(LastRuntimeUpgradeInfo { spec_version: 1.into(), spec_name: "test".into() }), - frame_system::LastRuntimeUpgrade::get(), + frame_system::LastRuntimeUpgrade::<Runtime>::get(), ); RUNTIME_VERSION.with(|v| *v.borrow_mut() = sp_version::RuntimeVersion { @@ -1030,11 +1030,11 @@ mod tests { }); assert!(!Executive::runtime_upgraded()); - frame_system::LastRuntimeUpgrade::take(); + frame_system::LastRuntimeUpgrade::<Runtime>::take(); assert!(Executive::runtime_upgraded()); assert_eq!( Some(LastRuntimeUpgradeInfo { spec_version: 1.into(), spec_name: "test".into() }), - frame_system::LastRuntimeUpgrade::get(), + frame_system::LastRuntimeUpgrade::<Runtime>::get(), ); }) } diff --git a/substrate/frame/session/benchmarking/src/lib.rs b/substrate/frame/session/benchmarking/src/lib.rs index 8f1911c125b8532646a6a93c3ac0eef501efaa88..06dfa3da349438d976d4610d4a181f1d9a3ffcfd 100644 --- a/substrate/frame/session/benchmarking/src/lib.rs +++ b/substrate/frame/session/benchmarking/src/lib.rs @@ -28,7 +28,7 @@ use sp_std::vec; use frame_benchmarking::benchmarks; use frame_support::{ codec::Decode, - storage::{StorageValue, StorageMap}, + storage::StorageValue, traits::{KeyOwnerProofSystem, OnInitialize}, }; use frame_system::RawOrigin; diff --git a/substrate/frame/system/src/extensions/check_mortality.rs b/substrate/frame/system/src/extensions/check_mortality.rs index 8e5fd36e6217a223be896498f0e8c3f48d137a83..f1951baba5d50133f00e6ff0ded91920642fd37b 100644 --- a/substrate/frame/system/src/extensions/check_mortality.rs +++ b/substrate/frame/system/src/extensions/check_mortality.rs @@ -17,7 +17,6 @@ use codec::{Encode, Decode}; use crate::{Config, Module, BlockHash}; -use frame_support::StorageMap; use sp_runtime::{ generic::Era, traits::{SignedExtension, DispatchInfoOf, SaturatedConversion}, diff --git a/substrate/frame/system/src/extensions/check_nonce.rs b/substrate/frame/system/src/extensions/check_nonce.rs index c5d0e5242b4848217b17280e6b32d2c8ace218cd..bc48be925bc0d0299488b23513b502c4f380b6c8 100644 --- a/substrate/frame/system/src/extensions/check_nonce.rs +++ b/substrate/frame/system/src/extensions/check_nonce.rs @@ -17,10 +17,7 @@ use codec::{Encode, Decode}; use crate::Config; -use frame_support::{ - weights::DispatchInfo, - StorageMap, -}; +use frame_support::weights::DispatchInfo; use sp_runtime::{ traits::{SignedExtension, DispatchInfoOf, Dispatchable, One}, transaction_validity::{ diff --git a/substrate/frame/system/src/extensions/check_weight.rs b/substrate/frame/system/src/extensions/check_weight.rs index c84c29518593f4ee2bc57a7d4acb820a3c089fca..70116f4b6524bbbc906cb1928f240220bdd4fe34 100644 --- a/substrate/frame/system/src/extensions/check_weight.rs +++ b/substrate/frame/system/src/extensions/check_weight.rs @@ -28,7 +28,6 @@ use sp_runtime::{ use frame_support::{ traits::{Get}, weights::{PostDispatchInfo, DispatchInfo, DispatchClass, priority::FrameTransactionPriority}, - StorageValue, }; /// Block resource (weight) limit check. @@ -115,8 +114,8 @@ impl<T: Config + Send + Sync> CheckWeight<T> where let next_weight = Self::check_block_weight(info)?; Self::check_extrinsic_weight(info)?; - crate::AllExtrinsicsLen::put(next_len); - crate::BlockWeight::put(next_weight); + crate::AllExtrinsicsLen::<T>::put(next_len); + crate::BlockWeight::<T>::put(next_weight); Ok(()) } @@ -257,7 +256,7 @@ impl<T: Config + Send + Sync> SignedExtension for CheckWeight<T> where let unspent = post_info.calc_unspent(info); if unspent > 0 { - crate::BlockWeight::mutate(|current_weight| { + crate::BlockWeight::<T>::mutate(|current_weight| { current_weight.sub(unspent, info.class); }) } @@ -465,7 +464,7 @@ mod tests { let normal_limit = normal_weight_limit(); // given almost full block - BlockWeight::mutate(|current_weight| { + BlockWeight::<Test>::mutate(|current_weight| { current_weight.set(normal_limit, DispatchClass::Normal) }); // will not fit. @@ -475,7 +474,7 @@ mod tests { // likewise for length limit. let len = 100_usize; - AllExtrinsicsLen::put(normal_length_limit()); + AllExtrinsicsLen::<Test>::put(normal_length_limit()); assert!(CheckWeight::<Test>(PhantomData).pre_dispatch(&1, CALL, &normal, len).is_err()); assert!(CheckWeight::<Test>(PhantomData).pre_dispatch(&1, CALL, &op, len).is_ok()); }) @@ -508,7 +507,7 @@ mod tests { let normal = DispatchInfo::default(); let normal_limit = normal_weight_limit() as usize; let reset_check_weight = |tx, s, f| { - AllExtrinsicsLen::put(0); + AllExtrinsicsLen::<Test>::put(0); let r = CheckWeight::<Test>(PhantomData).pre_dispatch(&1, CALL, tx, s); if f { assert!(r.is_err()) } else { assert!(r.is_ok()) } }; @@ -544,7 +543,7 @@ mod tests { let len = 0_usize; let reset_check_weight = |i, f, s| { - BlockWeight::mutate(|current_weight| { + BlockWeight::<Test>::mutate(|current_weight| { current_weight.set(s, DispatchClass::Normal) }); let r = CheckWeight::<Test>(PhantomData).pre_dispatch(&1, CALL, i, len); @@ -570,20 +569,20 @@ mod tests { let base_extrinsic = block_weights().get(DispatchClass::Normal).base_extrinsic; // We allow 75% for normal transaction, so we put 25% - extrinsic base weight - BlockWeight::mutate(|current_weight| { + BlockWeight::<Test>::mutate(|current_weight| { current_weight.set(0, DispatchClass::Mandatory); current_weight.set(256 - base_extrinsic, DispatchClass::Normal); }); let pre = CheckWeight::<Test>(PhantomData).pre_dispatch(&1, CALL, &info, len).unwrap(); - assert_eq!(BlockWeight::get().total(), info.weight + 256); + assert_eq!(BlockWeight::<Test>::get().total(), info.weight + 256); assert!( CheckWeight::<Test>::post_dispatch(pre, &info, &post_info, len, &Ok(())) .is_ok() ); assert_eq!( - BlockWeight::get().total(), + BlockWeight::<Test>::get().total(), post_info.actual_weight.unwrap() + 256, ); }) @@ -599,14 +598,14 @@ mod tests { }; let len = 0_usize; - BlockWeight::mutate(|current_weight| { + BlockWeight::<Test>::mutate(|current_weight| { current_weight.set(0, DispatchClass::Mandatory); current_weight.set(128, DispatchClass::Normal); }); let pre = CheckWeight::<Test>(PhantomData).pre_dispatch(&1, CALL, &info, len).unwrap(); assert_eq!( - BlockWeight::get().total(), + BlockWeight::<Test>::get().total(), info.weight + 128 + block_weights().get(DispatchClass::Normal).base_extrinsic, ); @@ -615,7 +614,7 @@ mod tests { .is_ok() ); assert_eq!( - BlockWeight::get().total(), + BlockWeight::<Test>::get().total(), info.weight + 128 + block_weights().get(DispatchClass::Normal).base_extrinsic, ); }) diff --git a/substrate/frame/system/src/lib.rs b/substrate/frame/system/src/lib.rs index 0efa511e99b5e9bb9dda8ee4eea768b888d84cee..cdb26623734fdfe61aaa77f81571f8291144342c 100644 --- a/substrate/frame/system/src/lib.rs +++ b/substrate/frame/system/src/lib.rs @@ -15,17 +15,17 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! # System Module +//! # System Pallet //! -//! The System module provides low-level access to core types and cross-cutting utilities. +//! The System pallet provides low-level access to core types and cross-cutting utilities. //! It acts as the base layer for other pallets to interact with the Substrate framework components. //! -//! - [`system::Config`](./trait.Config.html) +//! - [`Config`] //! //! ## Overview //! -//! The System module defines the core data types used in a Substrate runtime. -//! It also provides several utility functions (see [`Module`](./struct.Module.html)) for other FRAME pallets. +//! The System pallet defines the core data types used in a Substrate runtime. +//! It also provides several utility functions (see [`Pallet`]) for other FRAME pallets. //! //! In addition, it manages the storage items for extrinsics data, indexes, event records, and digest items, //! among other things that support the execution of the current block. @@ -37,15 +37,15 @@ //! //! ### Dispatchable Functions //! -//! The System module does not implement any dispatchable functions. +//! The System pallet does not implement any dispatchable functions. //! //! ### Public Functions //! -//! See the [`Module`](./struct.Module.html) struct for details of publicly available functions. +//! See the [`Pallet`] struct for details of publicly available functions. //! //! ### Signed Extensions //! -//! The System module defines the following extensions: +//! The System pallet defines the following extensions: //! //! - [`CheckWeight`]: Checks the weight and length of the block and ensure that it does not //! exceed the limits. @@ -61,34 +61,6 @@ //! //! Lookup the runtime aggregator file (e.g. `node/runtime`) to see the full list of signed //! extensions included in a chain. -//! -//! ## Usage -//! -//! ### Prerequisites -//! -//! Import the System module and derive your module's configuration trait from the system trait. -//! -//! ### Example - Get extrinsic count and parent hash for the current block -//! -//! ``` -//! use frame_support::{decl_module, dispatch}; -//! use frame_system::{self as system, ensure_signed}; -//! -//! pub trait Config: system::Config {} -//! -//! decl_module! { -//! pub struct Module<T: Config> for enum Call where origin: T::Origin { -//! #[weight = 0] -//! pub fn system_module_example(origin) -> dispatch::DispatchResult { -//! let _sender = ensure_signed(origin)?; -//! let _extrinsic_count = <system::Module<T>>::extrinsic_count(); -//! let _parent_hash = <system::Module<T>>::parent_hash(); -//! Ok(()) -//! } -//! } -//! } -//! # fn main() { } -//! ``` #![cfg_attr(not(feature = "std"), no_std)] @@ -113,7 +85,7 @@ use sp_runtime::{ use sp_core::{ChangesTrieConfiguration, storage::well_known_keys}; use frame_support::{ - decl_module, decl_event, decl_storage, decl_error, Parameter, debug, storage, + Parameter, debug, storage, traits::{ Contains, Get, PalletInfo, OnNewAccount, OnKilledAccount, HandleLifetime, StoredMap, EnsureOrigin, OriginTrait, Filter, @@ -126,6 +98,8 @@ use frame_support::{ }; use codec::{Encode, Decode, FullCodec, EncodeLike}; +#[cfg(feature = "std")] +use frame_support::traits::GenesisBuild; #[cfg(any(feature = "std", test))] use sp_io::TestExternalities; @@ -162,401 +136,132 @@ pub fn extrinsics_data_root<H: Hash>(xts: Vec<Vec<u8>>) -> H::Output { /// An object to track the currently used extrinsic weight in a block. pub type ConsumedWeight = PerDispatchClass<Weight>; -/// System configuration trait. Implemented by runtime. -pub trait Config: 'static + Eq + Clone { - /// The basic call filter to use in Origin. All origins are built with this filter as base, - /// except Root. - type BaseCallFilter: Filter<Self::Call>; - - /// Block & extrinsics weights: base values and limits. - type BlockWeights: Get<limits::BlockWeights>; - - /// The maximum length of a block (in bytes). - type BlockLength: Get<limits::BlockLength>; - - /// The `Origin` type used by dispatchable calls. - type Origin: - Into<Result<RawOrigin<Self::AccountId>, Self::Origin>> - + From<RawOrigin<Self::AccountId>> - + Clone - + OriginTrait<Call = Self::Call>; - - /// The aggregated `Call` type. - type Call: Dispatchable + Debug; - - /// Account index (aka nonce) type. This stores the number of previous transactions associated - /// with a sender account. - type Index: - Parameter + Member + MaybeSerialize + Debug + Default + MaybeDisplay + AtLeast32Bit - + Copy; - - /// The block number type used by the runtime. - type BlockNumber: - Parameter + Member + MaybeSerializeDeserialize + Debug + MaybeDisplay + - AtLeast32BitUnsigned + Default + Bounded + Copy + sp_std::hash::Hash + - sp_std::str::FromStr + MaybeMallocSizeOf; - - /// The output of the `Hashing` function. - type Hash: - Parameter + Member + MaybeSerializeDeserialize + Debug + MaybeDisplay + SimpleBitOps + Ord - + Default + Copy + CheckEqual + sp_std::hash::Hash + AsRef<[u8]> + AsMut<[u8]> + MaybeMallocSizeOf; - - /// The hashing system (algorithm) being used in the runtime (e.g. Blake2). - type Hashing: Hash<Output = Self::Hash>; - - /// The user account identifier type for the runtime. - type AccountId: Parameter + Member + MaybeSerializeDeserialize + Debug + MaybeDisplay + Ord - + Default; - - /// Converting trait to take a source type and convert to `AccountId`. - /// - /// Used to define the type and conversion mechanism for referencing accounts in transactions. - /// It's perfectly reasonable for this to be an identity conversion (with the source type being - /// `AccountId`), but other modules (e.g. Indices module) may provide more functional/efficient - /// alternatives. - type Lookup: StaticLookup<Target = Self::AccountId>; - - /// The block header. - type Header: Parameter + traits::Header< - Number = Self::BlockNumber, - Hash = Self::Hash, - >; - - /// The aggregated event type of the runtime. - type Event: Parameter + Member + From<Event<Self>> + Debug; - - /// Maximum number of block number to block hash mappings to keep (oldest pruned first). - type BlockHashCount: Get<Self::BlockNumber>; - - /// The weight of runtime database operations the runtime can invoke. - type DbWeight: Get<RuntimeDbWeight>; - - /// Get the chain's current version. - type Version: Get<RuntimeVersion>; - - /// Provides information about the pallet setup in the runtime. - /// - /// Expects the `PalletInfo` type that is being generated by `construct_runtime!` in the - /// runtime. - /// - /// For tests it is okay to use `()` as type, however it will provide "useless" data. - type PalletInfo: PalletInfo; - - /// Data to be associated with an account (other than nonce/transaction counter, which this - /// module does regardless). - type AccountData: Member + FullCodec + Clone + Default; - - /// Handler for when a new account has just been created. - type OnNewAccount: OnNewAccount<Self::AccountId>; - - /// A function that is invoked when an account has been determined to be dead. - /// - /// All resources should be cleaned up associated with the given account. - type OnKilledAccount: OnKilledAccount<Self::AccountId>; - - type SystemWeightInfo: WeightInfo; - - /// The designated SS85 prefix of this chain. - /// - /// This replaces the "ss58Format" property declared in the chain spec. Reason is - /// that the runtime should know about the prefix in order to make use of it as - /// an identifier of the chain. - type SS58Prefix: Get<u8>; -} - -pub type DigestOf<T> = generic::Digest<<T as Config>::Hash>; -pub type DigestItemOf<T> = generic::DigestItem<<T as Config>::Hash>; - -pub type Key = Vec<u8>; -pub type KeyValue = (Vec<u8>, Vec<u8>); - -/// A phase of a block's execution. -#[derive(Encode, Decode, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(Serialize, PartialEq, Eq, Clone))] -pub enum Phase { - /// Applying an extrinsic. - ApplyExtrinsic(u32), - /// Finalizing the block. - Finalization, - /// Initializing the block. - Initialization, -} - -impl Default for Phase { - fn default() -> Self { - Self::Initialization - } -} - -/// Record of an event happening. -#[derive(Encode, Decode, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(Serialize, PartialEq, Eq, Clone))] -pub struct EventRecord<E: Parameter + Member, T> { - /// The phase of the block it happened in. - pub phase: Phase, - /// The event itself. - pub event: E, - /// The list of the topics this event has. - pub topics: Vec<T>, -} - -/// Origin for the System module. -#[derive(PartialEq, Eq, Clone, RuntimeDebug, Encode, Decode)] -pub enum RawOrigin<AccountId> { - /// The system itself ordained this dispatch to happen: this is the highest privilege level. - Root, - /// It is signed by some public key and we provide the `AccountId`. - Signed(AccountId), - /// It is signed by nobody, can be either: - /// * included and agreed upon by the validators anyway, - /// * or unsigned transaction validated by a module. - None, -} - -impl<AccountId> From<Option<AccountId>> for RawOrigin<AccountId> { - fn from(s: Option<AccountId>) -> RawOrigin<AccountId> { - match s { - Some(who) => RawOrigin::Signed(who), - None => RawOrigin::None, - } - } -} - -/// Exposed trait-generic origin type. -pub type Origin<T> = RawOrigin<<T as Config>::AccountId>; - -// Create a Hash with 69 for each byte, -// only used to build genesis config. -#[cfg(feature = "std")] -fn hash69<T: AsMut<[u8]> + Default>() -> T { - let mut h = T::default(); - h.as_mut().iter_mut().for_each(|byte| *byte = 69); - h -} - -/// This type alias represents an index of an event. -/// -/// We use `u32` here because this index is used as index for `Events<T>` -/// which can't contain more than `u32::max_value()` items. -type EventIndex = u32; - -/// Type used to encode the number of references an account has. -pub type RefCount = u32; - -/// Information of an account. -#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode)] -pub struct AccountInfo<Index, AccountData> { - /// The number of transactions this account has sent. - pub nonce: Index, - /// The number of other modules that currently depend on this account's existence. The account - /// cannot be reaped until this is zero. - pub consumers: RefCount, - /// The number of other modules that allow this account to exist. The account may not be reaped - /// until this is zero. - pub providers: RefCount, - /// The additional data that belongs to this account. Used to store the balance(s) in a lot of - /// chains. - pub data: AccountData, -} - -/// Stores the `spec_version` and `spec_name` of when the last runtime upgrade -/// happened. -#[derive(sp_runtime::RuntimeDebug, Encode, Decode)] -#[cfg_attr(feature = "std", derive(PartialEq))] -pub struct LastRuntimeUpgradeInfo { - pub spec_version: codec::Compact<u32>, - pub spec_name: sp_runtime::RuntimeString, -} - -impl LastRuntimeUpgradeInfo { - /// Returns if the runtime was upgraded in comparison of `self` and `current`. - /// - /// Checks if either the `spec_version` increased or the `spec_name` changed. - pub fn was_upgraded(&self, current: &sp_version::RuntimeVersion) -> bool { - current.spec_version > self.spec_version.0 || current.spec_name != self.spec_name - } -} - -impl From<sp_version::RuntimeVersion> for LastRuntimeUpgradeInfo { - fn from(version: sp_version::RuntimeVersion) -> Self { - Self { - spec_version: version.spec_version.into(), - spec_name: version.spec_name, - } - } -} - -decl_storage! { - trait Store for Module<T: Config> as System { - /// The full account information for a particular account ID. - pub Account get(fn account): - map hasher(blake2_128_concat) T::AccountId => AccountInfo<T::Index, T::AccountData>; - - /// Total extrinsics count for the current block. - ExtrinsicCount: Option<u32>; - - /// The current weight for the block. - BlockWeight get(fn block_weight): ConsumedWeight; - - /// Total length (in bytes) for all extrinsics put together, for the current block. - AllExtrinsicsLen: Option<u32>; - - /// Map of block numbers to block hashes. - pub BlockHash get(fn block_hash) build(|_| vec![(T::BlockNumber::zero(), hash69())]): - map hasher(twox_64_concat) T::BlockNumber => T::Hash; - - /// Extrinsics data for the current block (maps an extrinsic's index to its data). - ExtrinsicData get(fn extrinsic_data): map hasher(twox_64_concat) u32 => Vec<u8>; - - /// The current block number being processed. Set by `execute_block`. - Number get(fn block_number): T::BlockNumber; +pub use pallet::*; + +#[frame_support::pallet] +pub mod pallet { + use crate::{*, pallet_prelude::*, self as frame_system}; + use frame_support::pallet_prelude::*; + + /// System configuration trait. Implemented by runtime. + #[pallet::config] + #[pallet::disable_frame_system_supertrait_check] + pub trait Config: 'static + Eq + Clone { + /// The basic call filter to use in Origin. All origins are built with this filter as base, + /// except Root. + type BaseCallFilter: Filter<Self::Call>; + + /// Block & extrinsics weights: base values and limits. + #[pallet::constant] + type BlockWeights: Get<limits::BlockWeights>; + + /// The maximum length of a block (in bytes). + #[pallet::constant] + type BlockLength: Get<limits::BlockLength>; + + /// The `Origin` type used by dispatchable calls. + type Origin: + Into<Result<RawOrigin<Self::AccountId>, Self::Origin>> + + From<RawOrigin<Self::AccountId>> + + Clone + + OriginTrait<Call=Self::Call>; + + /// The aggregated `Call` type. + type Call: Dispatchable + Debug; + + /// Account index (aka nonce) type. This stores the number of previous transactions associated + /// with a sender account. + type Index: + Parameter + Member + MaybeSerialize + Debug + Default + MaybeDisplay + AtLeast32Bit + + Copy; + + /// The block number type used by the runtime. + type BlockNumber: + Parameter + Member + MaybeSerializeDeserialize + Debug + MaybeDisplay + + AtLeast32BitUnsigned + Default + Bounded + Copy + sp_std::hash::Hash + + sp_std::str::FromStr + MaybeMallocSizeOf; + + /// The output of the `Hashing` function. + type Hash: + Parameter + Member + MaybeSerializeDeserialize + Debug + MaybeDisplay + SimpleBitOps + Ord + + Default + Copy + CheckEqual + sp_std::hash::Hash + AsRef<[u8]> + AsMut<[u8]> + MaybeMallocSizeOf; + + /// The hashing system (algorithm) being used in the runtime (e.g. Blake2). + type Hashing: Hash<Output=Self::Hash>; + + /// The user account identifier type for the runtime. + type AccountId: Parameter + Member + MaybeSerializeDeserialize + Debug + MaybeDisplay + Ord + + Default; + + /// Converting trait to take a source type and convert to `AccountId`. + /// + /// Used to define the type and conversion mechanism for referencing accounts in transactions. + /// It's perfectly reasonable for this to be an identity conversion (with the source type being + /// `AccountId`), but other pallets (e.g. Indices pallet) may provide more functional/efficient + /// alternatives. + type Lookup: StaticLookup<Target=Self::AccountId>; - /// Hash of the previous block. - ParentHash get(fn parent_hash) build(|_| hash69()): T::Hash; + /// The block header. + type Header: Parameter + traits::Header< + Number=Self::BlockNumber, + Hash=Self::Hash, + >; - /// Digest of the current block, also part of the block header. - Digest get(fn digest): DigestOf<T>; + /// The aggregated event type of the runtime. + type Event: Parameter + Member + From<Event<Self>> + Debug + IsType<<Self as frame_system::Config>::Event>; - /// Events deposited for the current block. - Events get(fn events): Vec<EventRecord<T::Event, T::Hash>>; + /// Maximum number of block number to block hash mappings to keep (oldest pruned first). + #[pallet::constant] + type BlockHashCount: Get<Self::BlockNumber>; - /// The number of events in the `Events<T>` list. - EventCount get(fn event_count): EventIndex; + /// The weight of runtime database operations the runtime can invoke. + #[pallet::constant] + type DbWeight: Get<RuntimeDbWeight>; - // TODO: https://github.com/paritytech/substrate/issues/2553 - // Possibly, we can improve it by using something like: - // `Option<(BlockNumber, Vec<EventIndex>)>`, however in this case we won't be able to use - // `EventTopics::append`. + /// Get the chain's current version. + #[pallet::constant] + type Version: Get<RuntimeVersion>; - /// Mapping between a topic (represented by T::Hash) and a vector of indexes - /// of events in the `<Events<T>>` list. + /// Provides information about the pallet setup in the runtime. /// - /// All topic vectors have deterministic storage locations depending on the topic. This - /// allows light-clients to leverage the changes trie storage tracking mechanism and - /// in case of changes fetch the list of events of interest. + /// Expects the `PalletInfo` type that is being generated by `construct_runtime!` in the + /// runtime. /// - /// The value has the type `(T::BlockNumber, EventIndex)` because if we used only just - /// the `EventIndex` then in case if the topic has the same contents on the next block - /// no notification will be triggered thus the event might be lost. - EventTopics get(fn event_topics): map hasher(blake2_128_concat) T::Hash => Vec<(T::BlockNumber, EventIndex)>; - - /// Stores the `spec_version` and `spec_name` of when the last runtime upgrade happened. - pub LastRuntimeUpgrade build(|_| Some(LastRuntimeUpgradeInfo::from(T::Version::get()))): Option<LastRuntimeUpgradeInfo>; + /// For tests it is okay to use `()` as type, however it will provide "useless" data. + type PalletInfo: PalletInfo; - /// True if we have upgraded so that `type RefCount` is `u32`. False (default) if not. - UpgradedToU32RefCount build(|_| true): bool; + /// Data to be associated with an account (other than nonce/transaction counter, which this + /// pallet does regardless). + type AccountData: Member + FullCodec + Clone + Default; - /// True if we have upgraded so that AccountInfo contains two types of `RefCount`. False - /// (default) if not. - UpgradedToDualRefCount build(|_| true): bool; + /// Handler for when a new account has just been created. + type OnNewAccount: OnNewAccount<Self::AccountId>; - /// The execution phase of the block. - ExecutionPhase: Option<Phase>; - } - add_extra_genesis { - config(changes_trie_config): Option<ChangesTrieConfiguration>; - #[serde(with = "sp_core::bytes")] - config(code): Vec<u8>; - - build(|config: &GenesisConfig| { - use codec::Encode; - - sp_io::storage::set(well_known_keys::CODE, &config.code); - sp_io::storage::set(well_known_keys::EXTRINSIC_INDEX, &0u32.encode()); - - if let Some(ref changes_trie_config) = config.changes_trie_config { - sp_io::storage::set( - well_known_keys::CHANGES_TRIE_CONFIG, - &changes_trie_config.encode(), - ); - } - }); - } -} - -decl_event!( - /// Event for the System module. - pub enum Event<T> where AccountId = <T as Config>::AccountId { - /// An extrinsic completed successfully. \[info\] - ExtrinsicSuccess(DispatchInfo), - /// An extrinsic failed. \[error, info\] - ExtrinsicFailed(DispatchError, DispatchInfo), - /// `:code` was updated. - CodeUpdated, - /// A new \[account\] was created. - NewAccount(AccountId), - /// An \[account\] was reaped. - KilledAccount(AccountId), - } -); - -decl_error! { - /// Error for the System module - pub enum Error for Module<T: Config> { - /// The name of specification does not match between the current runtime - /// and the new runtime. - InvalidSpecName, - /// The specification version is not allowed to decrease between the current runtime - /// and the new runtime. - SpecVersionNeedsToIncrease, - /// Failed to extract the runtime version from the new runtime. + /// A function that is invoked when an account has been determined to be dead. /// - /// Either calling `Core_version` or decoding `RuntimeVersion` failed. - FailedToExtractRuntimeVersion, - /// Suicide called when the account has non-default composite data. - NonDefaultComposite, - /// There is a non-zero reference count preventing the account from being purged. - NonZeroRefCount, - } -} - -mod migrations { - use super::*; - - #[allow(dead_code)] - pub fn migrate_all<T: Config>() -> frame_support::weights::Weight { - Account::<T>::translate::<(T::Index, u8, T::AccountData), _>(|_key, (nonce, rc, data)| - Some(AccountInfo { nonce, consumers: rc as RefCount, providers: 1, data }) - ); - T::BlockWeights::get().max_block - } - - pub fn migrate_to_dual_ref_count<T: Config>() -> frame_support::weights::Weight { - Account::<T>::translate::<(T::Index, RefCount, T::AccountData), _>(|_key, (nonce, rc, data)| - Some(AccountInfo { nonce, consumers: rc as RefCount, providers: 1, data }) - ); - T::BlockWeights::get().max_block - } -} + /// All resources should be cleaned up associated with the given account. + type OnKilledAccount: OnKilledAccount<Self::AccountId>; -/// Pallet struct placeholder on which is implemented the pallet logic. -/// -/// It is currently an alias for `Module` as old macros still generate/use old name. -pub type Pallet<T> = Module<T>; - -decl_module! { - pub struct Module<T: Config> for enum Call where origin: T::Origin, system=self { - type Error = Error<T>; - - /// The maximum number of blocks to allow in mortal eras. - const BlockHashCount: T::BlockNumber = T::BlockHashCount::get(); - - /// The weight of runtime database operations the runtime can invoke. - const DbWeight: RuntimeDbWeight = T::DbWeight::get(); - - /// The weight configuration (limits & base values) for each class of extrinsics and block. - const BlockWeights: limits::BlockWeights = T::BlockWeights::get(); + type SystemWeightInfo: WeightInfo; /// The designated SS85 prefix of this chain. /// /// This replaces the "ss58Format" property declared in the chain spec. Reason is /// that the runtime should know about the prefix in order to make use of it as /// an identifier of the chain. - const SS58Prefix: u8 = T::SS58Prefix::get(); + #[pallet::constant] + type SS58Prefix: Get<u8>; + } + #[pallet::pallet] + #[pallet::generate_store(pub (super) trait Store)] + pub struct Pallet<T>(PhantomData<T>); + + #[pallet::hooks] + impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> { fn on_runtime_upgrade() -> frame_support::weights::Weight { - if !UpgradedToDualRefCount::get() { - UpgradedToDualRefCount::put(true); + if !UpgradedToDualRefCount::<T>::get() { + UpgradedToDualRefCount::<T>::put(true); migrations::migrate_to_dual_ref_count::<T>() } else { 0 @@ -568,13 +273,17 @@ decl_module! { .validate() .expect("The weights are invalid."); } + } + #[pallet::call] + impl<T: Config> Pallet<T> { /// A dispatch that will fill the block weight up to the given ratio. // TODO: This should only be available for testing, rather than in general usage, but - // that's not possible at present (since it's within the decl_module macro). - #[weight = *_ratio * T::BlockWeights::get().max_block] - fn fill_block(origin, _ratio: Perbill) { + // that's not possible at present (since it's within the pallet macro). + #[pallet::weight(*_ratio * T::BlockWeights::get().max_block)] + pub(crate) fn fill_block(origin: OriginFor<T>, _ratio: Perbill) -> DispatchResultWithPostInfo { ensure_root(origin)?; + Ok(().into()) } /// Make some on-chain remark. @@ -584,9 +293,10 @@ decl_module! { /// - Base Weight: 0.665 µs, independent of remark length. /// - No DB operations. /// # </weight> - #[weight = T::SystemWeightInfo::remark(_remark.len() as u32)] - fn remark(origin, _remark: Vec<u8>) { + #[pallet::weight(T::SystemWeightInfo::remark(_remark.len() as u32))] + pub(crate) fn remark(origin: OriginFor<T>, _remark: Vec<u8>) -> DispatchResultWithPostInfo { ensure_signed(origin)?; + Ok(().into()) } /// Set the number of pages in the WebAssembly environment's heap. @@ -597,10 +307,11 @@ decl_module! { /// - Base Weight: 1.405 µs /// - 1 write to HEAP_PAGES /// # </weight> - #[weight = (T::SystemWeightInfo::set_heap_pages(), DispatchClass::Operational)] - fn set_heap_pages(origin, pages: u64) { + #[pallet::weight((T::SystemWeightInfo::set_heap_pages(), DispatchClass::Operational))] + pub(crate) fn set_heap_pages(origin: OriginFor<T>, pages: u64) -> DispatchResultWithPostInfo { ensure_root(origin)?; storage::unhashed::put_raw(well_known_keys::HEAP_PAGES, &pages.encode()); + Ok(().into()) } /// Set the new runtime code. @@ -613,13 +324,14 @@ decl_module! { /// The weight of this function is dependent on the runtime, but generally this is very expensive. /// We will treat this as a full block. /// # </weight> - #[weight = (T::BlockWeights::get().max_block, DispatchClass::Operational)] - pub fn set_code(origin, code: Vec<u8>) { + #[pallet::weight((T::BlockWeights::get().max_block, DispatchClass::Operational))] + pub fn set_code(origin: OriginFor<T>, code: Vec<u8>) -> DispatchResultWithPostInfo { ensure_root(origin)?; Self::can_set_code(&code)?; storage::unhashed::put_raw(well_known_keys::CODE, &code); - Self::deposit_event(RawEvent::CodeUpdated); + Self::deposit_event(Event::CodeUpdated); + Ok(().into()) } /// Set the new runtime code without doing any checks of the given `code`. @@ -630,11 +342,15 @@ decl_module! { /// - 1 event. /// The weight of this function is dependent on the runtime. We will treat this as a full block. /// # </weight> - #[weight = (T::BlockWeights::get().max_block, DispatchClass::Operational)] - pub fn set_code_without_checks(origin, code: Vec<u8>) { + #[pallet::weight((T::BlockWeights::get().max_block, DispatchClass::Operational))] + pub fn set_code_without_checks( + origin: OriginFor<T>, + code: Vec<u8>, + ) -> DispatchResultWithPostInfo { ensure_root(origin)?; storage::unhashed::put_raw(well_known_keys::CODE, &code); - Self::deposit_event(RawEvent::CodeUpdated); + Self::deposit_event(Event::CodeUpdated); + Ok(().into()) } /// Set the new changes trie configuration. @@ -647,8 +363,11 @@ decl_module! { /// - DB Weight: /// - Writes: Changes Trie, System Digest /// # </weight> - #[weight = (T::SystemWeightInfo::set_changes_trie_config(), DispatchClass::Operational)] - pub fn set_changes_trie_config(origin, changes_trie_config: Option<ChangesTrieConfiguration>) { + #[pallet::weight((T::SystemWeightInfo::set_changes_trie_config(), DispatchClass::Operational))] + pub fn set_changes_trie_config( + origin: OriginFor<T>, + changes_trie_config: Option<ChangesTrieConfiguration>, + ) -> DispatchResultWithPostInfo { ensure_root(origin)?; match changes_trie_config.clone() { Some(changes_trie_config) => storage::unhashed::put_raw( @@ -662,6 +381,7 @@ decl_module! { generic::ChangesTrieSignal::NewConfiguration(changes_trie_config), ); Self::deposit_log(log.into()); + Ok(().into()) } /// Set some items of storage. @@ -672,15 +392,16 @@ decl_module! { /// - Base Weight: 0.568 * i µs /// - Writes: Number of items /// # </weight> - #[weight = ( + #[pallet::weight(( T::SystemWeightInfo::set_storage(items.len() as u32), DispatchClass::Operational, - )] - fn set_storage(origin, items: Vec<KeyValue>) { + ))] + pub(crate) fn set_storage(origin: OriginFor<T>, items: Vec<KeyValue>) -> DispatchResultWithPostInfo { ensure_root(origin)?; for i in &items { storage::unhashed::put_raw(&i.0, &i.1); } + Ok(().into()) } /// Kill some items from storage. @@ -691,15 +412,16 @@ decl_module! { /// - Base Weight: .378 * i µs /// - Writes: Number of items /// # </weight> - #[weight = ( + #[pallet::weight(( T::SystemWeightInfo::kill_storage(keys.len() as u32), DispatchClass::Operational, - )] - fn kill_storage(origin, keys: Vec<Key>) { + ))] + pub(crate) fn kill_storage(origin: OriginFor<T>, keys: Vec<Key>) -> DispatchResultWithPostInfo { ensure_root(origin)?; for key in &keys { storage::unhashed::kill(&key); } + Ok(().into()) } /// Kill all storage items with a key that starts with the given prefix. @@ -713,13 +435,347 @@ decl_module! { /// - Base Weight: 0.834 * P µs /// - Writes: Number of subkeys + 1 /// # </weight> - #[weight = ( + #[pallet::weight(( T::SystemWeightInfo::kill_prefix(_subkeys.saturating_add(1)), DispatchClass::Operational, - )] - fn kill_prefix(origin, prefix: Key, _subkeys: u32) { + ))] + pub(crate) fn kill_prefix( + origin: OriginFor<T>, + prefix: Key, + _subkeys: u32, + ) -> DispatchResultWithPostInfo { ensure_root(origin)?; storage::unhashed::kill_prefix(&prefix); + Ok(().into()) + } + } + + /// Event for the System pallet. + #[pallet::event] + #[pallet::metadata(T::AccountId = "AccountId")] + pub enum Event<T: Config> { + /// An extrinsic completed successfully. \[info\] + ExtrinsicSuccess(DispatchInfo), + /// An extrinsic failed. \[error, info\] + ExtrinsicFailed(DispatchError, DispatchInfo), + /// `:code` was updated. + CodeUpdated, + /// A new \[account\] was created. + NewAccount(T::AccountId), + /// An \[account\] was reaped. + KilledAccount(T::AccountId), + } + + /// Old name generated by `decl_event`. + #[deprecated(note = "use `Event` instead")] + pub type RawEvent<T> = Event<T>; + + /// Error for the System pallet + #[pallet::error] + pub enum Error<T> { + /// The name of specification does not match between the current runtime + /// and the new runtime. + InvalidSpecName, + /// The specification version is not allowed to decrease between the current runtime + /// and the new runtime. + SpecVersionNeedsToIncrease, + /// Failed to extract the runtime version from the new runtime. + /// + /// Either calling `Core_version` or decoding `RuntimeVersion` failed. + FailedToExtractRuntimeVersion, + /// Suicide called when the account has non-default composite data. + NonDefaultComposite, + /// There is a non-zero reference count preventing the account from being purged. + NonZeroRefCount, + } + + /// Exposed trait-generic origin type. + #[pallet::origin] + pub type Origin<T> = RawOrigin<<T as Config>::AccountId>; + + /// The full account information for a particular account ID. + #[pallet::storage] + #[pallet::getter(fn account)] + pub type Account<T: Config> = StorageMap< + _, + Blake2_128Concat, + T::AccountId, + AccountInfo<T::Index, T::AccountData>, + ValueQuery, + >; + + /// Total extrinsics count for the current block. + #[pallet::storage] + pub(super) type ExtrinsicCount<T: Config> = StorageValue<_, u32>; + + /// The current weight for the block. + #[pallet::storage] + #[pallet::getter(fn block_weight)] + pub(super) type BlockWeight<T: Config> = StorageValue<_, ConsumedWeight, ValueQuery>; + + /// Total length (in bytes) for all extrinsics put together, for the current block. + #[pallet::storage] + pub(super) type AllExtrinsicsLen<T: Config> = StorageValue<_, u32>; + + /// Map of block numbers to block hashes. + #[pallet::storage] + #[pallet::getter(fn block_hash)] + pub type BlockHash<T: Config> = + StorageMap<_, Twox64Concat, T::BlockNumber, T::Hash, ValueQuery>; + + /// Extrinsics data for the current block (maps an extrinsic's index to its data). + #[pallet::storage] + #[pallet::getter(fn extrinsic_data)] + pub(super) type ExtrinsicData<T: Config> = + StorageMap<_, Twox64Concat, u32, Vec<u8>, ValueQuery>; + + /// The current block number being processed. Set by `execute_block`. + #[pallet::storage] + #[pallet::getter(fn block_number)] + pub(super) type Number<T: Config> = StorageValue<_, T::BlockNumber, ValueQuery>; + + /// Hash of the previous block. + #[pallet::storage] + #[pallet::getter(fn parent_hash)] + pub(super) type ParentHash<T: Config> = StorageValue<_, T::Hash, ValueQuery>; + + /// Digest of the current block, also part of the block header. + #[pallet::storage] + #[pallet::getter(fn digest)] + pub(super) type Digest<T: Config> = StorageValue<_, DigestOf<T>, ValueQuery>; + + /// Events deposited for the current block. + #[pallet::storage] + #[pallet::getter(fn events)] + pub(super) type Events<T: Config> = + StorageValue<_, Vec<EventRecord<T::Event, T::Hash>>, ValueQuery>; + + /// The number of events in the `Events<T>` list. + #[pallet::storage] + #[pallet::getter(fn event_count)] + pub(super) type EventCount<T: Config> = StorageValue<_, EventIndex, ValueQuery>; + + /// Mapping between a topic (represented by T::Hash) and a vector of indexes + /// of events in the `<Events<T>>` list. + /// + /// All topic vectors have deterministic storage locations depending on the topic. This + /// allows light-clients to leverage the changes trie storage tracking mechanism and + /// in case of changes fetch the list of events of interest. + /// + /// The value has the type `(T::BlockNumber, EventIndex)` because if we used only just + /// the `EventIndex` then in case if the topic has the same contents on the next block + /// no notification will be triggered thus the event might be lost. + #[pallet::storage] + #[pallet::getter(fn event_topics)] + pub(super) type EventTopics<T: Config> = + StorageMap<_, Blake2_128Concat, T::Hash, Vec<(T::BlockNumber, EventIndex)>, ValueQuery>; + + /// Stores the `spec_version` and `spec_name` of when the last runtime upgrade happened. + #[pallet::storage] + pub type LastRuntimeUpgrade<T: Config> = StorageValue<_, LastRuntimeUpgradeInfo>; + + /// True if we have upgraded so that `type RefCount` is `u32`. False (default) if not. + #[pallet::storage] + pub(super) type UpgradedToU32RefCount<T: Config> = StorageValue<_, bool, ValueQuery>; + + /// True if we have upgraded so that AccountInfo contains two types of `RefCount`. False + /// (default) if not. + #[pallet::storage] + pub(super) type UpgradedToDualRefCount<T: Config> = StorageValue<_, bool, ValueQuery>; + + /// The execution phase of the block. + #[pallet::storage] + pub(super) type ExecutionPhase<T: Config> = StorageValue<_, Phase>; + + #[pallet::genesis_config] + pub struct GenesisConfig { + pub changes_trie_config: Option<ChangesTrieConfiguration>, + #[serde(with = "sp_core::bytes")] + pub code: Vec<u8>, + } + + #[cfg(feature = "std")] + impl Default for GenesisConfig { + fn default() -> Self { + Self { + changes_trie_config: Default::default(), + code: Default::default(), + } + } + } + + #[pallet::genesis_build] + impl<T: Config> GenesisBuild<T> for GenesisConfig { + fn build(&self) { + <BlockHash<T>>::insert::<_, T::Hash>(T::BlockNumber::zero(), hash69()); + <ParentHash<T>>::put::<T::Hash>(hash69()); + <LastRuntimeUpgrade<T>>::put(LastRuntimeUpgradeInfo::from(T::Version::get())); + <UpgradedToU32RefCount<T>>::put(true); + <UpgradedToDualRefCount<T>>::put(true); + + sp_io::storage::set(well_known_keys::CODE, &self.code); + sp_io::storage::set(well_known_keys::EXTRINSIC_INDEX, &0u32.encode()); + if let Some(ref changes_trie_config) = self.changes_trie_config { + sp_io::storage::set(well_known_keys::CHANGES_TRIE_CONFIG, &changes_trie_config.encode()); + } + } + } +} + +mod migrations { + use super::*; + + #[allow(dead_code)] + pub fn migrate_all<T: Config>() -> frame_support::weights::Weight { + Account::<T>::translate::<(T::Index, u8, T::AccountData), _>(|_key, (nonce, rc, data)| + Some(AccountInfo { nonce, consumers: rc as RefCount, providers: 1, data }) + ); + T::BlockWeights::get().max_block + } + + pub fn migrate_to_dual_ref_count<T: Config>() -> frame_support::weights::Weight { + Account::<T>::translate::<(T::Index, RefCount, T::AccountData), _>(|_key, (nonce, rc, data)| + Some(AccountInfo { nonce, consumers: rc as RefCount, providers: 1, data }) + ); + T::BlockWeights::get().max_block + } +} + +#[cfg(feature = "std")] +impl GenesisConfig { + /// Direct implementation of `GenesisBuild::build_storage`. + /// + /// Kept in order not to break dependency. + pub fn build_storage<T: Config>(&self) -> Result<sp_runtime::Storage, String> { + <Self as GenesisBuild<T>>::build_storage(self) + } + + /// Direct implementation of `GenesisBuild::assimilate_storage`. + /// + /// Kept in order not to break dependency. + pub fn assimilate_storage<T: Config>( + &self, + storage: &mut sp_runtime::Storage + ) -> Result<(), String> { + <Self as GenesisBuild<T>>::assimilate_storage(self, storage) + } +} + +pub type DigestOf<T> = generic::Digest<<T as Config>::Hash>; +pub type DigestItemOf<T> = generic::DigestItem<<T as Config>::Hash>; + +pub type Key = Vec<u8>; +pub type KeyValue = (Vec<u8>, Vec<u8>); + +/// A phase of a block's execution. +#[derive(Encode, Decode, RuntimeDebug)] +#[cfg_attr(feature = "std", derive(Serialize, PartialEq, Eq, Clone))] +pub enum Phase { + /// Applying an extrinsic. + ApplyExtrinsic(u32), + /// Finalizing the block. + Finalization, + /// Initializing the block. + Initialization, +} + +impl Default for Phase { + fn default() -> Self { + Self::Initialization + } +} + +/// Record of an event happening. +#[derive(Encode, Decode, RuntimeDebug)] +#[cfg_attr(feature = "std", derive(Serialize, PartialEq, Eq, Clone))] +pub struct EventRecord<E: Parameter + Member, T> { + /// The phase of the block it happened in. + pub phase: Phase, + /// The event itself. + pub event: E, + /// The list of the topics this event has. + pub topics: Vec<T>, +} + +/// Origin for the System pallet. +#[derive(PartialEq, Eq, Clone, RuntimeDebug, Encode, Decode)] +pub enum RawOrigin<AccountId> { + /// The system itself ordained this dispatch to happen: this is the highest privilege level. + Root, + /// It is signed by some public key and we provide the `AccountId`. + Signed(AccountId), + /// It is signed by nobody, can be either: + /// * included and agreed upon by the validators anyway, + /// * or unsigned transaction validated by a pallet. + None, +} + +impl<AccountId> From<Option<AccountId>> for RawOrigin<AccountId> { + fn from(s: Option<AccountId>) -> RawOrigin<AccountId> { + match s { + Some(who) => RawOrigin::Signed(who), + None => RawOrigin::None, + } + } +} + +// Create a Hash with 69 for each byte, +// only used to build genesis config. +#[cfg(feature = "std")] +fn hash69<T: AsMut<[u8]> + Default>() -> T { + let mut h = T::default(); + h.as_mut().iter_mut().for_each(|byte| *byte = 69); + h +} + +/// This type alias represents an index of an event. +/// +/// We use `u32` here because this index is used as index for `Events<T>` +/// which can't contain more than `u32::max_value()` items. +type EventIndex = u32; + +/// Type used to encode the number of references an account has. +pub type RefCount = u32; + +/// Information of an account. +#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode)] +pub struct AccountInfo<Index, AccountData> { + /// The number of transactions this account has sent. + pub nonce: Index, + /// The number of other modules that currently depend on this account's existence. The account + /// cannot be reaped until this is zero. + pub consumers: RefCount, + /// The number of other modules that allow this account to exist. The account may not be reaped + /// until this is zero. + pub providers: RefCount, + /// The additional data that belongs to this account. Used to store the balance(s) in a lot of + /// chains. + pub data: AccountData, +} + +/// Stores the `spec_version` and `spec_name` of when the last runtime upgrade +/// happened. +#[derive(sp_runtime::RuntimeDebug, Encode, Decode)] +#[cfg_attr(feature = "std", derive(PartialEq))] +pub struct LastRuntimeUpgradeInfo { + pub spec_version: codec::Compact<u32>, + pub spec_name: sp_runtime::RuntimeString, +} + +impl LastRuntimeUpgradeInfo { + /// Returns if the runtime was upgraded in comparison of `self` and `current`. + /// + /// Checks if either the `spec_version` increased or the `spec_name` changed. + pub fn was_upgraded(&self, current: &sp_version::RuntimeVersion) -> bool { + current.spec_version > self.spec_version.0 || current.spec_name != self.spec_name + } +} + +impl From<sp_version::RuntimeVersion> for LastRuntimeUpgradeInfo { + fn from(version: sp_version::RuntimeVersion) -> Self { + Self { + spec_version: version.spec_version.into(), + spec_name: version.spec_name, } } } @@ -1064,7 +1120,7 @@ impl<T: Config> Module<T> { // Don't populate events on genesis. if block_number.is_zero() { return } - let phase = ExecutionPhase::get().unwrap_or_default(); + let phase = ExecutionPhase::<T>::get().unwrap_or_default(); let event = EventRecord { phase, event, @@ -1073,14 +1129,14 @@ impl<T: Config> Module<T> { // Index of the to be added event. let event_idx = { - let old_event_count = EventCount::get(); + let old_event_count = EventCount::<T>::get(); let new_event_count = match old_event_count.checked_add(1) { // We've reached the maximum number of events at this block, just // don't do anything and leave the event_count unaltered. None => return, Some(nc) => nc, }; - EventCount::put(new_event_count); + EventCount::<T>::put(new_event_count); old_event_count }; @@ -1098,17 +1154,17 @@ impl<T: Config> Module<T> { /// Gets extrinsics count. pub fn extrinsic_count() -> u32 { - ExtrinsicCount::get().unwrap_or_default() + ExtrinsicCount::<T>::get().unwrap_or_default() } pub fn all_extrinsics_len() -> u32 { - AllExtrinsicsLen::get().unwrap_or_default() + AllExtrinsicsLen::<T>::get().unwrap_or_default() } - /// Inform the system module of some additional weight that should be accounted for, in the + /// Inform the system pallet of some additional weight that should be accounted for, in the /// current block. /// - /// NOTE: use with extra care; this function is made public only be used for certain modules + /// NOTE: use with extra care; this function is made public only be used for certain pallets /// that need it. A runtime that does not have dynamic calls should never need this and should /// stick to static weights. A typical use case for this is inner calls or smart contract calls. /// Furthermore, it only makes sense to use this when it is presumably _cheap_ to provide the @@ -1121,7 +1177,7 @@ impl<T: Config> Module<T> { /// /// Another potential use-case could be for the `on_initialize` and `on_finalize` hooks. pub fn register_extra_weight_unchecked(weight: Weight, class: DispatchClass) { - BlockWeight::mutate(|current_weight| { + BlockWeight::<T>::mutate(|current_weight| { current_weight.add(weight, class); }); } @@ -1134,7 +1190,7 @@ impl<T: Config> Module<T> { kind: InitKind, ) { // populate environment - ExecutionPhase::put(Phase::Initialization); + ExecutionPhase::<T>::put(Phase::Initialization); storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &0u32); <Number<T>>::put(number); <Digest<T>>::put(digest); @@ -1142,12 +1198,12 @@ impl<T: Config> Module<T> { <BlockHash<T>>::insert(*number - One::one(), parent_hash); // Remove previous block data from storage - BlockWeight::kill(); + BlockWeight::<T>::kill(); // Kill inspectable storage entries in state when `InitKind::Full`. if let InitKind::Full = kind { <Events<T>>::kill(); - EventCount::kill(); + EventCount::<T>::kill(); <EventTopics<T>>::remove_all(); } } @@ -1155,8 +1211,8 @@ impl<T: Config> Module<T> { /// Remove temporary "environment" entries in storage, compute the storage root and return the /// resulting header for this block. pub fn finalize() -> T::Header { - ExecutionPhase::kill(); - AllExtrinsicsLen::kill(); + ExecutionPhase::<T>::kill(); + AllExtrinsicsLen::<T>::kill(); // The following fields // @@ -1172,8 +1228,8 @@ impl<T: Config> Module<T> { let parent_hash = <ParentHash<T>>::get(); let mut digest = <Digest<T>>::get(); - let extrinsics = (0..ExtrinsicCount::take().unwrap_or_default()) - .map(ExtrinsicData::take) + let extrinsics = (0..ExtrinsicCount::<T>::take().unwrap_or_default()) + .map(ExtrinsicData::<T>::take) .collect(); let extrinsics_root = extrinsics_data_root::<T::Hashing>(extrinsics); @@ -1213,7 +1269,7 @@ impl<T: Config> Module<T> { <Digest<T>>::append(item); } - /// Get the basic externalities for this module, useful for tests. + /// Get the basic externalities for this pallet, useful for tests. #[cfg(any(feature = "std", test))] pub fn externalities() -> TestExternalities { TestExternalities::new(sp_core::storage::Storage { @@ -1249,10 +1305,10 @@ impl<T: Config> Module<T> { /// Set the current block weight. This should only be used in some integration tests. #[cfg(any(feature = "std", test))] pub fn set_block_consumed_resources(weight: Weight, len: usize) { - BlockWeight::mutate(|current_weight| { + BlockWeight::<T>::mutate(|current_weight| { current_weight.set(weight, DispatchClass::Normal) }); - AllExtrinsicsLen::put(len as u32); + AllExtrinsicsLen::<T>::put(len as u32); } /// Reset events. Can be used as an alternative to @@ -1260,7 +1316,7 @@ impl<T: Config> Module<T> { #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))] pub fn reset_events() { <Events<T>>::kill(); - EventCount::kill(); + EventCount::<T>::kill(); <EventTopics<T>>::remove_all(); } @@ -1282,7 +1338,7 @@ impl<T: Config> Module<T> { /// This is required to be called before applying an extrinsic. The data will used /// in [`Self::finalize`] to calculate the correct extrinsics root. pub fn note_extrinsic(encoded_xt: Vec<u8>) { - ExtrinsicData::insert(Self::extrinsic_index().unwrap_or_default(), encoded_xt); + ExtrinsicData::<T>::insert(Self::extrinsic_index().unwrap_or_default(), encoded_xt); } /// To be called immediately after an extrinsic has been applied. @@ -1290,10 +1346,10 @@ impl<T: Config> Module<T> { info.weight = extract_actual_weight(r, &info); Self::deposit_event( match r { - Ok(_) => RawEvent::ExtrinsicSuccess(info), + Ok(_) => Event::ExtrinsicSuccess(info), Err(err) => { sp_runtime::print(err); - RawEvent::ExtrinsicFailed(err.error, info) + Event::ExtrinsicFailed(err.error, info) }, } ); @@ -1301,7 +1357,7 @@ impl<T: Config> Module<T> { let next_extrinsic_index = Self::extrinsic_index().unwrap_or_default() + 1u32; storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &next_extrinsic_index); - ExecutionPhase::put(Phase::ApplyExtrinsic(next_extrinsic_index)); + ExecutionPhase::<T>::put(Phase::ApplyExtrinsic(next_extrinsic_index)); } /// To be called immediately after `note_applied_extrinsic` of the last extrinsic of the block @@ -1309,26 +1365,26 @@ impl<T: Config> Module<T> { pub fn note_finished_extrinsics() { let extrinsic_index: u32 = storage::unhashed::take(well_known_keys::EXTRINSIC_INDEX) .unwrap_or_default(); - ExtrinsicCount::put(extrinsic_index); - ExecutionPhase::put(Phase::Finalization); + ExtrinsicCount::<T>::put(extrinsic_index); + ExecutionPhase::<T>::put(Phase::Finalization); } /// To be called immediately after finishing the initialization of the block - /// (e.g., called `on_initialize` for all modules). + /// (e.g., called `on_initialize` for all pallets). pub fn note_finished_initialize() { - ExecutionPhase::put(Phase::ApplyExtrinsic(0)) + ExecutionPhase::<T>::put(Phase::ApplyExtrinsic(0)) } /// An account is being created. pub fn on_created_account(who: T::AccountId, _a: &mut AccountInfo<T::Index, T::AccountData>) { T::OnNewAccount::on_new_account(&who); - Self::deposit_event(RawEvent::NewAccount(who)); + Self::deposit_event(Event::NewAccount(who)); } /// Do anything that needs to be done after an account has been killed. fn on_killed_account(who: T::AccountId) { T::OnKilledAccount::on_killed_account(&who); - Self::deposit_event(RawEvent::KilledAccount(who)); + Self::deposit_event(Event::KilledAccount(who)); } /// Determine whether or not it is possible to update the code. @@ -1385,12 +1441,12 @@ impl<T: Config> HandleLifetime<T::AccountId> for Consumer<T> { } } -impl<T: Config> BlockNumberProvider for Module<T> +impl<T: Config> BlockNumberProvider for Pallet<T> { type BlockNumber = <T as Config>::BlockNumber; fn current_block_number() -> Self::BlockNumber { - Module::<T>::block_number() + Pallet::<T>::block_number() } } @@ -1403,7 +1459,7 @@ fn is_providing<T: Default + Eq>(d: &T) -> bool { /// empty/default. /// /// Anything more complex will need more sophisticated logic. -impl<T: Config> StoredMap<T::AccountId, T::AccountData> for Module<T> { +impl<T: Config> StoredMap<T::AccountId, T::AccountData> for Pallet<T> { fn get(k: &T::AccountId) -> T::AccountData { Account::<T>::get(k).data } diff --git a/substrate/frame/system/src/limits.rs b/substrate/frame/system/src/limits.rs index 3d59bd2b7fa22399b3a4c4ab304917f810e15304..c24d671cdd7abe1028bbf5d0ea8ee01c35905f3d 100644 --- a/substrate/frame/system/src/limits.rs +++ b/substrate/frame/system/src/limits.rs @@ -29,7 +29,7 @@ use frame_support::weights::{Weight, DispatchClass, constants, PerDispatchClass, use sp_runtime::{RuntimeDebug, Perbill}; /// Block length limit configuration. -#[derive(RuntimeDebug, Clone)] +#[derive(RuntimeDebug, Clone, codec::Encode, codec::Decode)] pub struct BlockLength { /// Maximal total length in bytes for each extrinsic class. /// diff --git a/substrate/frame/system/src/offchain.rs b/substrate/frame/system/src/offchain.rs index db417c028675dec812991993bfbaacf7c1c37210..05a5882ee3982364654a7f8491ef9fca81b9795d 100644 --- a/substrate/frame/system/src/offchain.rs +++ b/substrate/frame/system/src/offchain.rs @@ -63,7 +63,7 @@ use sp_std::convert::{TryInto, TryFrom}; use sp_std::prelude::{Box, Vec}; use sp_runtime::app_crypto::RuntimeAppPublic; use sp_runtime::traits::{Extrinsic as ExtrinsicT, IdentifyAccount, One}; -use frame_support::{debug, storage::StorageMap, RuntimeDebug}; +use frame_support::{debug, RuntimeDebug}; /// Marker struct used to flag using all supported keys to sign a payload. pub struct ForAll {} diff --git a/substrate/frame/system/src/tests.rs b/substrate/frame/system/src/tests.rs index 89b84a2cc7ed5cb462220107d94f34a0e998f9be..d1992a14e06aa1c7214d39b7cafc2293a30afb36 100644 --- a/substrate/frame/system/src/tests.rs +++ b/substrate/frame/system/src/tests.rs @@ -18,8 +18,11 @@ use crate::*; use mock::{*, Origin}; use sp_core::H256; -use sp_runtime::{DispatchError, traits::{Header, BlakeTwo256}}; -use frame_support::weights::WithPostDispatchInfo; +use sp_runtime::{DispatchError, DispatchErrorWithPostInfo, traits::{Header, BlakeTwo256}}; +use frame_support::{ + weights::WithPostDispatchInfo, + dispatch::PostDispatchInfo, +}; #[test] fn origin_works() { @@ -329,7 +332,7 @@ fn set_code_checks_works() { ("test", 1, 2, Err(Error::<Test>::SpecVersionNeedsToIncrease)), ("test", 1, 1, Err(Error::<Test>::SpecVersionNeedsToIncrease)), ("test2", 1, 1, Err(Error::<Test>::InvalidSpecName)), - ("test", 2, 1, Ok(())), + ("test", 2, 1, Ok(PostDispatchInfo::default())), ("test", 0, 1, Err(Error::<Test>::SpecVersionNeedsToIncrease)), ("test", 1, 0, Err(Error::<Test>::SpecVersionNeedsToIncrease)), ]; @@ -351,7 +354,7 @@ fn set_code_checks_works() { vec![1, 2, 3, 4], ); - assert_eq!(expected.map_err(DispatchError::from), res); + assert_eq!(expected.map_err(DispatchErrorWithPostInfo::from), res); }); } } diff --git a/substrate/frame/transaction-payment/src/lib.rs b/substrate/frame/transaction-payment/src/lib.rs index c55eb333237cce5f55dfc2882cc9d3d442e02734..7521fcd80bf0a9ebd1b2f280822ff73b32afa5cc 100644 --- a/substrate/frame/transaction-payment/src/lib.rs +++ b/substrate/frame/transaction-payment/src/lib.rs @@ -1169,7 +1169,7 @@ mod tests { })); // Killed Event assert!(System::events().iter().any(|event| { - event.event == Event::system(system::RawEvent::KilledAccount(2)) + event.event == Event::system(system::Event::KilledAccount(2)) })); }); }