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