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