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