frame_system/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! # System Pallet
19//!
20//! The System pallet provides low-level access to core types and cross-cutting utilities. It acts
21//! as the base layer for other pallets to interact with the Substrate framework components.
22//!
23//! - [`Config`]
24//!
25//! ## Overview
26//!
27//! The System pallet defines the core data types used in a Substrate runtime. It also provides
28//! several utility functions (see [`Pallet`]) for other FRAME pallets.
29//!
30//! In addition, it manages the storage items for extrinsic data, indices, event records, and digest
31//! items, among other things that support the execution of the current block.
32//!
33//! It also handles low-level tasks like depositing logs, basic set up and take down of temporary
34//! storage entries, and access to previous block hashes.
35//!
36//! ## Interface
37//!
38//! ### Dispatchable Functions
39//!
40//! The System pallet provides dispatchable functions that, with the exception of `remark`, manage
41//! low-level or privileged functionality of a Substrate-based runtime.
42//!
43//! - `remark`: Make some on-chain remark.
44//! - `set_heap_pages`: Set the number of pages in the WebAssembly environment's heap.
45//! - `set_code`: Set the new runtime code.
46//! - `set_code_without_checks`: Set the new runtime code without any checks.
47//! - `set_storage`: Set some items of storage.
48//! - `kill_storage`: Kill some items from storage.
49//! - `kill_prefix`: Kill all storage items with a key that starts with the given prefix.
50//! - `remark_with_event`: Make some on-chain remark and emit an event.
51//! - `do_task`: Do some specified task.
52//! - `authorize_upgrade`: Authorize new runtime code.
53//! - `authorize_upgrade_without_checks`: Authorize new runtime code and an upgrade sans
54//!   verification.
55//! - `apply_authorized_upgrade`: Provide new, already-authorized runtime code.
56//!
57//! #### A Note on Upgrades
58//!
59//! The pallet provides two primary means of upgrading the runtime, a single-phase means using
60//! `set_code` and a two-phase means using `authorize_upgrade` followed by
61//! `apply_authorized_upgrade`. The first will directly attempt to apply the provided `code`
62//! (application may have to be scheduled, depending on the context and implementation of the
63//! `OnSetCode` trait).
64//!
65//! The `authorize_upgrade` route allows the authorization of a runtime's code hash. Once
66//! authorized, anyone may upload the correct runtime to apply the code. This pattern is useful when
67//! providing the runtime ahead of time may be unwieldy, for example when a large preimage (the
68//! code) would need to be stored on-chain or sent over a message transport protocol such as a
69//! bridge.
70//!
71//! The `*_without_checks` variants do not perform any version checks, so using them runs the risk
72//! of applying a downgrade or entirely other chain specification. They will still validate that the
73//! `code` meets the authorized hash.
74//!
75//! ### Public Functions
76//!
77//! See the [`Pallet`] struct for details of publicly available functions.
78//!
79//! ### Signed Extensions
80//!
81//! The System pallet defines the following extensions:
82//!
83//!   - [`CheckWeight`]: Checks the weight and length of the block and ensure that it does not
84//!     exceed the limits.
85//!   - [`CheckNonce`]: Checks the nonce of the transaction. Contains a single payload of type
86//!     `T::Nonce`.
87//!   - [`CheckEra`]: Checks the era of the transaction. Contains a single payload of type `Era`.
88//!   - [`CheckGenesis`]: Checks the provided genesis hash of the transaction. Must be a part of the
89//!     signed payload of the transaction.
90//!   - [`CheckSpecVersion`]: Checks that the runtime version is the same as the one used to sign
91//!     the transaction.
92//!   - [`CheckTxVersion`]: Checks that the transaction version is the same as the one used to sign
93//!     the transaction.
94//!
95//! Look up the runtime aggregator file (e.g. `node/runtime`) to see the full list of signed
96//! extensions included in a chain.
97
98#![cfg_attr(not(feature = "std"), no_std)]
99
100extern crate alloc;
101
102use alloc::{boxed::Box, vec, vec::Vec};
103use core::{fmt::Debug, marker::PhantomData};
104use pallet_prelude::{BlockNumberFor, HeaderFor};
105#[cfg(feature = "std")]
106use serde::Serialize;
107use sp_io::hashing::blake2_256;
108#[cfg(feature = "runtime-benchmarks")]
109use sp_runtime::traits::TrailingZeroInput;
110use sp_runtime::{
111	generic,
112	traits::{
113		self, AtLeast32Bit, BadOrigin, BlockNumberProvider, Bounded, CheckEqual, Dispatchable,
114		Hash, Header, Lookup, LookupError, MaybeDisplay, MaybeSerializeDeserialize, Member, One,
115		Saturating, SimpleBitOps, StaticLookup, Zero,
116	},
117	transaction_validity::{
118		InvalidTransaction, TransactionLongevity, TransactionSource, TransactionValidity,
119		ValidTransaction,
120	},
121	DispatchError, RuntimeDebug,
122};
123#[cfg(any(feature = "std", test))]
124use sp_std::map;
125use sp_version::RuntimeVersion;
126
127use codec::{Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen};
128#[cfg(feature = "std")]
129use frame_support::traits::BuildGenesisConfig;
130use frame_support::{
131	dispatch::{
132		extract_actual_pays_fee, extract_actual_weight, DispatchClass, DispatchInfo,
133		DispatchResult, DispatchResultWithPostInfo, PerDispatchClass, PostDispatchInfo,
134	},
135	ensure, impl_ensure_origin_with_arg_ignoring_arg,
136	migrations::MultiStepMigrator,
137	pallet_prelude::Pays,
138	storage::{self, StorageStreamIter},
139	traits::{
140		ConstU32, Contains, EnsureOrigin, EnsureOriginWithArg, Get, HandleLifetime,
141		OnKilledAccount, OnNewAccount, OnRuntimeUpgrade, OriginTrait, PalletInfo, SortedMembers,
142		StoredMap, TypedGet,
143	},
144	Parameter,
145};
146use scale_info::TypeInfo;
147use sp_core::storage::well_known_keys;
148use sp_weights::{RuntimeDbWeight, Weight};
149
150#[cfg(any(feature = "std", test))]
151use sp_io::TestExternalities;
152
153pub mod limits;
154#[cfg(test)]
155pub(crate) mod mock;
156
157pub mod offchain;
158
159mod extensions;
160#[cfg(feature = "std")]
161pub mod mocking;
162#[cfg(test)]
163mod tests;
164pub mod weights;
165
166pub mod migrations;
167
168pub use extensions::{
169	check_genesis::CheckGenesis, check_mortality::CheckMortality,
170	check_non_zero_sender::CheckNonZeroSender, check_nonce::CheckNonce,
171	check_spec_version::CheckSpecVersion, check_tx_version::CheckTxVersion,
172	check_weight::CheckWeight,
173};
174// Backward compatible re-export.
175pub use extensions::check_mortality::CheckMortality as CheckEra;
176pub use frame_support::dispatch::RawOrigin;
177use frame_support::traits::{PostInherents, PostTransactions, PreInherents};
178use sp_core::storage::StateVersion;
179pub use weights::WeightInfo;
180
181const LOG_TARGET: &str = "runtime::system";
182
183/// Compute the trie root of a list of extrinsics.
184///
185/// The merkle proof is using the same trie as runtime state with
186/// `state_version` 0 or 1.
187pub fn extrinsics_root<H: Hash, E: codec::Encode>(
188	extrinsics: &[E],
189	state_version: StateVersion,
190) -> H::Output {
191	extrinsics_data_root::<H>(extrinsics.iter().map(codec::Encode::encode).collect(), state_version)
192}
193
194/// Compute the trie root of a list of extrinsics.
195///
196/// The merkle proof is using the same trie as runtime state with
197/// `state_version` 0 or 1.
198pub fn extrinsics_data_root<H: Hash>(xts: Vec<Vec<u8>>, state_version: StateVersion) -> H::Output {
199	H::ordered_trie_root(xts, state_version)
200}
201
202/// An object to track the currently used extrinsic weight in a block.
203pub type ConsumedWeight = PerDispatchClass<Weight>;
204
205pub use pallet::*;
206
207/// Do something when we should be setting the code.
208pub trait SetCode<T: Config> {
209	/// Set the code to the given blob.
210	fn set_code(code: Vec<u8>) -> DispatchResult;
211}
212
213impl<T: Config> SetCode<T> for () {
214	fn set_code(code: Vec<u8>) -> DispatchResult {
215		<Pallet<T>>::update_code_in_storage(&code);
216		Ok(())
217	}
218}
219
220/// Numeric limits over the ability to add a consumer ref using `inc_consumers`.
221pub trait ConsumerLimits {
222	/// The number of consumers over which `inc_consumers` will cease to work.
223	fn max_consumers() -> RefCount;
224	/// The maximum number of additional consumers expected to be over be added at once using
225	/// `inc_consumers_without_limit`.
226	///
227	/// Note: This is not enforced and it's up to the chain's author to ensure this reflects the
228	/// actual situation.
229	fn max_overflow() -> RefCount;
230}
231
232impl<const Z: u32> ConsumerLimits for ConstU32<Z> {
233	fn max_consumers() -> RefCount {
234		Z
235	}
236	fn max_overflow() -> RefCount {
237		Z
238	}
239}
240
241impl<MaxNormal: Get<u32>, MaxOverflow: Get<u32>> ConsumerLimits for (MaxNormal, MaxOverflow) {
242	fn max_consumers() -> RefCount {
243		MaxNormal::get()
244	}
245	fn max_overflow() -> RefCount {
246		MaxOverflow::get()
247	}
248}
249
250/// Information needed when a new runtime binary is submitted and needs to be authorized before
251/// replacing the current runtime.
252#[derive(Decode, Encode, Default, PartialEq, Eq, MaxEncodedLen, TypeInfo)]
253#[scale_info(skip_type_params(T))]
254pub struct CodeUpgradeAuthorization<T>
255where
256	T: Config,
257{
258	/// Hash of the new runtime binary.
259	code_hash: T::Hash,
260	/// Whether or not to carry out version checks.
261	check_version: bool,
262}
263
264#[frame_support::pallet]
265pub mod pallet {
266	use crate::{self as frame_system, pallet_prelude::*, *};
267	use frame_support::pallet_prelude::*;
268
269	/// Default implementations of [`DefaultConfig`], which can be used to implement [`Config`].
270	pub mod config_preludes {
271		use super::{inject_runtime_type, DefaultConfig};
272		use frame_support::{derive_impl, traits::Get};
273
274		/// A predefined adapter that covers `BlockNumberFor<T>` for `Config::Block::BlockNumber` of
275		/// the types `u32`, `u64`, and `u128`.
276		///
277		/// NOTE: Avoids overriding `BlockHashCount` when using `mocking::{MockBlock, MockBlockU32,
278		/// MockBlockU128}`.
279		pub struct TestBlockHashCount<C: Get<u32>>(core::marker::PhantomData<C>);
280		impl<I: From<u32>, C: Get<u32>> Get<I> for TestBlockHashCount<C> {
281			fn get() -> I {
282				C::get().into()
283			}
284		}
285
286		/// Provides a viable default config that can be used with
287		/// [`derive_impl`](`frame_support::derive_impl`) to derive a testing pallet config
288		/// based on this one.
289		///
290		/// See `Test` in the `default-config` example pallet's `test.rs` for an example of
291		/// a downstream user of this particular `TestDefaultConfig`
292		pub struct TestDefaultConfig;
293
294		#[frame_support::register_default_impl(TestDefaultConfig)]
295		impl DefaultConfig for TestDefaultConfig {
296			type Nonce = u32;
297			type Hash = sp_core::hash::H256;
298			type Hashing = sp_runtime::traits::BlakeTwo256;
299			type AccountId = u64;
300			type Lookup = sp_runtime::traits::IdentityLookup<u64>;
301			type MaxConsumers = frame_support::traits::ConstU32<16>;
302			type AccountData = ();
303			type OnNewAccount = ();
304			type OnKilledAccount = ();
305			type SystemWeightInfo = ();
306			type SS58Prefix = ();
307			type Version = ();
308			type BlockWeights = ();
309			type BlockLength = ();
310			type DbWeight = ();
311			#[inject_runtime_type]
312			type RuntimeEvent = ();
313			#[inject_runtime_type]
314			type RuntimeOrigin = ();
315			#[inject_runtime_type]
316			type RuntimeCall = ();
317			#[inject_runtime_type]
318			type PalletInfo = ();
319			#[inject_runtime_type]
320			type RuntimeTask = ();
321			type BaseCallFilter = frame_support::traits::Everything;
322			type BlockHashCount = TestBlockHashCount<frame_support::traits::ConstU32<10>>;
323			type OnSetCode = ();
324			type SingleBlockMigrations = ();
325			type MultiBlockMigrator = ();
326			type PreInherents = ();
327			type PostInherents = ();
328			type PostTransactions = ();
329		}
330
331		/// Default configurations of this pallet in a solochain environment.
332		///
333		/// ## Considerations:
334		///
335		/// By default, this type makes the following choices:
336		///
337		/// * Use a normal 32 byte account id, with a [`DefaultConfig::Lookup`] that implies no
338		///   'account-indexing' pallet is being used.
339		/// * Given that we don't know anything about the existence of a currency system in scope,
340		///   an [`DefaultConfig::AccountData`] is chosen that has no addition data. Overwrite this
341		///   if you use `pallet-balances` or similar.
342		/// * Make sure to overwrite [`DefaultConfig::Version`].
343		/// * 2s block time, and a default 5mb block size is used.
344		pub struct SolochainDefaultConfig;
345
346		#[frame_support::register_default_impl(SolochainDefaultConfig)]
347		impl DefaultConfig for SolochainDefaultConfig {
348			/// The default type for storing how many extrinsics an account has signed.
349			type Nonce = u32;
350
351			/// The default type for hashing blocks and tries.
352			type Hash = sp_core::hash::H256;
353
354			/// The default hashing algorithm used.
355			type Hashing = sp_runtime::traits::BlakeTwo256;
356
357			/// The default identifier used to distinguish between accounts.
358			type AccountId = sp_runtime::AccountId32;
359
360			/// The lookup mechanism to get account ID from whatever is passed in dispatchers.
361			type Lookup = sp_runtime::traits::AccountIdLookup<Self::AccountId, ()>;
362
363			/// The maximum number of consumers allowed on a single account. Using 128 as default.
364			type MaxConsumers = frame_support::traits::ConstU32<128>;
365
366			/// The default data to be stored in an account.
367			type AccountData = crate::AccountInfo<Self::Nonce, ()>;
368
369			/// What to do if a new account is created.
370			type OnNewAccount = ();
371
372			/// What to do if an account is fully reaped from the system.
373			type OnKilledAccount = ();
374
375			/// Weight information for the extrinsics of this pallet.
376			type SystemWeightInfo = ();
377
378			/// This is used as an identifier of the chain.
379			type SS58Prefix = ();
380
381			/// Version of the runtime.
382			type Version = ();
383
384			/// Block & extrinsics weights: base values and limits.
385			type BlockWeights = ();
386
387			/// The maximum length of a block (in bytes).
388			type BlockLength = ();
389
390			/// The weight of database operations that the runtime can invoke.
391			type DbWeight = ();
392
393			/// The ubiquitous event type injected by `construct_runtime!`.
394			#[inject_runtime_type]
395			type RuntimeEvent = ();
396
397			/// The ubiquitous origin type injected by `construct_runtime!`.
398			#[inject_runtime_type]
399			type RuntimeOrigin = ();
400
401			/// The aggregated dispatch type available for extrinsics, injected by
402			/// `construct_runtime!`.
403			#[inject_runtime_type]
404			type RuntimeCall = ();
405
406			/// The aggregated Task type, injected by `construct_runtime!`.
407			#[inject_runtime_type]
408			type RuntimeTask = ();
409
410			/// Converts a module to the index of the module, injected by `construct_runtime!`.
411			#[inject_runtime_type]
412			type PalletInfo = ();
413
414			/// The basic call filter to use in dispatchable. Supports everything as the default.
415			type BaseCallFilter = frame_support::traits::Everything;
416
417			/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
418			/// Using 256 as default.
419			type BlockHashCount = TestBlockHashCount<frame_support::traits::ConstU32<256>>;
420
421			/// The set code logic, just the default since we're not a parachain.
422			type OnSetCode = ();
423			type SingleBlockMigrations = ();
424			type MultiBlockMigrator = ();
425			type PreInherents = ();
426			type PostInherents = ();
427			type PostTransactions = ();
428		}
429
430		/// Default configurations of this pallet in a relay-chain environment.
431		pub struct RelayChainDefaultConfig;
432
433		/// It currently uses the same configuration as `SolochainDefaultConfig`.
434		#[derive_impl(SolochainDefaultConfig as DefaultConfig, no_aggregated_types)]
435		#[frame_support::register_default_impl(RelayChainDefaultConfig)]
436		impl DefaultConfig for RelayChainDefaultConfig {}
437
438		/// Default configurations of this pallet in a parachain environment.
439		pub struct ParaChainDefaultConfig;
440
441		/// It currently uses the same configuration as `SolochainDefaultConfig`.
442		#[derive_impl(SolochainDefaultConfig as DefaultConfig, no_aggregated_types)]
443		#[frame_support::register_default_impl(ParaChainDefaultConfig)]
444		impl DefaultConfig for ParaChainDefaultConfig {}
445	}
446
447	/// System configuration trait. Implemented by runtime.
448	#[pallet::config(with_default)]
449	#[pallet::disable_frame_system_supertrait_check]
450	pub trait Config: 'static + Eq + Clone {
451		/// The aggregated event type of the runtime.
452		#[pallet::no_default_bounds]
453		type RuntimeEvent: Parameter
454			+ Member
455			+ From<Event<Self>>
456			+ Debug
457			+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
458
459		/// The basic call filter to use in Origin. All origins are built with this filter as base,
460		/// except Root.
461		///
462		/// This works as a filter for each incoming call. The call needs to pass this filter in
463		/// order to dispatch. Otherwise it will be rejected with `CallFiltered`. This can be
464		/// bypassed via `dispatch_bypass_filter` which should only be accessible by root. The
465		/// filter can be composed of sub-filters by nesting for example
466		/// [`frame_support::traits::InsideBoth`], [`frame_support::traits::TheseExcept`] or
467		/// [`frame_support::traits::EverythingBut`] et al. The default would be
468		/// [`frame_support::traits::Everything`].
469		#[pallet::no_default_bounds]
470		type BaseCallFilter: Contains<Self::RuntimeCall>;
471
472		/// Block & extrinsics weights: base values and limits.
473		#[pallet::constant]
474		type BlockWeights: Get<limits::BlockWeights>;
475
476		/// The maximum length of a block (in bytes).
477		#[pallet::constant]
478		type BlockLength: Get<limits::BlockLength>;
479
480		/// The `RuntimeOrigin` type used by dispatchable calls.
481		#[pallet::no_default_bounds]
482		type RuntimeOrigin: Into<Result<RawOrigin<Self::AccountId>, Self::RuntimeOrigin>>
483			+ From<RawOrigin<Self::AccountId>>
484			+ Clone
485			+ OriginTrait<Call = Self::RuntimeCall, AccountId = Self::AccountId>;
486
487		#[docify::export(system_runtime_call)]
488		/// The aggregated `RuntimeCall` type.
489		#[pallet::no_default_bounds]
490		type RuntimeCall: Parameter
491			+ Dispatchable<RuntimeOrigin = Self::RuntimeOrigin>
492			+ Debug
493			+ From<Call<Self>>;
494
495		/// The aggregated `RuntimeTask` type.
496		#[pallet::no_default_bounds]
497		type RuntimeTask: Task;
498
499		/// This stores the number of previous transactions associated with a sender account.
500		type Nonce: Parameter
501			+ Member
502			+ MaybeSerializeDeserialize
503			+ Debug
504			+ Default
505			+ MaybeDisplay
506			+ AtLeast32Bit
507			+ Copy
508			+ MaxEncodedLen;
509
510		/// The output of the `Hashing` function.
511		type Hash: Parameter
512			+ Member
513			+ MaybeSerializeDeserialize
514			+ Debug
515			+ MaybeDisplay
516			+ SimpleBitOps
517			+ Ord
518			+ Default
519			+ Copy
520			+ CheckEqual
521			+ core::hash::Hash
522			+ AsRef<[u8]>
523			+ AsMut<[u8]>
524			+ MaxEncodedLen;
525
526		/// The hashing system (algorithm) being used in the runtime (e.g. Blake2).
527		type Hashing: Hash<Output = Self::Hash> + TypeInfo;
528
529		/// The user account identifier type for the runtime.
530		type AccountId: Parameter
531			+ Member
532			+ MaybeSerializeDeserialize
533			+ Debug
534			+ MaybeDisplay
535			+ Ord
536			+ MaxEncodedLen;
537
538		/// Converting trait to take a source type and convert to `AccountId`.
539		///
540		/// Used to define the type and conversion mechanism for referencing accounts in
541		/// transactions. It's perfectly reasonable for this to be an identity conversion (with the
542		/// source type being `AccountId`), but other pallets (e.g. Indices pallet) may provide more
543		/// functional/efficient alternatives.
544		type Lookup: StaticLookup<Target = Self::AccountId>;
545
546		/// The Block type used by the runtime. This is used by `construct_runtime` to retrieve the
547		/// extrinsics or other block specific data as needed.
548		#[pallet::no_default]
549		type Block: Parameter + Member + traits::Block<Hash = Self::Hash>;
550
551		/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
552		#[pallet::constant]
553		#[pallet::no_default_bounds]
554		type BlockHashCount: Get<BlockNumberFor<Self>>;
555
556		/// The weight of runtime database operations the runtime can invoke.
557		#[pallet::constant]
558		type DbWeight: Get<RuntimeDbWeight>;
559
560		/// Get the chain's in-code version.
561		#[pallet::constant]
562		type Version: Get<RuntimeVersion>;
563
564		/// Provides information about the pallet setup in the runtime.
565		///
566		/// Expects the `PalletInfo` type that is being generated by `construct_runtime!` in the
567		/// runtime.
568		///
569		/// For tests it is okay to use `()` as type, however it will provide "useless" data.
570		#[pallet::no_default_bounds]
571		type PalletInfo: PalletInfo;
572
573		/// Data to be associated with an account (other than nonce/transaction counter, which this
574		/// pallet does regardless).
575		type AccountData: Member + FullCodec + Clone + Default + TypeInfo + MaxEncodedLen;
576
577		/// Handler for when a new account has just been created.
578		type OnNewAccount: OnNewAccount<Self::AccountId>;
579
580		/// A function that is invoked when an account has been determined to be dead.
581		///
582		/// All resources should be cleaned up associated with the given account.
583		type OnKilledAccount: OnKilledAccount<Self::AccountId>;
584
585		type SystemWeightInfo: WeightInfo;
586
587		/// The designated SS58 prefix of this chain.
588		///
589		/// This replaces the "ss58Format" property declared in the chain spec. Reason is
590		/// that the runtime should know about the prefix in order to make use of it as
591		/// an identifier of the chain.
592		#[pallet::constant]
593		type SS58Prefix: Get<u16>;
594
595		/// What to do if the runtime wants to change the code to something new.
596		///
597		/// The default (`()`) implementation is responsible for setting the correct storage
598		/// entry and emitting corresponding event and log item. (see
599		/// [`Pallet::update_code_in_storage`]).
600		/// It's unlikely that this needs to be customized, unless you are writing a parachain using
601		/// `Cumulus`, where the actual code change is deferred.
602		#[pallet::no_default_bounds]
603		type OnSetCode: SetCode<Self>;
604
605		/// The maximum number of consumers allowed on a single account.
606		type MaxConsumers: ConsumerLimits;
607
608		/// All migrations that should run in the next runtime upgrade.
609		///
610		/// These used to be formerly configured in `Executive`. Parachains need to ensure that
611		/// running all these migrations in one block will not overflow the weight limit of a block.
612		/// The migrations are run *before* the pallet `on_runtime_upgrade` hooks, just like the
613		/// `OnRuntimeUpgrade` migrations.
614		type SingleBlockMigrations: OnRuntimeUpgrade;
615
616		/// The migrator that is used to run Multi-Block-Migrations.
617		///
618		/// Can be set to [`pallet-migrations`] or an alternative implementation of the interface.
619		/// The diagram in `frame_executive::block_flowchart` explains when it runs.
620		type MultiBlockMigrator: MultiStepMigrator;
621
622		/// A callback that executes in *every block* directly before all inherents were applied.
623		///
624		/// See `frame_executive::block_flowchart` for a in-depth explanation when it runs.
625		type PreInherents: PreInherents;
626
627		/// A callback that executes in *every block* directly after all inherents were applied.
628		///
629		/// See `frame_executive::block_flowchart` for a in-depth explanation when it runs.
630		type PostInherents: PostInherents;
631
632		/// A callback that executes in *every block* directly after all transactions were applied.
633		///
634		/// See `frame_executive::block_flowchart` for a in-depth explanation when it runs.
635		type PostTransactions: PostTransactions;
636	}
637
638	#[pallet::pallet]
639	pub struct Pallet<T>(_);
640
641	#[pallet::hooks]
642	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
643		#[cfg(feature = "std")]
644		fn integrity_test() {
645			T::BlockWeights::get().validate().expect("The weights are invalid.");
646		}
647	}
648
649	#[pallet::call]
650	impl<T: Config> Pallet<T> {
651		/// Make some on-chain remark.
652		///
653		/// Can be executed by every `origin`.
654		#[pallet::call_index(0)]
655		#[pallet::weight(T::SystemWeightInfo::remark(remark.len() as u32))]
656		pub fn remark(_origin: OriginFor<T>, remark: Vec<u8>) -> DispatchResultWithPostInfo {
657			let _ = remark; // No need to check the weight witness.
658			Ok(().into())
659		}
660
661		/// Set the number of pages in the WebAssembly environment's heap.
662		#[pallet::call_index(1)]
663		#[pallet::weight((T::SystemWeightInfo::set_heap_pages(), DispatchClass::Operational))]
664		pub fn set_heap_pages(origin: OriginFor<T>, pages: u64) -> DispatchResultWithPostInfo {
665			ensure_root(origin)?;
666			storage::unhashed::put_raw(well_known_keys::HEAP_PAGES, &pages.encode());
667			Self::deposit_log(generic::DigestItem::RuntimeEnvironmentUpdated);
668			Ok(().into())
669		}
670
671		/// Set the new runtime code.
672		#[pallet::call_index(2)]
673		#[pallet::weight((T::SystemWeightInfo::set_code(), DispatchClass::Operational))]
674		pub fn set_code(origin: OriginFor<T>, code: Vec<u8>) -> DispatchResultWithPostInfo {
675			ensure_root(origin)?;
676			Self::can_set_code(&code)?;
677			T::OnSetCode::set_code(code)?;
678			// consume the rest of the block to prevent further transactions
679			Ok(Some(T::BlockWeights::get().max_block).into())
680		}
681
682		/// Set the new runtime code without doing any checks of the given `code`.
683		///
684		/// Note that runtime upgrades will not run if this is called with a not-increasing spec
685		/// version!
686		#[pallet::call_index(3)]
687		#[pallet::weight((T::SystemWeightInfo::set_code(), DispatchClass::Operational))]
688		pub fn set_code_without_checks(
689			origin: OriginFor<T>,
690			code: Vec<u8>,
691		) -> DispatchResultWithPostInfo {
692			ensure_root(origin)?;
693			T::OnSetCode::set_code(code)?;
694			Ok(Some(T::BlockWeights::get().max_block).into())
695		}
696
697		/// Set some items of storage.
698		#[pallet::call_index(4)]
699		#[pallet::weight((
700			T::SystemWeightInfo::set_storage(items.len() as u32),
701			DispatchClass::Operational,
702		))]
703		pub fn set_storage(
704			origin: OriginFor<T>,
705			items: Vec<KeyValue>,
706		) -> DispatchResultWithPostInfo {
707			ensure_root(origin)?;
708			for i in &items {
709				storage::unhashed::put_raw(&i.0, &i.1);
710			}
711			Ok(().into())
712		}
713
714		/// Kill some items from storage.
715		#[pallet::call_index(5)]
716		#[pallet::weight((
717			T::SystemWeightInfo::kill_storage(keys.len() as u32),
718			DispatchClass::Operational,
719		))]
720		pub fn kill_storage(origin: OriginFor<T>, keys: Vec<Key>) -> DispatchResultWithPostInfo {
721			ensure_root(origin)?;
722			for key in &keys {
723				storage::unhashed::kill(key);
724			}
725			Ok(().into())
726		}
727
728		/// Kill all storage items with a key that starts with the given prefix.
729		///
730		/// **NOTE:** We rely on the Root origin to provide us the number of subkeys under
731		/// the prefix we are removing to accurately calculate the weight of this function.
732		#[pallet::call_index(6)]
733		#[pallet::weight((
734			T::SystemWeightInfo::kill_prefix(subkeys.saturating_add(1)),
735			DispatchClass::Operational,
736		))]
737		pub fn kill_prefix(
738			origin: OriginFor<T>,
739			prefix: Key,
740			subkeys: u32,
741		) -> DispatchResultWithPostInfo {
742			ensure_root(origin)?;
743			let _ = storage::unhashed::clear_prefix(&prefix, Some(subkeys), None);
744			Ok(().into())
745		}
746
747		/// Make some on-chain remark and emit event.
748		#[pallet::call_index(7)]
749		#[pallet::weight(T::SystemWeightInfo::remark_with_event(remark.len() as u32))]
750		pub fn remark_with_event(
751			origin: OriginFor<T>,
752			remark: Vec<u8>,
753		) -> DispatchResultWithPostInfo {
754			let who = ensure_signed(origin)?;
755			let hash = T::Hashing::hash(&remark[..]);
756			Self::deposit_event(Event::Remarked { sender: who, hash });
757			Ok(().into())
758		}
759
760		#[cfg(feature = "experimental")]
761		#[pallet::call_index(8)]
762		#[pallet::weight(task.weight())]
763		pub fn do_task(_origin: OriginFor<T>, task: T::RuntimeTask) -> DispatchResultWithPostInfo {
764			if !task.is_valid() {
765				return Err(Error::<T>::InvalidTask.into())
766			}
767
768			Self::deposit_event(Event::TaskStarted { task: task.clone() });
769			if let Err(err) = task.run() {
770				Self::deposit_event(Event::TaskFailed { task, err });
771				return Err(Error::<T>::FailedTask.into())
772			}
773
774			// Emit a success event, if your design includes events for this pallet.
775			Self::deposit_event(Event::TaskCompleted { task });
776
777			// Return success.
778			Ok(().into())
779		}
780
781		/// Authorize an upgrade to a given `code_hash` for the runtime. The runtime can be supplied
782		/// later.
783		///
784		/// This call requires Root origin.
785		#[pallet::call_index(9)]
786		#[pallet::weight((T::SystemWeightInfo::authorize_upgrade(), DispatchClass::Operational))]
787		pub fn authorize_upgrade(origin: OriginFor<T>, code_hash: T::Hash) -> DispatchResult {
788			ensure_root(origin)?;
789			Self::do_authorize_upgrade(code_hash, true);
790			Ok(())
791		}
792
793		/// Authorize an upgrade to a given `code_hash` for the runtime. The runtime can be supplied
794		/// later.
795		///
796		/// WARNING: This authorizes an upgrade that will take place without any safety checks, for
797		/// example that the spec name remains the same and that the version number increases. Not
798		/// recommended for normal use. Use `authorize_upgrade` instead.
799		///
800		/// This call requires Root origin.
801		#[pallet::call_index(10)]
802		#[pallet::weight((T::SystemWeightInfo::authorize_upgrade(), DispatchClass::Operational))]
803		pub fn authorize_upgrade_without_checks(
804			origin: OriginFor<T>,
805			code_hash: T::Hash,
806		) -> DispatchResult {
807			ensure_root(origin)?;
808			Self::do_authorize_upgrade(code_hash, false);
809			Ok(())
810		}
811
812		/// Provide the preimage (runtime binary) `code` for an upgrade that has been authorized.
813		///
814		/// If the authorization required a version check, this call will ensure the spec name
815		/// remains unchanged and that the spec version has increased.
816		///
817		/// Depending on the runtime's `OnSetCode` configuration, this function may directly apply
818		/// the new `code` in the same block or attempt to schedule the upgrade.
819		///
820		/// All origins are allowed.
821		#[pallet::call_index(11)]
822		#[pallet::weight((T::SystemWeightInfo::apply_authorized_upgrade(), DispatchClass::Operational))]
823		pub fn apply_authorized_upgrade(
824			_: OriginFor<T>,
825			code: Vec<u8>,
826		) -> DispatchResultWithPostInfo {
827			let post = Self::do_apply_authorize_upgrade(code)?;
828			Ok(post)
829		}
830	}
831
832	/// Event for the System pallet.
833	#[pallet::event]
834	pub enum Event<T: Config> {
835		/// An extrinsic completed successfully.
836		ExtrinsicSuccess { dispatch_info: DispatchInfo },
837		/// An extrinsic failed.
838		ExtrinsicFailed { dispatch_error: DispatchError, dispatch_info: DispatchInfo },
839		/// `:code` was updated.
840		CodeUpdated,
841		/// A new account was created.
842		NewAccount { account: T::AccountId },
843		/// An account was reaped.
844		KilledAccount { account: T::AccountId },
845		/// On on-chain remark happened.
846		Remarked { sender: T::AccountId, hash: T::Hash },
847		#[cfg(feature = "experimental")]
848		/// A [`Task`] has started executing
849		TaskStarted { task: T::RuntimeTask },
850		#[cfg(feature = "experimental")]
851		/// A [`Task`] has finished executing.
852		TaskCompleted { task: T::RuntimeTask },
853		#[cfg(feature = "experimental")]
854		/// A [`Task`] failed during execution.
855		TaskFailed { task: T::RuntimeTask, err: DispatchError },
856		/// An upgrade was authorized.
857		UpgradeAuthorized { code_hash: T::Hash, check_version: bool },
858	}
859
860	/// Error for the System pallet
861	#[pallet::error]
862	pub enum Error<T> {
863		/// The name of specification does not match between the current runtime
864		/// and the new runtime.
865		InvalidSpecName,
866		/// The specification version is not allowed to decrease between the current runtime
867		/// and the new runtime.
868		SpecVersionNeedsToIncrease,
869		/// Failed to extract the runtime version from the new runtime.
870		///
871		/// Either calling `Core_version` or decoding `RuntimeVersion` failed.
872		FailedToExtractRuntimeVersion,
873		/// Suicide called when the account has non-default composite data.
874		NonDefaultComposite,
875		/// There is a non-zero reference count preventing the account from being purged.
876		NonZeroRefCount,
877		/// The origin filter prevent the call to be dispatched.
878		CallFiltered,
879		/// A multi-block migration is ongoing and prevents the current code from being replaced.
880		MultiBlockMigrationsOngoing,
881		#[cfg(feature = "experimental")]
882		/// The specified [`Task`] is not valid.
883		InvalidTask,
884		#[cfg(feature = "experimental")]
885		/// The specified [`Task`] failed during execution.
886		FailedTask,
887		/// No upgrade authorized.
888		NothingAuthorized,
889		/// The submitted code is not authorized.
890		Unauthorized,
891	}
892
893	/// Exposed trait-generic origin type.
894	#[pallet::origin]
895	pub type Origin<T> = RawOrigin<<T as Config>::AccountId>;
896
897	/// The full account information for a particular account ID.
898	#[pallet::storage]
899	#[pallet::getter(fn account)]
900	pub type Account<T: Config> = StorageMap<
901		_,
902		Blake2_128Concat,
903		T::AccountId,
904		AccountInfo<T::Nonce, T::AccountData>,
905		ValueQuery,
906	>;
907
908	/// Total extrinsics count for the current block.
909	#[pallet::storage]
910	pub(super) type ExtrinsicCount<T: Config> = StorageValue<_, u32>;
911
912	/// Whether all inherents have been applied.
913	#[pallet::storage]
914	pub type InherentsApplied<T: Config> = StorageValue<_, bool, ValueQuery>;
915
916	/// The current weight for the block.
917	#[pallet::storage]
918	#[pallet::whitelist_storage]
919	#[pallet::getter(fn block_weight)]
920	pub type BlockWeight<T: Config> = StorageValue<_, ConsumedWeight, ValueQuery>;
921
922	/// Total length (in bytes) for all extrinsics put together, for the current block.
923	#[pallet::storage]
924	pub type AllExtrinsicsLen<T: Config> = StorageValue<_, u32>;
925
926	/// Map of block numbers to block hashes.
927	#[pallet::storage]
928	#[pallet::getter(fn block_hash)]
929	pub type BlockHash<T: Config> =
930		StorageMap<_, Twox64Concat, BlockNumberFor<T>, T::Hash, ValueQuery>;
931
932	/// Extrinsics data for the current block (maps an extrinsic's index to its data).
933	#[pallet::storage]
934	#[pallet::getter(fn extrinsic_data)]
935	#[pallet::unbounded]
936	pub(super) type ExtrinsicData<T: Config> =
937		StorageMap<_, Twox64Concat, u32, Vec<u8>, ValueQuery>;
938
939	/// The current block number being processed. Set by `execute_block`.
940	#[pallet::storage]
941	#[pallet::whitelist_storage]
942	#[pallet::getter(fn block_number)]
943	pub(super) type Number<T: Config> = StorageValue<_, BlockNumberFor<T>, ValueQuery>;
944
945	/// Hash of the previous block.
946	#[pallet::storage]
947	#[pallet::getter(fn parent_hash)]
948	pub(super) type ParentHash<T: Config> = StorageValue<_, T::Hash, ValueQuery>;
949
950	/// Digest of the current block, also part of the block header.
951	#[pallet::storage]
952	#[pallet::unbounded]
953	#[pallet::getter(fn digest)]
954	pub(super) type Digest<T: Config> = StorageValue<_, generic::Digest, ValueQuery>;
955
956	/// Events deposited for the current block.
957	///
958	/// NOTE: The item is unbound and should therefore never be read on chain.
959	/// It could otherwise inflate the PoV size of a block.
960	///
961	/// Events have a large in-memory size. Box the events to not go out-of-memory
962	/// just in case someone still reads them from within the runtime.
963	#[pallet::storage]
964	#[pallet::whitelist_storage]
965	#[pallet::disable_try_decode_storage]
966	#[pallet::unbounded]
967	pub(super) type Events<T: Config> =
968		StorageValue<_, Vec<Box<EventRecord<T::RuntimeEvent, T::Hash>>>, ValueQuery>;
969
970	/// The number of events in the `Events<T>` list.
971	#[pallet::storage]
972	#[pallet::whitelist_storage]
973	#[pallet::getter(fn event_count)]
974	pub(super) type EventCount<T: Config> = StorageValue<_, EventIndex, ValueQuery>;
975
976	/// Mapping between a topic (represented by T::Hash) and a vector of indexes
977	/// of events in the `<Events<T>>` list.
978	///
979	/// All topic vectors have deterministic storage locations depending on the topic. This
980	/// allows light-clients to leverage the changes trie storage tracking mechanism and
981	/// in case of changes fetch the list of events of interest.
982	///
983	/// The value has the type `(BlockNumberFor<T>, EventIndex)` because if we used only just
984	/// the `EventIndex` then in case if the topic has the same contents on the next block
985	/// no notification will be triggered thus the event might be lost.
986	#[pallet::storage]
987	#[pallet::unbounded]
988	#[pallet::getter(fn event_topics)]
989	pub(super) type EventTopics<T: Config> =
990		StorageMap<_, Blake2_128Concat, T::Hash, Vec<(BlockNumberFor<T>, EventIndex)>, ValueQuery>;
991
992	/// Stores the `spec_version` and `spec_name` of when the last runtime upgrade happened.
993	#[pallet::storage]
994	#[pallet::unbounded]
995	pub type LastRuntimeUpgrade<T: Config> = StorageValue<_, LastRuntimeUpgradeInfo>;
996
997	/// True if we have upgraded so that `type RefCount` is `u32`. False (default) if not.
998	#[pallet::storage]
999	pub(super) type UpgradedToU32RefCount<T: Config> = StorageValue<_, bool, ValueQuery>;
1000
1001	/// True if we have upgraded so that AccountInfo contains three types of `RefCount`. False
1002	/// (default) if not.
1003	#[pallet::storage]
1004	pub(super) type UpgradedToTripleRefCount<T: Config> = StorageValue<_, bool, ValueQuery>;
1005
1006	/// The execution phase of the block.
1007	#[pallet::storage]
1008	#[pallet::whitelist_storage]
1009	pub(super) type ExecutionPhase<T: Config> = StorageValue<_, Phase>;
1010
1011	/// `Some` if a code upgrade has been authorized.
1012	#[pallet::storage]
1013	#[pallet::getter(fn authorized_upgrade)]
1014	pub(super) type AuthorizedUpgrade<T: Config> =
1015		StorageValue<_, CodeUpgradeAuthorization<T>, OptionQuery>;
1016
1017	#[derive(frame_support::DefaultNoBound)]
1018	#[pallet::genesis_config]
1019	pub struct GenesisConfig<T: Config> {
1020		#[serde(skip)]
1021		pub _config: core::marker::PhantomData<T>,
1022	}
1023
1024	#[pallet::genesis_build]
1025	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
1026		fn build(&self) {
1027			<BlockHash<T>>::insert::<_, T::Hash>(BlockNumberFor::<T>::zero(), hash69());
1028			<ParentHash<T>>::put::<T::Hash>(hash69());
1029			<LastRuntimeUpgrade<T>>::put(LastRuntimeUpgradeInfo::from(T::Version::get()));
1030			<UpgradedToU32RefCount<T>>::put(true);
1031			<UpgradedToTripleRefCount<T>>::put(true);
1032
1033			sp_io::storage::set(well_known_keys::EXTRINSIC_INDEX, &0u32.encode());
1034		}
1035	}
1036
1037	#[pallet::validate_unsigned]
1038	impl<T: Config> sp_runtime::traits::ValidateUnsigned for Pallet<T> {
1039		type Call = Call<T>;
1040		fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity {
1041			if let Call::apply_authorized_upgrade { ref code } = call {
1042				if let Ok(hash) = Self::validate_authorized_upgrade(&code[..]) {
1043					return Ok(ValidTransaction {
1044						priority: 100,
1045						requires: Vec::new(),
1046						provides: vec![hash.as_ref().to_vec()],
1047						longevity: TransactionLongevity::max_value(),
1048						propagate: true,
1049					})
1050				}
1051			}
1052			#[cfg(feature = "experimental")]
1053			if let Call::do_task { ref task } = call {
1054				if task.is_valid() {
1055					return Ok(ValidTransaction {
1056						priority: u64::max_value(),
1057						requires: Vec::new(),
1058						provides: vec![T::Hashing::hash_of(&task.encode()).as_ref().to_vec()],
1059						longevity: TransactionLongevity::max_value(),
1060						propagate: true,
1061					})
1062				}
1063			}
1064			Err(InvalidTransaction::Call.into())
1065		}
1066	}
1067}
1068
1069pub type Key = Vec<u8>;
1070pub type KeyValue = (Vec<u8>, Vec<u8>);
1071
1072/// A phase of a block's execution.
1073#[derive(Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]
1074#[cfg_attr(feature = "std", derive(Serialize, PartialEq, Eq, Clone))]
1075pub enum Phase {
1076	/// Applying an extrinsic.
1077	ApplyExtrinsic(u32),
1078	/// Finalizing the block.
1079	Finalization,
1080	/// Initializing the block.
1081	Initialization,
1082}
1083
1084impl Default for Phase {
1085	fn default() -> Self {
1086		Self::Initialization
1087	}
1088}
1089
1090/// Record of an event happening.
1091#[derive(Encode, Decode, RuntimeDebug, TypeInfo)]
1092#[cfg_attr(feature = "std", derive(Serialize, PartialEq, Eq, Clone))]
1093pub struct EventRecord<E: Parameter + Member, T> {
1094	/// The phase of the block it happened in.
1095	pub phase: Phase,
1096	/// The event itself.
1097	pub event: E,
1098	/// The list of the topics this event has.
1099	pub topics: Vec<T>,
1100}
1101
1102// Create a Hash with 69 for each byte,
1103// only used to build genesis config.
1104fn hash69<T: AsMut<[u8]> + Default>() -> T {
1105	let mut h = T::default();
1106	h.as_mut().iter_mut().for_each(|byte| *byte = 69);
1107	h
1108}
1109
1110/// This type alias represents an index of an event.
1111///
1112/// We use `u32` here because this index is used as index for `Events<T>`
1113/// which can't contain more than `u32::MAX` items.
1114type EventIndex = u32;
1115
1116/// Type used to encode the number of references an account has.
1117pub type RefCount = u32;
1118
1119/// Information of an account.
1120#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)]
1121pub struct AccountInfo<Nonce, AccountData> {
1122	/// The number of transactions this account has sent.
1123	pub nonce: Nonce,
1124	/// The number of other modules that currently depend on this account's existence. The account
1125	/// cannot be reaped until this is zero.
1126	pub consumers: RefCount,
1127	/// The number of other modules that allow this account to exist. The account may not be reaped
1128	/// until this and `sufficients` are both zero.
1129	pub providers: RefCount,
1130	/// The number of modules that allow this account to exist for their own purposes only. The
1131	/// account may not be reaped until this and `providers` are both zero.
1132	pub sufficients: RefCount,
1133	/// The additional data that belongs to this account. Used to store the balance(s) in a lot of
1134	/// chains.
1135	pub data: AccountData,
1136}
1137
1138/// Stores the `spec_version` and `spec_name` of when the last runtime upgrade
1139/// happened.
1140#[derive(sp_runtime::RuntimeDebug, Encode, Decode, TypeInfo)]
1141#[cfg_attr(feature = "std", derive(PartialEq))]
1142pub struct LastRuntimeUpgradeInfo {
1143	pub spec_version: codec::Compact<u32>,
1144	pub spec_name: sp_runtime::RuntimeString,
1145}
1146
1147impl LastRuntimeUpgradeInfo {
1148	/// Returns if the runtime was upgraded in comparison of `self` and `current`.
1149	///
1150	/// Checks if either the `spec_version` increased or the `spec_name` changed.
1151	pub fn was_upgraded(&self, current: &sp_version::RuntimeVersion) -> bool {
1152		current.spec_version > self.spec_version.0 || current.spec_name != self.spec_name
1153	}
1154}
1155
1156impl From<sp_version::RuntimeVersion> for LastRuntimeUpgradeInfo {
1157	fn from(version: sp_version::RuntimeVersion) -> Self {
1158		Self { spec_version: version.spec_version.into(), spec_name: version.spec_name }
1159	}
1160}
1161
1162/// Ensure the origin is Root.
1163pub struct EnsureRoot<AccountId>(core::marker::PhantomData<AccountId>);
1164impl<O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>, AccountId>
1165	EnsureOrigin<O> for EnsureRoot<AccountId>
1166{
1167	type Success = ();
1168	fn try_origin(o: O) -> Result<Self::Success, O> {
1169		o.into().and_then(|o| match o {
1170			RawOrigin::Root => Ok(()),
1171			r => Err(O::from(r)),
1172		})
1173	}
1174
1175	#[cfg(feature = "runtime-benchmarks")]
1176	fn try_successful_origin() -> Result<O, ()> {
1177		Ok(O::from(RawOrigin::Root))
1178	}
1179}
1180
1181impl_ensure_origin_with_arg_ignoring_arg! {
1182	impl< { O: .., AccountId: Decode, T } >
1183		EnsureOriginWithArg<O, T> for EnsureRoot<AccountId>
1184	{}
1185}
1186
1187/// Ensure the origin is Root and return the provided `Success` value.
1188pub struct EnsureRootWithSuccess<AccountId, Success>(
1189	core::marker::PhantomData<(AccountId, Success)>,
1190);
1191impl<
1192		O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>,
1193		AccountId,
1194		Success: TypedGet,
1195	> EnsureOrigin<O> for EnsureRootWithSuccess<AccountId, Success>
1196{
1197	type Success = Success::Type;
1198	fn try_origin(o: O) -> Result<Self::Success, O> {
1199		o.into().and_then(|o| match o {
1200			RawOrigin::Root => Ok(Success::get()),
1201			r => Err(O::from(r)),
1202		})
1203	}
1204
1205	#[cfg(feature = "runtime-benchmarks")]
1206	fn try_successful_origin() -> Result<O, ()> {
1207		Ok(O::from(RawOrigin::Root))
1208	}
1209}
1210
1211impl_ensure_origin_with_arg_ignoring_arg! {
1212	impl< { O: .., AccountId: Decode, Success: TypedGet, T } >
1213		EnsureOriginWithArg<O, T> for EnsureRootWithSuccess<AccountId, Success>
1214	{}
1215}
1216
1217/// Ensure the origin is provided `Ensure` origin and return the provided `Success` value.
1218pub struct EnsureWithSuccess<Ensure, AccountId, Success>(
1219	core::marker::PhantomData<(Ensure, AccountId, Success)>,
1220);
1221
1222impl<
1223		O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>,
1224		Ensure: EnsureOrigin<O>,
1225		AccountId,
1226		Success: TypedGet,
1227	> EnsureOrigin<O> for EnsureWithSuccess<Ensure, AccountId, Success>
1228{
1229	type Success = Success::Type;
1230
1231	fn try_origin(o: O) -> Result<Self::Success, O> {
1232		Ensure::try_origin(o).map(|_| Success::get())
1233	}
1234
1235	#[cfg(feature = "runtime-benchmarks")]
1236	fn try_successful_origin() -> Result<O, ()> {
1237		Ensure::try_successful_origin()
1238	}
1239}
1240
1241/// Ensure the origin is any `Signed` origin.
1242pub struct EnsureSigned<AccountId>(core::marker::PhantomData<AccountId>);
1243impl<O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>, AccountId: Decode>
1244	EnsureOrigin<O> for EnsureSigned<AccountId>
1245{
1246	type Success = AccountId;
1247	fn try_origin(o: O) -> Result<Self::Success, O> {
1248		o.into().and_then(|o| match o {
1249			RawOrigin::Signed(who) => Ok(who),
1250			r => Err(O::from(r)),
1251		})
1252	}
1253
1254	#[cfg(feature = "runtime-benchmarks")]
1255	fn try_successful_origin() -> Result<O, ()> {
1256		let zero_account_id =
1257			AccountId::decode(&mut TrailingZeroInput::zeroes()).map_err(|_| ())?;
1258		Ok(O::from(RawOrigin::Signed(zero_account_id)))
1259	}
1260}
1261
1262impl_ensure_origin_with_arg_ignoring_arg! {
1263	impl< { O: .., AccountId: Decode, T } >
1264		EnsureOriginWithArg<O, T> for EnsureSigned<AccountId>
1265	{}
1266}
1267
1268/// Ensure the origin is `Signed` origin from the given `AccountId`.
1269pub struct EnsureSignedBy<Who, AccountId>(core::marker::PhantomData<(Who, AccountId)>);
1270impl<
1271		O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>,
1272		Who: SortedMembers<AccountId>,
1273		AccountId: PartialEq + Clone + Ord + Decode,
1274	> EnsureOrigin<O> for EnsureSignedBy<Who, AccountId>
1275{
1276	type Success = AccountId;
1277	fn try_origin(o: O) -> Result<Self::Success, O> {
1278		o.into().and_then(|o| match o {
1279			RawOrigin::Signed(ref who) if Who::contains(who) => Ok(who.clone()),
1280			r => Err(O::from(r)),
1281		})
1282	}
1283
1284	#[cfg(feature = "runtime-benchmarks")]
1285	fn try_successful_origin() -> Result<O, ()> {
1286		let first_member = match Who::sorted_members().first() {
1287			Some(account) => account.clone(),
1288			None => AccountId::decode(&mut TrailingZeroInput::zeroes()).map_err(|_| ())?,
1289		};
1290		Ok(O::from(RawOrigin::Signed(first_member)))
1291	}
1292}
1293
1294impl_ensure_origin_with_arg_ignoring_arg! {
1295	impl< { O: .., Who: SortedMembers<AccountId>, AccountId: PartialEq + Clone + Ord + Decode, T } >
1296		EnsureOriginWithArg<O, T> for EnsureSignedBy<Who, AccountId>
1297	{}
1298}
1299
1300/// Ensure the origin is `None`. i.e. unsigned transaction.
1301pub struct EnsureNone<AccountId>(core::marker::PhantomData<AccountId>);
1302impl<O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>, AccountId>
1303	EnsureOrigin<O> for EnsureNone<AccountId>
1304{
1305	type Success = ();
1306	fn try_origin(o: O) -> Result<Self::Success, O> {
1307		o.into().and_then(|o| match o {
1308			RawOrigin::None => Ok(()),
1309			r => Err(O::from(r)),
1310		})
1311	}
1312
1313	#[cfg(feature = "runtime-benchmarks")]
1314	fn try_successful_origin() -> Result<O, ()> {
1315		Ok(O::from(RawOrigin::None))
1316	}
1317}
1318
1319impl_ensure_origin_with_arg_ignoring_arg! {
1320	impl< { O: .., AccountId, T } >
1321		EnsureOriginWithArg<O, T> for EnsureNone<AccountId>
1322	{}
1323}
1324
1325/// Always fail.
1326pub struct EnsureNever<Success>(core::marker::PhantomData<Success>);
1327impl<O, Success> EnsureOrigin<O> for EnsureNever<Success> {
1328	type Success = Success;
1329	fn try_origin(o: O) -> Result<Self::Success, O> {
1330		Err(o)
1331	}
1332
1333	#[cfg(feature = "runtime-benchmarks")]
1334	fn try_successful_origin() -> Result<O, ()> {
1335		Err(())
1336	}
1337}
1338
1339impl_ensure_origin_with_arg_ignoring_arg! {
1340	impl< { O, Success, T } >
1341		EnsureOriginWithArg<O, T> for EnsureNever<Success>
1342	{}
1343}
1344
1345#[docify::export]
1346/// Ensure that the origin `o` represents a signed extrinsic (i.e. transaction).
1347/// Returns `Ok` with the account that signed the extrinsic or an `Err` otherwise.
1348pub fn ensure_signed<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<AccountId, BadOrigin>
1349where
1350	OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
1351{
1352	match o.into() {
1353		Ok(RawOrigin::Signed(t)) => Ok(t),
1354		_ => Err(BadOrigin),
1355	}
1356}
1357
1358/// Ensure that the origin `o` represents either a signed extrinsic (i.e. transaction) or the root.
1359/// Returns `Ok` with the account that signed the extrinsic, `None` if it was root,  or an `Err`
1360/// otherwise.
1361pub fn ensure_signed_or_root<OuterOrigin, AccountId>(
1362	o: OuterOrigin,
1363) -> Result<Option<AccountId>, BadOrigin>
1364where
1365	OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
1366{
1367	match o.into() {
1368		Ok(RawOrigin::Root) => Ok(None),
1369		Ok(RawOrigin::Signed(t)) => Ok(Some(t)),
1370		_ => Err(BadOrigin),
1371	}
1372}
1373
1374/// Ensure that the origin `o` represents the root. Returns `Ok` or an `Err` otherwise.
1375pub fn ensure_root<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<(), BadOrigin>
1376where
1377	OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
1378{
1379	match o.into() {
1380		Ok(RawOrigin::Root) => Ok(()),
1381		_ => Err(BadOrigin),
1382	}
1383}
1384
1385/// Ensure that the origin `o` represents an unsigned extrinsic. Returns `Ok` or an `Err` otherwise.
1386pub fn ensure_none<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<(), BadOrigin>
1387where
1388	OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
1389{
1390	match o.into() {
1391		Ok(RawOrigin::None) => Ok(()),
1392		_ => Err(BadOrigin),
1393	}
1394}
1395
1396/// Reference status; can be either referenced or unreferenced.
1397#[derive(RuntimeDebug)]
1398pub enum RefStatus {
1399	Referenced,
1400	Unreferenced,
1401}
1402
1403/// Some resultant status relevant to incrementing a provider/self-sufficient reference.
1404#[derive(Eq, PartialEq, RuntimeDebug)]
1405pub enum IncRefStatus {
1406	/// Account was created.
1407	Created,
1408	/// Account already existed.
1409	Existed,
1410}
1411
1412/// Some resultant status relevant to decrementing a provider/self-sufficient reference.
1413#[derive(Eq, PartialEq, RuntimeDebug)]
1414pub enum DecRefStatus {
1415	/// Account was destroyed.
1416	Reaped,
1417	/// Account still exists.
1418	Exists,
1419}
1420
1421impl<T: Config> Pallet<T> {
1422	/// Returns the `spec_version` of the last runtime upgrade.
1423	///
1424	/// This function is useful for writing guarded runtime migrations in the runtime. A runtime
1425	/// migration can use the `spec_version` to ensure that it isn't applied twice. This works
1426	/// similar as the storage version for pallets.
1427	///
1428	/// This functions returns the `spec_version` of the last runtime upgrade while executing the
1429	/// runtime migrations
1430	/// [`on_runtime_upgrade`](frame_support::traits::OnRuntimeUpgrade::on_runtime_upgrade)
1431	/// function. After all migrations are executed, this will return the `spec_version` of the
1432	/// current runtime until there is another runtime upgrade.
1433	///
1434	/// Example:
1435	#[doc = docify::embed!("src/tests.rs", last_runtime_upgrade_spec_version_usage)]
1436	pub fn last_runtime_upgrade_spec_version() -> u32 {
1437		LastRuntimeUpgrade::<T>::get().map_or(0, |l| l.spec_version.0)
1438	}
1439
1440	/// Returns true if the given account exists.
1441	pub fn account_exists(who: &T::AccountId) -> bool {
1442		Account::<T>::contains_key(who)
1443	}
1444
1445	/// Write code to the storage and emit related events and digest items.
1446	///
1447	/// Note this function almost never should be used directly. It is exposed
1448	/// for `OnSetCode` implementations that defer actual code being written to
1449	/// the storage (for instance in case of parachains).
1450	pub fn update_code_in_storage(code: &[u8]) {
1451		storage::unhashed::put_raw(well_known_keys::CODE, code);
1452		Self::deposit_log(generic::DigestItem::RuntimeEnvironmentUpdated);
1453		Self::deposit_event(Event::CodeUpdated);
1454	}
1455
1456	/// Whether all inherents have been applied.
1457	pub fn inherents_applied() -> bool {
1458		InherentsApplied::<T>::get()
1459	}
1460
1461	/// Note that all inherents have been applied.
1462	///
1463	/// Should be called immediately after all inherents have been applied. Must be called at least
1464	/// once per block.
1465	pub fn note_inherents_applied() {
1466		InherentsApplied::<T>::put(true);
1467	}
1468
1469	/// Increment the reference counter on an account.
1470	#[deprecated = "Use `inc_consumers` instead"]
1471	pub fn inc_ref(who: &T::AccountId) {
1472		let _ = Self::inc_consumers(who);
1473	}
1474
1475	/// Decrement the reference counter on an account. This *MUST* only be done once for every time
1476	/// you called `inc_consumers` on `who`.
1477	#[deprecated = "Use `dec_consumers` instead"]
1478	pub fn dec_ref(who: &T::AccountId) {
1479		let _ = Self::dec_consumers(who);
1480	}
1481
1482	/// The number of outstanding references for the account `who`.
1483	#[deprecated = "Use `consumers` instead"]
1484	pub fn refs(who: &T::AccountId) -> RefCount {
1485		Self::consumers(who)
1486	}
1487
1488	/// True if the account has no outstanding references.
1489	#[deprecated = "Use `!is_provider_required` instead"]
1490	pub fn allow_death(who: &T::AccountId) -> bool {
1491		!Self::is_provider_required(who)
1492	}
1493
1494	/// Increment the provider reference counter on an account.
1495	pub fn inc_providers(who: &T::AccountId) -> IncRefStatus {
1496		Account::<T>::mutate(who, |a| {
1497			if a.providers == 0 && a.sufficients == 0 {
1498				// Account is being created.
1499				a.providers = 1;
1500				Self::on_created_account(who.clone(), a);
1501				IncRefStatus::Created
1502			} else {
1503				a.providers = a.providers.saturating_add(1);
1504				IncRefStatus::Existed
1505			}
1506		})
1507	}
1508
1509	/// Decrement the provider reference counter on an account.
1510	///
1511	/// This *MUST* only be done once for every time you called `inc_providers` on `who`.
1512	pub fn dec_providers(who: &T::AccountId) -> Result<DecRefStatus, DispatchError> {
1513		Account::<T>::try_mutate_exists(who, |maybe_account| {
1514			if let Some(mut account) = maybe_account.take() {
1515				if account.providers == 0 {
1516					// Logic error - cannot decrement beyond zero.
1517					log::error!(
1518						target: LOG_TARGET,
1519						"Logic error: Unexpected underflow in reducing provider",
1520					);
1521					account.providers = 1;
1522				}
1523				match (account.providers, account.consumers, account.sufficients) {
1524					(1, 0, 0) => {
1525						// No providers left (and no consumers) and no sufficients. Account dead.
1526
1527						Pallet::<T>::on_killed_account(who.clone());
1528						Ok(DecRefStatus::Reaped)
1529					},
1530					(1, c, _) if c > 0 => {
1531						// Cannot remove last provider if there are consumers.
1532						Err(DispatchError::ConsumerRemaining)
1533					},
1534					(x, _, _) => {
1535						// Account will continue to exist as there is either > 1 provider or
1536						// > 0 sufficients.
1537						account.providers = x - 1;
1538						*maybe_account = Some(account);
1539						Ok(DecRefStatus::Exists)
1540					},
1541				}
1542			} else {
1543				log::error!(
1544					target: LOG_TARGET,
1545					"Logic error: Account already dead when reducing provider",
1546				);
1547				Ok(DecRefStatus::Reaped)
1548			}
1549		})
1550	}
1551
1552	/// Increment the self-sufficient reference counter on an account.
1553	pub fn inc_sufficients(who: &T::AccountId) -> IncRefStatus {
1554		Account::<T>::mutate(who, |a| {
1555			if a.providers + a.sufficients == 0 {
1556				// Account is being created.
1557				a.sufficients = 1;
1558				Self::on_created_account(who.clone(), a);
1559				IncRefStatus::Created
1560			} else {
1561				a.sufficients = a.sufficients.saturating_add(1);
1562				IncRefStatus::Existed
1563			}
1564		})
1565	}
1566
1567	/// Decrement the sufficients reference counter on an account.
1568	///
1569	/// This *MUST* only be done once for every time you called `inc_sufficients` on `who`.
1570	pub fn dec_sufficients(who: &T::AccountId) -> DecRefStatus {
1571		Account::<T>::mutate_exists(who, |maybe_account| {
1572			if let Some(mut account) = maybe_account.take() {
1573				if account.sufficients == 0 {
1574					// Logic error - cannot decrement beyond zero.
1575					log::error!(
1576						target: LOG_TARGET,
1577						"Logic error: Unexpected underflow in reducing sufficients",
1578					);
1579				}
1580				match (account.sufficients, account.providers) {
1581					(0, 0) | (1, 0) => {
1582						Pallet::<T>::on_killed_account(who.clone());
1583						DecRefStatus::Reaped
1584					},
1585					(x, _) => {
1586						account.sufficients = x - 1;
1587						*maybe_account = Some(account);
1588						DecRefStatus::Exists
1589					},
1590				}
1591			} else {
1592				log::error!(
1593					target: LOG_TARGET,
1594					"Logic error: Account already dead when reducing provider",
1595				);
1596				DecRefStatus::Reaped
1597			}
1598		})
1599	}
1600
1601	/// The number of outstanding provider references for the account `who`.
1602	pub fn providers(who: &T::AccountId) -> RefCount {
1603		Account::<T>::get(who).providers
1604	}
1605
1606	/// The number of outstanding sufficient references for the account `who`.
1607	pub fn sufficients(who: &T::AccountId) -> RefCount {
1608		Account::<T>::get(who).sufficients
1609	}
1610
1611	/// The number of outstanding provider and sufficient references for the account `who`.
1612	pub fn reference_count(who: &T::AccountId) -> RefCount {
1613		let a = Account::<T>::get(who);
1614		a.providers + a.sufficients
1615	}
1616
1617	/// Increment the reference counter on an account.
1618	///
1619	/// The account `who`'s `providers` must be non-zero and the current number of consumers must
1620	/// be less than `MaxConsumers::max_consumers()` or this will return an error.
1621	pub fn inc_consumers(who: &T::AccountId) -> Result<(), DispatchError> {
1622		Account::<T>::try_mutate(who, |a| {
1623			if a.providers > 0 {
1624				if a.consumers < T::MaxConsumers::max_consumers() {
1625					a.consumers = a.consumers.saturating_add(1);
1626					Ok(())
1627				} else {
1628					Err(DispatchError::TooManyConsumers)
1629				}
1630			} else {
1631				Err(DispatchError::NoProviders)
1632			}
1633		})
1634	}
1635
1636	/// Increment the reference counter on an account, ignoring the `MaxConsumers` limits.
1637	///
1638	/// The account `who`'s `providers` must be non-zero or this will return an error.
1639	pub fn inc_consumers_without_limit(who: &T::AccountId) -> Result<(), DispatchError> {
1640		Account::<T>::try_mutate(who, |a| {
1641			if a.providers > 0 {
1642				a.consumers = a.consumers.saturating_add(1);
1643				Ok(())
1644			} else {
1645				Err(DispatchError::NoProviders)
1646			}
1647		})
1648	}
1649
1650	/// Decrement the reference counter on an account. This *MUST* only be done once for every time
1651	/// you called `inc_consumers` on `who`.
1652	pub fn dec_consumers(who: &T::AccountId) {
1653		Account::<T>::mutate(who, |a| {
1654			if a.consumers > 0 {
1655				a.consumers -= 1;
1656			} else {
1657				log::error!(
1658					target: LOG_TARGET,
1659					"Logic error: Unexpected underflow in reducing consumer",
1660				);
1661			}
1662		})
1663	}
1664
1665	/// The number of outstanding references for the account `who`.
1666	pub fn consumers(who: &T::AccountId) -> RefCount {
1667		Account::<T>::get(who).consumers
1668	}
1669
1670	/// True if the account has some outstanding consumer references.
1671	pub fn is_provider_required(who: &T::AccountId) -> bool {
1672		Account::<T>::get(who).consumers != 0
1673	}
1674
1675	/// True if the account has no outstanding consumer references or more than one provider.
1676	pub fn can_dec_provider(who: &T::AccountId) -> bool {
1677		let a = Account::<T>::get(who);
1678		a.consumers == 0 || a.providers > 1
1679	}
1680
1681	/// True if the account has at least one provider reference and adding `amount` consumer
1682	/// references would not take it above the the maximum.
1683	pub fn can_accrue_consumers(who: &T::AccountId, amount: u32) -> bool {
1684		let a = Account::<T>::get(who);
1685		match a.consumers.checked_add(amount) {
1686			Some(c) => a.providers > 0 && c <= T::MaxConsumers::max_consumers(),
1687			None => false,
1688		}
1689	}
1690
1691	/// True if the account has at least one provider reference and fewer consumer references than
1692	/// the maximum.
1693	pub fn can_inc_consumer(who: &T::AccountId) -> bool {
1694		Self::can_accrue_consumers(who, 1)
1695	}
1696
1697	/// Deposits an event into this block's event record.
1698	///
1699	/// NOTE: Events not registered at the genesis block and quietly omitted.
1700	pub fn deposit_event(event: impl Into<T::RuntimeEvent>) {
1701		Self::deposit_event_indexed(&[], event.into());
1702	}
1703
1704	/// Deposits an event into this block's event record adding this event
1705	/// to the corresponding topic indexes.
1706	///
1707	/// This will update storage entries that correspond to the specified topics.
1708	/// It is expected that light-clients could subscribe to this topics.
1709	///
1710	/// NOTE: Events not registered at the genesis block and quietly omitted.
1711	pub fn deposit_event_indexed(topics: &[T::Hash], event: T::RuntimeEvent) {
1712		let block_number = Self::block_number();
1713
1714		// Don't populate events on genesis.
1715		if block_number.is_zero() {
1716			return
1717		}
1718
1719		let phase = ExecutionPhase::<T>::get().unwrap_or_default();
1720		let event = EventRecord { phase, event, topics: topics.to_vec() };
1721
1722		// Index of the event to be added.
1723		let event_idx = {
1724			let old_event_count = EventCount::<T>::get();
1725			let new_event_count = match old_event_count.checked_add(1) {
1726				// We've reached the maximum number of events at this block, just
1727				// don't do anything and leave the event_count unaltered.
1728				None => return,
1729				Some(nc) => nc,
1730			};
1731			EventCount::<T>::put(new_event_count);
1732			old_event_count
1733		};
1734
1735		Events::<T>::append(event);
1736
1737		for topic in topics {
1738			<EventTopics<T>>::append(topic, &(block_number, event_idx));
1739		}
1740	}
1741
1742	/// Gets the index of extrinsic that is currently executing.
1743	pub fn extrinsic_index() -> Option<u32> {
1744		storage::unhashed::get(well_known_keys::EXTRINSIC_INDEX)
1745	}
1746
1747	/// Gets extrinsics count.
1748	pub fn extrinsic_count() -> u32 {
1749		ExtrinsicCount::<T>::get().unwrap_or_default()
1750	}
1751
1752	pub fn all_extrinsics_len() -> u32 {
1753		AllExtrinsicsLen::<T>::get().unwrap_or_default()
1754	}
1755
1756	/// Inform the system pallet of some additional weight that should be accounted for, in the
1757	/// current block.
1758	///
1759	/// NOTE: use with extra care; this function is made public only be used for certain pallets
1760	/// that need it. A runtime that does not have dynamic calls should never need this and should
1761	/// stick to static weights. A typical use case for this is inner calls or smart contract calls.
1762	/// Furthermore, it only makes sense to use this when it is presumably  _cheap_ to provide the
1763	/// argument `weight`; In other words, if this function is to be used to account for some
1764	/// unknown, user provided call's weight, it would only make sense to use it if you are sure you
1765	/// can rapidly compute the weight of the inner call.
1766	///
1767	/// Even more dangerous is to note that this function does NOT take any action, if the new sum
1768	/// of block weight is more than the block weight limit. This is what the _unchecked_.
1769	///
1770	/// Another potential use-case could be for the `on_initialize` and `on_finalize` hooks.
1771	pub fn register_extra_weight_unchecked(weight: Weight, class: DispatchClass) {
1772		BlockWeight::<T>::mutate(|current_weight| {
1773			current_weight.accrue(weight, class);
1774		});
1775	}
1776
1777	/// Start the execution of a particular block.
1778	pub fn initialize(number: &BlockNumberFor<T>, parent_hash: &T::Hash, digest: &generic::Digest) {
1779		// populate environment
1780		ExecutionPhase::<T>::put(Phase::Initialization);
1781		storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &0u32);
1782		let entropy = (b"frame_system::initialize", parent_hash).using_encoded(blake2_256);
1783		storage::unhashed::put_raw(well_known_keys::INTRABLOCK_ENTROPY, &entropy[..]);
1784		<Number<T>>::put(number);
1785		<Digest<T>>::put(digest);
1786		<ParentHash<T>>::put(parent_hash);
1787		<BlockHash<T>>::insert(*number - One::one(), parent_hash);
1788		<InherentsApplied<T>>::kill();
1789
1790		// Remove previous block data from storage
1791		BlockWeight::<T>::kill();
1792	}
1793
1794	/// Remove temporary "environment" entries in storage, compute the storage root and return the
1795	/// resulting header for this block.
1796	pub fn finalize() -> HeaderFor<T> {
1797		log::debug!(
1798			target: LOG_TARGET,
1799			"[{:?}] {} extrinsics, length: {} (normal {}%, op: {}%, mandatory {}%) / normal weight:\
1800			 {} ({}%) op weight {} ({}%) / mandatory weight {} ({}%)",
1801			Self::block_number(),
1802			Self::extrinsic_count(),
1803			Self::all_extrinsics_len(),
1804			sp_runtime::Percent::from_rational(
1805				Self::all_extrinsics_len(),
1806				*T::BlockLength::get().max.get(DispatchClass::Normal)
1807			).deconstruct(),
1808			sp_runtime::Percent::from_rational(
1809				Self::all_extrinsics_len(),
1810				*T::BlockLength::get().max.get(DispatchClass::Operational)
1811			).deconstruct(),
1812			sp_runtime::Percent::from_rational(
1813				Self::all_extrinsics_len(),
1814				*T::BlockLength::get().max.get(DispatchClass::Mandatory)
1815			).deconstruct(),
1816			Self::block_weight().get(DispatchClass::Normal),
1817			sp_runtime::Percent::from_rational(
1818				Self::block_weight().get(DispatchClass::Normal).ref_time(),
1819				T::BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap_or(Bounded::max_value()).ref_time()
1820			).deconstruct(),
1821			Self::block_weight().get(DispatchClass::Operational),
1822			sp_runtime::Percent::from_rational(
1823				Self::block_weight().get(DispatchClass::Operational).ref_time(),
1824				T::BlockWeights::get().get(DispatchClass::Operational).max_total.unwrap_or(Bounded::max_value()).ref_time()
1825			).deconstruct(),
1826			Self::block_weight().get(DispatchClass::Mandatory),
1827			sp_runtime::Percent::from_rational(
1828				Self::block_weight().get(DispatchClass::Mandatory).ref_time(),
1829				T::BlockWeights::get().get(DispatchClass::Mandatory).max_total.unwrap_or(Bounded::max_value()).ref_time()
1830			).deconstruct(),
1831		);
1832		ExecutionPhase::<T>::kill();
1833		AllExtrinsicsLen::<T>::kill();
1834		storage::unhashed::kill(well_known_keys::INTRABLOCK_ENTROPY);
1835		InherentsApplied::<T>::kill();
1836
1837		// The following fields
1838		//
1839		// - <Events<T>>
1840		// - <EventCount<T>>
1841		// - <EventTopics<T>>
1842		// - <Number<T>>
1843		// - <ParentHash<T>>
1844		// - <Digest<T>>
1845		//
1846		// stay to be inspected by the client and will be cleared by `Self::initialize`.
1847		let number = <Number<T>>::get();
1848		let parent_hash = <ParentHash<T>>::get();
1849		let digest = <Digest<T>>::get();
1850
1851		let extrinsics = (0..ExtrinsicCount::<T>::take().unwrap_or_default())
1852			.map(ExtrinsicData::<T>::take)
1853			.collect();
1854		let extrinsics_root_state_version = T::Version::get().extrinsics_root_state_version();
1855		let extrinsics_root =
1856			extrinsics_data_root::<T::Hashing>(extrinsics, extrinsics_root_state_version);
1857
1858		// move block hash pruning window by one block
1859		let block_hash_count = T::BlockHashCount::get();
1860		let to_remove = number.saturating_sub(block_hash_count).saturating_sub(One::one());
1861
1862		// keep genesis hash
1863		if !to_remove.is_zero() {
1864			<BlockHash<T>>::remove(to_remove);
1865		}
1866
1867		let version = T::Version::get().state_version();
1868		let storage_root = T::Hash::decode(&mut &sp_io::storage::root(version)[..])
1869			.expect("Node is configured to use the same hash; qed");
1870
1871		HeaderFor::<T>::new(number, extrinsics_root, storage_root, parent_hash, digest)
1872	}
1873
1874	/// Deposits a log and ensures it matches the block's log data.
1875	pub fn deposit_log(item: generic::DigestItem) {
1876		<Digest<T>>::append(item);
1877	}
1878
1879	/// Get the basic externalities for this pallet, useful for tests.
1880	#[cfg(any(feature = "std", test))]
1881	pub fn externalities() -> TestExternalities {
1882		TestExternalities::new(sp_core::storage::Storage {
1883			top: map![
1884				<BlockHash<T>>::hashed_key_for(BlockNumberFor::<T>::zero()) => [69u8; 32].encode(),
1885				<Number<T>>::hashed_key().to_vec() => BlockNumberFor::<T>::one().encode(),
1886				<ParentHash<T>>::hashed_key().to_vec() => [69u8; 32].encode()
1887			],
1888			children_default: map![],
1889		})
1890	}
1891
1892	/// Get the current events deposited by the runtime.
1893	///
1894	/// NOTE: This should only be used in tests. Reading events from the runtime can have a large
1895	/// impact on the PoV size of a block. Users should use alternative and well bounded storage
1896	/// items for any behavior like this.
1897	///
1898	/// NOTE: Events not registered at the genesis block and quietly omitted.
1899	#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
1900	pub fn events() -> Vec<EventRecord<T::RuntimeEvent, T::Hash>> {
1901		// Dereferencing the events here is fine since we are not in the memory-restricted runtime.
1902		Self::read_events_no_consensus().map(|e| *e).collect()
1903	}
1904
1905	/// Get a single event at specified index.
1906	///
1907	/// Should only be called if you know what you are doing and outside of the runtime block
1908	/// execution else it can have a large impact on the PoV size of a block.
1909	pub fn event_no_consensus(index: usize) -> Option<T::RuntimeEvent> {
1910		Self::read_events_no_consensus().nth(index).map(|e| e.event.clone())
1911	}
1912
1913	/// Get the current events deposited by the runtime.
1914	///
1915	/// Should only be called if you know what you are doing and outside of the runtime block
1916	/// execution else it can have a large impact on the PoV size of a block.
1917	pub fn read_events_no_consensus(
1918	) -> impl Iterator<Item = Box<EventRecord<T::RuntimeEvent, T::Hash>>> {
1919		Events::<T>::stream_iter()
1920	}
1921
1922	/// Read and return the events of a specific pallet, as denoted by `E`.
1923	///
1924	/// This is useful for a pallet that wishes to read only the events it has deposited into
1925	/// `frame_system` using the standard `fn deposit_event`.
1926	pub fn read_events_for_pallet<E>() -> Vec<E>
1927	where
1928		T::RuntimeEvent: TryInto<E>,
1929	{
1930		Events::<T>::get()
1931			.into_iter()
1932			.map(|er| er.event)
1933			.filter_map(|e| e.try_into().ok())
1934			.collect::<_>()
1935	}
1936
1937	/// Set the block number to something in particular. Can be used as an alternative to
1938	/// `initialize` for tests that don't need to bother with the other environment entries.
1939	#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
1940	pub fn set_block_number(n: BlockNumberFor<T>) {
1941		<Number<T>>::put(n);
1942	}
1943
1944	/// Sets the index of extrinsic that is currently executing.
1945	#[cfg(any(feature = "std", test))]
1946	pub fn set_extrinsic_index(extrinsic_index: u32) {
1947		storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &extrinsic_index)
1948	}
1949
1950	/// Set the parent hash number to something in particular. Can be used as an alternative to
1951	/// `initialize` for tests that don't need to bother with the other environment entries.
1952	#[cfg(any(feature = "std", test))]
1953	pub fn set_parent_hash(n: T::Hash) {
1954		<ParentHash<T>>::put(n);
1955	}
1956
1957	/// Set the current block weight. This should only be used in some integration tests.
1958	#[cfg(any(feature = "std", test))]
1959	pub fn set_block_consumed_resources(weight: Weight, len: usize) {
1960		BlockWeight::<T>::mutate(|current_weight| {
1961			current_weight.set(weight, DispatchClass::Normal)
1962		});
1963		AllExtrinsicsLen::<T>::put(len as u32);
1964	}
1965
1966	/// Reset events.
1967	///
1968	/// This needs to be used in prior calling [`initialize`](Self::initialize) for each new block
1969	/// to clear events from previous block.
1970	pub fn reset_events() {
1971		<Events<T>>::kill();
1972		EventCount::<T>::kill();
1973		let _ = <EventTopics<T>>::clear(u32::max_value(), None);
1974	}
1975
1976	/// Assert the given `event` exists.
1977	///
1978	/// NOTE: Events not registered at the genesis block and quietly omitted.
1979	#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
1980	pub fn assert_has_event(event: T::RuntimeEvent) {
1981		let events = Self::events();
1982		assert!(
1983			events.iter().any(|record| record.event == event),
1984			"expected event {event:?} not found in events {events:?}",
1985		);
1986	}
1987
1988	/// Assert the last event equal to the given `event`.
1989	///
1990	/// NOTE: Events not registered at the genesis block and quietly omitted.
1991	#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
1992	pub fn assert_last_event(event: T::RuntimeEvent) {
1993		let last_event = Self::events().last().expect("events expected").event.clone();
1994		assert_eq!(
1995			last_event, event,
1996			"expected event {event:?} is not equal to the last event {last_event:?}",
1997		);
1998	}
1999
2000	/// Return the chain's current runtime version.
2001	pub fn runtime_version() -> RuntimeVersion {
2002		T::Version::get()
2003	}
2004
2005	/// Retrieve the account transaction counter from storage.
2006	pub fn account_nonce(who: impl EncodeLike<T::AccountId>) -> T::Nonce {
2007		Account::<T>::get(who).nonce
2008	}
2009
2010	/// Increment a particular account's nonce by 1.
2011	pub fn inc_account_nonce(who: impl EncodeLike<T::AccountId>) {
2012		Account::<T>::mutate(who, |a| a.nonce += T::Nonce::one());
2013	}
2014
2015	/// Note what the extrinsic data of the current extrinsic index is.
2016	///
2017	/// This is required to be called before applying an extrinsic. The data will used
2018	/// in [`Self::finalize`] to calculate the correct extrinsics root.
2019	pub fn note_extrinsic(encoded_xt: Vec<u8>) {
2020		ExtrinsicData::<T>::insert(Self::extrinsic_index().unwrap_or_default(), encoded_xt);
2021	}
2022
2023	/// To be called immediately after an extrinsic has been applied.
2024	///
2025	/// Emits an `ExtrinsicSuccess` or `ExtrinsicFailed` event depending on the outcome.
2026	/// The emitted event contains the post-dispatch corrected weight including
2027	/// the base-weight for its dispatch class.
2028	pub fn note_applied_extrinsic(r: &DispatchResultWithPostInfo, mut info: DispatchInfo) {
2029		info.weight = extract_actual_weight(r, &info)
2030			.saturating_add(T::BlockWeights::get().get(info.class).base_extrinsic);
2031		info.pays_fee = extract_actual_pays_fee(r, &info);
2032
2033		Self::deposit_event(match r {
2034			Ok(_) => Event::ExtrinsicSuccess { dispatch_info: info },
2035			Err(err) => {
2036				log::trace!(
2037					target: LOG_TARGET,
2038					"Extrinsic failed at block({:?}): {:?}",
2039					Self::block_number(),
2040					err,
2041				);
2042				Event::ExtrinsicFailed { dispatch_error: err.error, dispatch_info: info }
2043			},
2044		});
2045
2046		let next_extrinsic_index = Self::extrinsic_index().unwrap_or_default() + 1u32;
2047
2048		storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &next_extrinsic_index);
2049		ExecutionPhase::<T>::put(Phase::ApplyExtrinsic(next_extrinsic_index));
2050	}
2051
2052	/// To be called immediately after `note_applied_extrinsic` of the last extrinsic of the block
2053	/// has been called.
2054	pub fn note_finished_extrinsics() {
2055		let extrinsic_index: u32 =
2056			storage::unhashed::take(well_known_keys::EXTRINSIC_INDEX).unwrap_or_default();
2057		ExtrinsicCount::<T>::put(extrinsic_index);
2058		ExecutionPhase::<T>::put(Phase::Finalization);
2059	}
2060
2061	/// To be called immediately after finishing the initialization of the block
2062	/// (e.g., called `on_initialize` for all pallets).
2063	pub fn note_finished_initialize() {
2064		ExecutionPhase::<T>::put(Phase::ApplyExtrinsic(0))
2065	}
2066
2067	/// An account is being created.
2068	pub fn on_created_account(who: T::AccountId, _a: &mut AccountInfo<T::Nonce, T::AccountData>) {
2069		T::OnNewAccount::on_new_account(&who);
2070		Self::deposit_event(Event::NewAccount { account: who });
2071	}
2072
2073	/// Do anything that needs to be done after an account has been killed.
2074	fn on_killed_account(who: T::AccountId) {
2075		T::OnKilledAccount::on_killed_account(&who);
2076		Self::deposit_event(Event::KilledAccount { account: who });
2077	}
2078
2079	/// Determine whether or not it is possible to update the code.
2080	///
2081	/// Checks the given code if it is a valid runtime wasm blob by instantiating
2082	/// it and extracting the runtime version of it. It checks that the runtime version
2083	/// of the old and new runtime has the same spec name and that the spec version is increasing.
2084	pub fn can_set_code(code: &[u8]) -> Result<(), sp_runtime::DispatchError> {
2085		if T::MultiBlockMigrator::ongoing() {
2086			return Err(Error::<T>::MultiBlockMigrationsOngoing.into())
2087		}
2088
2089		let current_version = T::Version::get();
2090		let new_version = sp_io::misc::runtime_version(code)
2091			.and_then(|v| RuntimeVersion::decode(&mut &v[..]).ok())
2092			.ok_or(Error::<T>::FailedToExtractRuntimeVersion)?;
2093
2094		cfg_if::cfg_if! {
2095			if #[cfg(all(feature = "runtime-benchmarks", not(test)))] {
2096					// Let's ensure the compiler doesn't optimize our fetching of the runtime version away.
2097					core::hint::black_box((new_version, current_version));
2098					Ok(())
2099			} else {
2100				if new_version.spec_name != current_version.spec_name {
2101					return Err(Error::<T>::InvalidSpecName.into())
2102				}
2103
2104				if new_version.spec_version <= current_version.spec_version {
2105					return Err(Error::<T>::SpecVersionNeedsToIncrease.into())
2106				}
2107
2108				Ok(())
2109			}
2110		}
2111	}
2112
2113	/// To be called after any origin/privilege checks. Put the code upgrade authorization into
2114	/// storage and emit an event. Infallible.
2115	pub fn do_authorize_upgrade(code_hash: T::Hash, check_version: bool) {
2116		AuthorizedUpgrade::<T>::put(CodeUpgradeAuthorization { code_hash, check_version });
2117		Self::deposit_event(Event::UpgradeAuthorized { code_hash, check_version });
2118	}
2119
2120	/// Apply an authorized upgrade, performing any validation checks, and remove the authorization.
2121	/// Whether or not the code is set directly depends on the `OnSetCode` configuration of the
2122	/// runtime.
2123	pub fn do_apply_authorize_upgrade(code: Vec<u8>) -> Result<PostDispatchInfo, DispatchError> {
2124		Self::validate_authorized_upgrade(&code[..])?;
2125		T::OnSetCode::set_code(code)?;
2126		AuthorizedUpgrade::<T>::kill();
2127		let post = PostDispatchInfo {
2128			// consume the rest of the block to prevent further transactions
2129			actual_weight: Some(T::BlockWeights::get().max_block),
2130			// no fee for valid upgrade
2131			pays_fee: Pays::No,
2132		};
2133		Ok(post)
2134	}
2135
2136	/// Check that provided `code` can be upgraded to. Namely, check that its hash matches an
2137	/// existing authorization and that it meets the specification requirements of `can_set_code`.
2138	pub fn validate_authorized_upgrade(code: &[u8]) -> Result<T::Hash, DispatchError> {
2139		let authorization = AuthorizedUpgrade::<T>::get().ok_or(Error::<T>::NothingAuthorized)?;
2140		let actual_hash = T::Hashing::hash(code);
2141		ensure!(actual_hash == authorization.code_hash, Error::<T>::Unauthorized);
2142		if authorization.check_version {
2143			Self::can_set_code(code)?
2144		}
2145		Ok(actual_hash)
2146	}
2147}
2148
2149/// Returns a 32 byte datum which is guaranteed to be universally unique. `entropy` is provided
2150/// as a facility to reduce the potential for precalculating results.
2151pub fn unique(entropy: impl Encode) -> [u8; 32] {
2152	let mut last = [0u8; 32];
2153	sp_io::storage::read(well_known_keys::INTRABLOCK_ENTROPY, &mut last[..], 0);
2154	let next = (b"frame_system::unique", entropy, last).using_encoded(blake2_256);
2155	sp_io::storage::set(well_known_keys::INTRABLOCK_ENTROPY, &next);
2156	next
2157}
2158
2159/// Event handler which registers a provider when created.
2160pub struct Provider<T>(PhantomData<T>);
2161impl<T: Config> HandleLifetime<T::AccountId> for Provider<T> {
2162	fn created(t: &T::AccountId) -> Result<(), DispatchError> {
2163		Pallet::<T>::inc_providers(t);
2164		Ok(())
2165	}
2166	fn killed(t: &T::AccountId) -> Result<(), DispatchError> {
2167		Pallet::<T>::dec_providers(t).map(|_| ())
2168	}
2169}
2170
2171/// Event handler which registers a self-sufficient when created.
2172pub struct SelfSufficient<T>(PhantomData<T>);
2173impl<T: Config> HandleLifetime<T::AccountId> for SelfSufficient<T> {
2174	fn created(t: &T::AccountId) -> Result<(), DispatchError> {
2175		Pallet::<T>::inc_sufficients(t);
2176		Ok(())
2177	}
2178	fn killed(t: &T::AccountId) -> Result<(), DispatchError> {
2179		Pallet::<T>::dec_sufficients(t);
2180		Ok(())
2181	}
2182}
2183
2184/// Event handler which registers a consumer when created.
2185pub struct Consumer<T>(PhantomData<T>);
2186impl<T: Config> HandleLifetime<T::AccountId> for Consumer<T> {
2187	fn created(t: &T::AccountId) -> Result<(), DispatchError> {
2188		Pallet::<T>::inc_consumers(t)
2189	}
2190	fn killed(t: &T::AccountId) -> Result<(), DispatchError> {
2191		Pallet::<T>::dec_consumers(t);
2192		Ok(())
2193	}
2194}
2195
2196impl<T: Config> BlockNumberProvider for Pallet<T> {
2197	type BlockNumber = BlockNumberFor<T>;
2198
2199	fn current_block_number() -> Self::BlockNumber {
2200		Pallet::<T>::block_number()
2201	}
2202
2203	#[cfg(feature = "runtime-benchmarks")]
2204	fn set_block_number(n: BlockNumberFor<T>) {
2205		Self::set_block_number(n)
2206	}
2207}
2208
2209/// Implement StoredMap for a simple single-item, provide-when-not-default system. This works fine
2210/// for storing a single item which allows the account to continue existing as long as it's not
2211/// empty/default.
2212///
2213/// Anything more complex will need more sophisticated logic.
2214impl<T: Config> StoredMap<T::AccountId, T::AccountData> for Pallet<T> {
2215	fn get(k: &T::AccountId) -> T::AccountData {
2216		Account::<T>::get(k).data
2217	}
2218
2219	fn try_mutate_exists<R, E: From<DispatchError>>(
2220		k: &T::AccountId,
2221		f: impl FnOnce(&mut Option<T::AccountData>) -> Result<R, E>,
2222	) -> Result<R, E> {
2223		let account = Account::<T>::get(k);
2224		let is_default = account.data == T::AccountData::default();
2225		let mut some_data = if is_default { None } else { Some(account.data) };
2226		let result = f(&mut some_data)?;
2227		if Self::providers(k) > 0 || Self::sufficients(k) > 0 {
2228			Account::<T>::mutate(k, |a| a.data = some_data.unwrap_or_default());
2229		} else {
2230			Account::<T>::remove(k)
2231		}
2232		Ok(result)
2233	}
2234}
2235
2236/// Split an `option` into two constituent options, as defined by a `splitter` function.
2237pub fn split_inner<T, R, S>(
2238	option: Option<T>,
2239	splitter: impl FnOnce(T) -> (R, S),
2240) -> (Option<R>, Option<S>) {
2241	match option {
2242		Some(inner) => {
2243			let (r, s) = splitter(inner);
2244			(Some(r), Some(s))
2245		},
2246		None => (None, None),
2247	}
2248}
2249
2250pub struct ChainContext<T>(PhantomData<T>);
2251impl<T> Default for ChainContext<T> {
2252	fn default() -> Self {
2253		ChainContext(PhantomData)
2254	}
2255}
2256
2257impl<T: Config> Lookup for ChainContext<T> {
2258	type Source = <T::Lookup as StaticLookup>::Source;
2259	type Target = <T::Lookup as StaticLookup>::Target;
2260
2261	fn lookup(&self, s: Self::Source) -> Result<Self::Target, LookupError> {
2262		<T::Lookup as StaticLookup>::lookup(s)
2263	}
2264}
2265
2266/// Prelude to be used alongside pallet macro, for ease of use.
2267pub mod pallet_prelude {
2268	pub use crate::{ensure_none, ensure_root, ensure_signed, ensure_signed_or_root};
2269
2270	/// Type alias for the `Origin` associated type of system config.
2271	pub type OriginFor<T> = <T as crate::Config>::RuntimeOrigin;
2272
2273	/// Type alias for the `Header`.
2274	pub type HeaderFor<T> =
2275		<<T as crate::Config>::Block as sp_runtime::traits::HeaderProvider>::HeaderT;
2276
2277	/// Type alias for the `BlockNumber` associated type of system config.
2278	pub type BlockNumberFor<T> = <HeaderFor<T> as sp_runtime::traits::Header>::Number;
2279
2280	/// Type alias for the `Extrinsic` associated type of system config.
2281	pub type ExtrinsicFor<T> =
2282		<<T as crate::Config>::Block as sp_runtime::traits::Block>::Extrinsic;
2283
2284	/// Type alias for the `RuntimeCall` associated type of system config.
2285	pub type RuntimeCallFor<T> = <T as crate::Config>::RuntimeCall;
2286}