diff --git a/substrate/bin/node/executor/tests/basic.rs b/substrate/bin/node/executor/tests/basic.rs index 26c04efe49..f007ba41cc 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 ed354d5534..9d83610b68 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 c628826c62..ff483d9ecd 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 90e8e0d7cb..7a1b57a7b4 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 2cbf467092..762ebe871b 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 965cb7e49a..96bcf99bf8 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 05b4b0f982..df1ae17df6 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::::get(); let current = >::get(); if last.map(|v| v.was_upgraded(¤t)).unwrap_or(true) { - frame_system::LastRuntimeUpgrade::put( + frame_system::LastRuntimeUpgrade::::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::::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::::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::::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::::take(); assert!(Executive::runtime_upgraded()); assert_eq!( Some(LastRuntimeUpgradeInfo { spec_version: 1.into(), spec_name: "test".into() }), - frame_system::LastRuntimeUpgrade::get(), + frame_system::LastRuntimeUpgrade::::get(), ); }) } diff --git a/substrate/frame/session/benchmarking/src/lib.rs b/substrate/frame/session/benchmarking/src/lib.rs index 8f1911c125..06dfa3da34 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 8e5fd36e62..f1951baba5 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 c5d0e5242b..bc48be925b 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 c84c295185..70116f4b65 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 CheckWeight 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::::put(next_len); + crate::BlockWeight::::put(next_weight); Ok(()) } @@ -257,7 +256,7 @@ impl SignedExtension for CheckWeight where let unspent = post_info.calc_unspent(info); if unspent > 0 { - crate::BlockWeight::mutate(|current_weight| { + crate::BlockWeight::::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::::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::::put(normal_length_limit()); assert!(CheckWeight::(PhantomData).pre_dispatch(&1, CALL, &normal, len).is_err()); assert!(CheckWeight::(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::::put(0); let r = CheckWeight::(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::::mutate(|current_weight| { current_weight.set(s, DispatchClass::Normal) }); let r = CheckWeight::(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::::mutate(|current_weight| { current_weight.set(0, DispatchClass::Mandatory); current_weight.set(256 - base_extrinsic, DispatchClass::Normal); }); let pre = CheckWeight::(PhantomData).pre_dispatch(&1, CALL, &info, len).unwrap(); - assert_eq!(BlockWeight::get().total(), info.weight + 256); + assert_eq!(BlockWeight::::get().total(), info.weight + 256); assert!( CheckWeight::::post_dispatch(pre, &info, &post_info, len, &Ok(())) .is_ok() ); assert_eq!( - BlockWeight::get().total(), + BlockWeight::::get().total(), post_info.actual_weight.unwrap() + 256, ); }) @@ -599,14 +598,14 @@ mod tests { }; let len = 0_usize; - BlockWeight::mutate(|current_weight| { + BlockWeight::::mutate(|current_weight| { current_weight.set(0, DispatchClass::Mandatory); current_weight.set(128, DispatchClass::Normal); }); let pre = CheckWeight::(PhantomData).pre_dispatch(&1, CALL, &info, len).unwrap(); assert_eq!( - BlockWeight::get().total(), + BlockWeight::::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::::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 0efa511e99..cdb2662373 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 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 = >::extrinsic_count(); -//! let _parent_hash = >::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,106 +136,529 @@ pub fn extrinsics_data_root(xts: Vec>) -> H::Output { /// An object to track the currently used extrinsic weight in a block. pub type ConsumedWeight = PerDispatchClass; -/// 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; +pub use pallet::*; - /// Block & extrinsics weights: base values and limits. - type BlockWeights: Get; +#[frame_support::pallet] +pub mod pallet { + use crate::{*, pallet_prelude::*, self as frame_system}; + use frame_support::pallet_prelude::*; - /// The maximum length of a block (in bytes). - type BlockLength: Get; + /// 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; - /// The `Origin` type used by dispatchable calls. - type Origin: - Into, Self::Origin>> - + From> - + Clone - + OriginTrait; + /// Block & extrinsics weights: base values and limits. + #[pallet::constant] + type BlockWeights: Get; - /// The aggregated `Call` type. - type Call: Dispatchable + Debug; + /// The maximum length of a block (in bytes). + #[pallet::constant] + type BlockLength: Get; - /// 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 `Origin` type used by dispatchable calls. + type Origin: + Into, Self::Origin>> + + From> + + Clone + + OriginTrait; - /// 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 aggregated `Call` type. + type Call: Dispatchable + Debug; - /// 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; + /// 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 hashing system (algorithm) being used in the runtime (e.g. Blake2). - type Hashing: Hash; + /// 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 user account identifier type for the runtime. - type AccountId: Parameter + Member + MaybeSerializeDeserialize + Debug + MaybeDisplay + Ord - + Default; + /// 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; - /// 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; + /// The hashing system (algorithm) being used in the runtime (e.g. Blake2). + type Hashing: Hash; - /// The block header. - type Header: Parameter + traits::Header< - Number = Self::BlockNumber, - Hash = 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; + + /// 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> + Debug + IsType<::Event>; + + /// Maximum number of block number to block hash mappings to keep (oldest pruned first). + #[pallet::constant] + type BlockHashCount: Get; + + /// The weight of runtime database operations the runtime can invoke. + #[pallet::constant] + type DbWeight: Get; + + /// Get the chain's current version. + #[pallet::constant] + type Version: Get; + + /// 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 + /// pallet does regardless). + type AccountData: Member + FullCodec + Clone + Default; + + /// Handler for when a new account has just been created. + type OnNewAccount: OnNewAccount; + + /// 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; + + 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. + #[pallet::constant] + type SS58Prefix: Get; + } + + #[pallet::pallet] + #[pallet::generate_store(pub (super) trait Store)] + pub struct Pallet(PhantomData); + + #[pallet::hooks] + impl Hooks> for Pallet { + fn on_runtime_upgrade() -> frame_support::weights::Weight { + if !UpgradedToDualRefCount::::get() { + UpgradedToDualRefCount::::put(true); + migrations::migrate_to_dual_ref_count::() + } else { + 0 + } + } + + fn integrity_test() { + T::BlockWeights::get() + .validate() + .expect("The weights are invalid."); + } + } + + #[pallet::call] + impl Pallet { + /// 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 pallet macro). + #[pallet::weight(*_ratio * T::BlockWeights::get().max_block)] + pub(crate) fn fill_block(origin: OriginFor, _ratio: Perbill) -> DispatchResultWithPostInfo { + ensure_root(origin)?; + Ok(().into()) + } + + /// Make some on-chain remark. + /// + /// # + /// - `O(1)` + /// - Base Weight: 0.665 µs, independent of remark length. + /// - No DB operations. + /// # + #[pallet::weight(T::SystemWeightInfo::remark(_remark.len() as u32))] + pub(crate) fn remark(origin: OriginFor, _remark: Vec) -> DispatchResultWithPostInfo { + ensure_signed(origin)?; + Ok(().into()) + } + + /// Set the number of pages in the WebAssembly environment's heap. + /// + /// # + /// - `O(1)` + /// - 1 storage write. + /// - Base Weight: 1.405 µs + /// - 1 write to HEAP_PAGES + /// # + #[pallet::weight((T::SystemWeightInfo::set_heap_pages(), DispatchClass::Operational))] + pub(crate) fn set_heap_pages(origin: OriginFor, pages: u64) -> DispatchResultWithPostInfo { + ensure_root(origin)?; + storage::unhashed::put_raw(well_known_keys::HEAP_PAGES, &pages.encode()); + Ok(().into()) + } + + /// Set the new runtime code. + /// + /// # + /// - `O(C + S)` where `C` length of `code` and `S` complexity of `can_set_code` + /// - 1 storage write (codec `O(C)`). + /// - 1 call to `can_set_code`: `O(S)` (calls `sp_io::misc::runtime_version` which is expensive). + /// - 1 event. + /// The weight of this function is dependent on the runtime, but generally this is very expensive. + /// We will treat this as a full block. + /// # + #[pallet::weight((T::BlockWeights::get().max_block, DispatchClass::Operational))] + pub fn set_code(origin: OriginFor, code: Vec) -> DispatchResultWithPostInfo { + ensure_root(origin)?; + Self::can_set_code(&code)?; + + storage::unhashed::put_raw(well_known_keys::CODE, &code); + Self::deposit_event(Event::CodeUpdated); + Ok(().into()) + } + + /// Set the new runtime code without doing any checks of the given `code`. + /// + /// # + /// - `O(C)` where `C` length of `code` + /// - 1 storage write (codec `O(C)`). + /// - 1 event. + /// The weight of this function is dependent on the runtime. We will treat this as a full block. + /// # + #[pallet::weight((T::BlockWeights::get().max_block, DispatchClass::Operational))] + pub fn set_code_without_checks( + origin: OriginFor, + code: Vec, + ) -> DispatchResultWithPostInfo { + ensure_root(origin)?; + storage::unhashed::put_raw(well_known_keys::CODE, &code); + Self::deposit_event(Event::CodeUpdated); + Ok(().into()) + } + + /// Set the new changes trie configuration. + /// + /// # + /// - `O(1)` + /// - 1 storage write or delete (codec `O(1)`). + /// - 1 call to `deposit_log`: Uses `append` API, so O(1) + /// - Base Weight: 7.218 µs + /// - DB Weight: + /// - Writes: Changes Trie, System Digest + /// # + #[pallet::weight((T::SystemWeightInfo::set_changes_trie_config(), DispatchClass::Operational))] + pub fn set_changes_trie_config( + origin: OriginFor, + changes_trie_config: Option, + ) -> DispatchResultWithPostInfo { + ensure_root(origin)?; + match changes_trie_config.clone() { + Some(changes_trie_config) => storage::unhashed::put_raw( + well_known_keys::CHANGES_TRIE_CONFIG, + &changes_trie_config.encode(), + ), + None => storage::unhashed::kill(well_known_keys::CHANGES_TRIE_CONFIG), + } + + let log = generic::DigestItem::ChangesTrieSignal( + generic::ChangesTrieSignal::NewConfiguration(changes_trie_config), + ); + Self::deposit_log(log.into()); + Ok(().into()) + } + + /// Set some items of storage. + /// + /// # + /// - `O(I)` where `I` length of `items` + /// - `I` storage writes (`O(1)`). + /// - Base Weight: 0.568 * i µs + /// - Writes: Number of items + /// # + #[pallet::weight(( + T::SystemWeightInfo::set_storage(items.len() as u32), + DispatchClass::Operational, + ))] + pub(crate) fn set_storage(origin: OriginFor, items: Vec) -> DispatchResultWithPostInfo { + ensure_root(origin)?; + for i in &items { + storage::unhashed::put_raw(&i.0, &i.1); + } + Ok(().into()) + } + + /// Kill some items from storage. + /// + /// # + /// - `O(IK)` where `I` length of `keys` and `K` length of one key + /// - `I` storage deletions. + /// - Base Weight: .378 * i µs + /// - Writes: Number of items + /// # + #[pallet::weight(( + T::SystemWeightInfo::kill_storage(keys.len() as u32), + DispatchClass::Operational, + ))] + pub(crate) fn kill_storage(origin: OriginFor, keys: Vec) -> 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. + /// + /// **NOTE:** We rely on the Root origin to provide us the number of subkeys under + /// the prefix we are removing to accurately calculate the weight of this function. + /// + /// # + /// - `O(P)` where `P` amount of keys with prefix `prefix` + /// - `P` storage deletions. + /// - Base Weight: 0.834 * P µs + /// - Writes: Number of subkeys + 1 + /// # + #[pallet::weight(( + T::SystemWeightInfo::kill_prefix(_subkeys.saturating_add(1)), + DispatchClass::Operational, + ))] + pub(crate) fn kill_prefix( + origin: OriginFor, + 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 { + /// 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 = Event; + + /// Error for the System pallet + #[pallet::error] + pub enum Error { + /// 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 = RawOrigin<::AccountId>; + + /// The full account information for a particular account ID. + #[pallet::storage] + #[pallet::getter(fn account)] + pub type Account = StorageMap< + _, + Blake2_128Concat, + T::AccountId, + AccountInfo, + ValueQuery, >; - /// The aggregated event type of the runtime. - type Event: Parameter + Member + From> + Debug; + /// Total extrinsics count for the current block. + #[pallet::storage] + pub(super) type ExtrinsicCount = StorageValue<_, u32>; - /// Maximum number of block number to block hash mappings to keep (oldest pruned first). - type BlockHashCount: Get; + /// The current weight for the block. + #[pallet::storage] + #[pallet::getter(fn block_weight)] + pub(super) type BlockWeight = StorageValue<_, ConsumedWeight, ValueQuery>; - /// The weight of runtime database operations the runtime can invoke. - type DbWeight: Get; + /// Total length (in bytes) for all extrinsics put together, for the current block. + #[pallet::storage] + pub(super) type AllExtrinsicsLen = StorageValue<_, u32>; - /// Get the chain's current version. - type Version: Get; + /// Map of block numbers to block hashes. + #[pallet::storage] + #[pallet::getter(fn block_hash)] + pub type BlockHash = + StorageMap<_, Twox64Concat, T::BlockNumber, T::Hash, ValueQuery>; - /// Provides information about the pallet setup in the runtime. + /// 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 = + StorageMap<_, Twox64Concat, u32, Vec, ValueQuery>; + + /// The current block number being processed. Set by `execute_block`. + #[pallet::storage] + #[pallet::getter(fn block_number)] + pub(super) type Number = StorageValue<_, T::BlockNumber, ValueQuery>; + + /// Hash of the previous block. + #[pallet::storage] + #[pallet::getter(fn parent_hash)] + pub(super) type ParentHash = 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 = StorageValue<_, DigestOf, ValueQuery>; + + /// Events deposited for the current block. + #[pallet::storage] + #[pallet::getter(fn events)] + pub(super) type Events = + StorageValue<_, Vec>, ValueQuery>; + + /// The number of events in the `Events` list. + #[pallet::storage] + #[pallet::getter(fn event_count)] + pub(super) type EventCount = StorageValue<_, EventIndex, ValueQuery>; + + /// Mapping between a topic (represented by T::Hash) and a vector of indexes + /// of events in the `>` list. /// - /// Expects the `PalletInfo` type that is being generated by `construct_runtime!` 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. /// - /// For tests it is okay to use `()` as type, however it will provide "useless" data. - type PalletInfo: PalletInfo; + /// 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 = + StorageMap<_, Blake2_128Concat, T::Hash, Vec<(T::BlockNumber, EventIndex)>, ValueQuery>; - /// Data to be associated with an account (other than nonce/transaction counter, which this - /// module does regardless). - type AccountData: Member + FullCodec + Clone + Default; + /// Stores the `spec_version` and `spec_name` of when the last runtime upgrade happened. + #[pallet::storage] + pub type LastRuntimeUpgrade = StorageValue<_, LastRuntimeUpgradeInfo>; - /// Handler for when a new account has just been created. - type OnNewAccount: OnNewAccount; + /// True if we have upgraded so that `type RefCount` is `u32`. False (default) if not. + #[pallet::storage] + pub(super) type UpgradedToU32RefCount = StorageValue<_, bool, ValueQuery>; - /// A function that is invoked when an account has been determined to be dead. + /// True if we have upgraded so that AccountInfo contains two types of `RefCount`. False + /// (default) if not. + #[pallet::storage] + pub(super) type UpgradedToDualRefCount = StorageValue<_, bool, ValueQuery>; + + /// The execution phase of the block. + #[pallet::storage] + pub(super) type ExecutionPhase = StorageValue<_, Phase>; + + #[pallet::genesis_config] + pub struct GenesisConfig { + pub changes_trie_config: Option, + #[serde(with = "sp_core::bytes")] + pub code: Vec, + } + + #[cfg(feature = "std")] + impl Default for GenesisConfig { + fn default() -> Self { + Self { + changes_trie_config: Default::default(), + code: Default::default(), + } + } + } + + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) { + >::insert::<_, T::Hash>(T::BlockNumber::zero(), hash69()); + >::put::(hash69()); + >::put(LastRuntimeUpgradeInfo::from(T::Version::get())); + >::put(true); + >::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() -> frame_support::weights::Weight { + Account::::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() -> frame_support::weights::Weight { + Account::::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`. /// - /// All resources should be cleaned up associated with the given account. - type OnKilledAccount: OnKilledAccount; + /// Kept in order not to break dependency. + pub fn build_storage(&self) -> Result { + >::build_storage(self) + } - type SystemWeightInfo: WeightInfo; - - /// The designated SS85 prefix of this chain. + /// Direct implementation of `GenesisBuild::assimilate_storage`. /// - /// 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; + /// Kept in order not to break dependency. + pub fn assimilate_storage( + &self, + storage: &mut sp_runtime::Storage + ) -> Result<(), String> { + >::assimilate_storage(self, storage) + } } pub type DigestOf = generic::Digest<::Hash>; @@ -300,7 +697,7 @@ pub struct EventRecord { pub topics: Vec, } -/// Origin for the System module. +/// Origin for the System pallet. #[derive(PartialEq, Eq, Clone, RuntimeDebug, Encode, Decode)] pub enum RawOrigin { /// The system itself ordained this dispatch to happen: this is the highest privilege level. @@ -309,7 +706,7 @@ pub enum RawOrigin { 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. + /// * or unsigned transaction validated by a pallet. None, } @@ -322,9 +719,6 @@ impl From> for RawOrigin { } } -/// Exposed trait-generic origin type. -pub type Origin = RawOrigin<::AccountId>; - // Create a Hash with 69 for each byte, // only used to build genesis config. #[cfg(feature = "std")] @@ -386,344 +780,6 @@ impl From for LastRuntimeUpgradeInfo { } } -decl_storage! { - trait Store for Module as System { - /// The full account information for a particular account ID. - pub Account get(fn account): - map hasher(blake2_128_concat) T::AccountId => AccountInfo; - - /// Total extrinsics count for the current block. - ExtrinsicCount: Option; - - /// 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; - - /// 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; - - /// The current block number being processed. Set by `execute_block`. - Number get(fn block_number): T::BlockNumber; - - /// Hash of the previous block. - ParentHash get(fn parent_hash) build(|_| hash69()): T::Hash; - - /// Digest of the current block, also part of the block header. - Digest get(fn digest): DigestOf; - - /// Events deposited for the current block. - Events get(fn events): Vec>; - - /// The number of events in the `Events` list. - EventCount get(fn event_count): EventIndex; - - // TODO: https://github.com/paritytech/substrate/issues/2553 - // Possibly, we can improve it by using something like: - // `Option<(BlockNumber, Vec)>`, however in this case we won't be able to use - // `EventTopics::append`. - - /// Mapping between a topic (represented by T::Hash) and a vector of indexes - /// of events in the `>` 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. - 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; - - /// True if we have upgraded so that `type RefCount` is `u32`. False (default) if not. - UpgradedToU32RefCount build(|_| true): bool; - - /// True if we have upgraded so that AccountInfo contains two types of `RefCount`. False - /// (default) if not. - UpgradedToDualRefCount build(|_| true): bool; - - /// The execution phase of the block. - ExecutionPhase: Option; - } - add_extra_genesis { - config(changes_trie_config): Option; - #[serde(with = "sp_core::bytes")] - config(code): Vec; - - 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 where AccountId = ::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 { - /// 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, - } -} - -mod migrations { - use super::*; - - #[allow(dead_code)] - pub fn migrate_all() -> frame_support::weights::Weight { - Account::::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() -> frame_support::weights::Weight { - Account::::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 - } -} - -/// 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 = Module; - -decl_module! { - pub struct Module for enum Call where origin: T::Origin, system=self { - type Error = Error; - - /// 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(); - - /// 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(); - - fn on_runtime_upgrade() -> frame_support::weights::Weight { - if !UpgradedToDualRefCount::get() { - UpgradedToDualRefCount::put(true); - migrations::migrate_to_dual_ref_count::() - } else { - 0 - } - } - - fn integrity_test() { - T::BlockWeights::get() - .validate() - .expect("The weights are invalid."); - } - - /// 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) { - ensure_root(origin)?; - } - - /// Make some on-chain remark. - /// - /// # - /// - `O(1)` - /// - Base Weight: 0.665 µs, independent of remark length. - /// - No DB operations. - /// # - #[weight = T::SystemWeightInfo::remark(_remark.len() as u32)] - fn remark(origin, _remark: Vec) { - ensure_signed(origin)?; - } - - /// Set the number of pages in the WebAssembly environment's heap. - /// - /// # - /// - `O(1)` - /// - 1 storage write. - /// - Base Weight: 1.405 µs - /// - 1 write to HEAP_PAGES - /// # - #[weight = (T::SystemWeightInfo::set_heap_pages(), DispatchClass::Operational)] - fn set_heap_pages(origin, pages: u64) { - ensure_root(origin)?; - storage::unhashed::put_raw(well_known_keys::HEAP_PAGES, &pages.encode()); - } - - /// Set the new runtime code. - /// - /// # - /// - `O(C + S)` where `C` length of `code` and `S` complexity of `can_set_code` - /// - 1 storage write (codec `O(C)`). - /// - 1 call to `can_set_code`: `O(S)` (calls `sp_io::misc::runtime_version` which is expensive). - /// - 1 event. - /// 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 = (T::BlockWeights::get().max_block, DispatchClass::Operational)] - pub fn set_code(origin, code: Vec) { - ensure_root(origin)?; - Self::can_set_code(&code)?; - - storage::unhashed::put_raw(well_known_keys::CODE, &code); - Self::deposit_event(RawEvent::CodeUpdated); - } - - /// Set the new runtime code without doing any checks of the given `code`. - /// - /// # - /// - `O(C)` where `C` length of `code` - /// - 1 storage write (codec `O(C)`). - /// - 1 event. - /// The weight of this function is dependent on the runtime. We will treat this as a full block. - /// # - #[weight = (T::BlockWeights::get().max_block, DispatchClass::Operational)] - pub fn set_code_without_checks(origin, code: Vec) { - ensure_root(origin)?; - storage::unhashed::put_raw(well_known_keys::CODE, &code); - Self::deposit_event(RawEvent::CodeUpdated); - } - - /// Set the new changes trie configuration. - /// - /// # - /// - `O(1)` - /// - 1 storage write or delete (codec `O(1)`). - /// - 1 call to `deposit_log`: Uses `append` API, so O(1) - /// - Base Weight: 7.218 µs - /// - DB Weight: - /// - Writes: Changes Trie, System Digest - /// # - #[weight = (T::SystemWeightInfo::set_changes_trie_config(), DispatchClass::Operational)] - pub fn set_changes_trie_config(origin, changes_trie_config: Option) { - ensure_root(origin)?; - match changes_trie_config.clone() { - Some(changes_trie_config) => storage::unhashed::put_raw( - well_known_keys::CHANGES_TRIE_CONFIG, - &changes_trie_config.encode(), - ), - None => storage::unhashed::kill(well_known_keys::CHANGES_TRIE_CONFIG), - } - - let log = generic::DigestItem::ChangesTrieSignal( - generic::ChangesTrieSignal::NewConfiguration(changes_trie_config), - ); - Self::deposit_log(log.into()); - } - - /// Set some items of storage. - /// - /// # - /// - `O(I)` where `I` length of `items` - /// - `I` storage writes (`O(1)`). - /// - Base Weight: 0.568 * i µs - /// - Writes: Number of items - /// # - #[weight = ( - T::SystemWeightInfo::set_storage(items.len() as u32), - DispatchClass::Operational, - )] - fn set_storage(origin, items: Vec) { - ensure_root(origin)?; - for i in &items { - storage::unhashed::put_raw(&i.0, &i.1); - } - } - - /// Kill some items from storage. - /// - /// # - /// - `O(IK)` where `I` length of `keys` and `K` length of one key - /// - `I` storage deletions. - /// - Base Weight: .378 * i µs - /// - Writes: Number of items - /// # - #[weight = ( - T::SystemWeightInfo::kill_storage(keys.len() as u32), - DispatchClass::Operational, - )] - fn kill_storage(origin, keys: Vec) { - ensure_root(origin)?; - for key in &keys { - storage::unhashed::kill(&key); - } - } - - /// Kill all storage items with a key that starts with the given prefix. - /// - /// **NOTE:** We rely on the Root origin to provide us the number of subkeys under - /// the prefix we are removing to accurately calculate the weight of this function. - /// - /// # - /// - `O(P)` where `P` amount of keys with prefix `prefix` - /// - `P` storage deletions. - /// - Base Weight: 0.834 * P µs - /// - Writes: Number of subkeys + 1 - /// # - #[weight = ( - T::SystemWeightInfo::kill_prefix(_subkeys.saturating_add(1)), - DispatchClass::Operational, - )] - fn kill_prefix(origin, prefix: Key, _subkeys: u32) { - ensure_root(origin)?; - storage::unhashed::kill_prefix(&prefix); - } - } -} - pub struct EnsureRoot(sp_std::marker::PhantomData); impl< O: Into, O>> + From>, @@ -1064,7 +1120,7 @@ impl Module { // Don't populate events on genesis. if block_number.is_zero() { return } - let phase = ExecutionPhase::get().unwrap_or_default(); + let phase = ExecutionPhase::::get().unwrap_or_default(); let event = EventRecord { phase, event, @@ -1073,14 +1129,14 @@ impl Module { // Index of the to be added event. let event_idx = { - let old_event_count = EventCount::get(); + let old_event_count = EventCount::::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::::put(new_event_count); old_event_count }; @@ -1098,17 +1154,17 @@ impl Module { /// Gets extrinsics count. pub fn extrinsic_count() -> u32 { - ExtrinsicCount::get().unwrap_or_default() + ExtrinsicCount::::get().unwrap_or_default() } pub fn all_extrinsics_len() -> u32 { - AllExtrinsicsLen::get().unwrap_or_default() + AllExtrinsicsLen::::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 Module { /// /// 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::::mutate(|current_weight| { current_weight.add(weight, class); }); } @@ -1134,7 +1190,7 @@ impl Module { kind: InitKind, ) { // populate environment - ExecutionPhase::put(Phase::Initialization); + ExecutionPhase::::put(Phase::Initialization); storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &0u32); >::put(number); >::put(digest); @@ -1142,12 +1198,12 @@ impl Module { >::insert(*number - One::one(), parent_hash); // Remove previous block data from storage - BlockWeight::kill(); + BlockWeight::::kill(); // Kill inspectable storage entries in state when `InitKind::Full`. if let InitKind::Full = kind { >::kill(); - EventCount::kill(); + EventCount::::kill(); >::remove_all(); } } @@ -1155,8 +1211,8 @@ impl Module { /// 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::::kill(); + AllExtrinsicsLen::::kill(); // The following fields // @@ -1172,8 +1228,8 @@ impl Module { let parent_hash = >::get(); let mut digest = >::get(); - let extrinsics = (0..ExtrinsicCount::take().unwrap_or_default()) - .map(ExtrinsicData::take) + let extrinsics = (0..ExtrinsicCount::::take().unwrap_or_default()) + .map(ExtrinsicData::::take) .collect(); let extrinsics_root = extrinsics_data_root::(extrinsics); @@ -1213,7 +1269,7 @@ impl Module { >::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 Module { /// 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::::mutate(|current_weight| { current_weight.set(weight, DispatchClass::Normal) }); - AllExtrinsicsLen::put(len as u32); + AllExtrinsicsLen::::put(len as u32); } /// Reset events. Can be used as an alternative to @@ -1260,7 +1316,7 @@ impl Module { #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))] pub fn reset_events() { >::kill(); - EventCount::kill(); + EventCount::::kill(); >::remove_all(); } @@ -1282,7 +1338,7 @@ impl Module { /// 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) { - ExtrinsicData::insert(Self::extrinsic_index().unwrap_or_default(), encoded_xt); + ExtrinsicData::::insert(Self::extrinsic_index().unwrap_or_default(), encoded_xt); } /// To be called immediately after an extrinsic has been applied. @@ -1290,10 +1346,10 @@ impl Module { 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 Module { 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::::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 Module { 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::::put(extrinsic_index); + ExecutionPhase::::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::::put(Phase::ApplyExtrinsic(0)) } /// An account is being created. pub fn on_created_account(who: T::AccountId, _a: &mut AccountInfo) { 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 HandleLifetime for Consumer { } } -impl BlockNumberProvider for Module +impl BlockNumberProvider for Pallet { type BlockNumber = ::BlockNumber; fn current_block_number() -> Self::BlockNumber { - Module::::block_number() + Pallet::::block_number() } } @@ -1403,7 +1459,7 @@ fn is_providing(d: &T) -> bool { /// empty/default. /// /// Anything more complex will need more sophisticated logic. -impl StoredMap for Module { +impl StoredMap for Pallet { fn get(k: &T::AccountId) -> T::AccountData { Account::::get(k).data } diff --git a/substrate/frame/system/src/limits.rs b/substrate/frame/system/src/limits.rs index 3d59bd2b7f..c24d671cdd 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 db417c0286..05a5882ee3 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 89b84a2cc7..d1992a14e0 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::::SpecVersionNeedsToIncrease)), ("test", 1, 1, Err(Error::::SpecVersionNeedsToIncrease)), ("test2", 1, 1, Err(Error::::InvalidSpecName)), - ("test", 2, 1, Ok(())), + ("test", 2, 1, Ok(PostDispatchInfo::default())), ("test", 0, 1, Err(Error::::SpecVersionNeedsToIncrease)), ("test", 1, 0, Err(Error::::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 c55eb33323..7521fcd80b 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)) })); }); }