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

            
100
extern crate alloc;
101

            
102
use alloc::{boxed::Box, vec, vec::Vec};
103
use core::{fmt::Debug, marker::PhantomData};
104
use pallet_prelude::{BlockNumberFor, HeaderFor};
105
#[cfg(feature = "std")]
106
use serde::Serialize;
107
use sp_io::hashing::blake2_256;
108
#[cfg(feature = "runtime-benchmarks")]
109
use sp_runtime::traits::TrailingZeroInput;
110
use sp_runtime::{
111
	generic,
112
	traits::{
113
		self, AtLeast32Bit, BadOrigin, BlockNumberProvider, Bounded, CheckEqual, Dispatchable,
114
		Hash, Header, Lookup, LookupError, MaybeDisplay, MaybeSerializeDeserialize, Member, One,
115
		Saturating, SimpleBitOps, StaticLookup, Zero,
116
	},
117
	transaction_validity::{
118
		InvalidTransaction, TransactionLongevity, TransactionSource, TransactionValidity,
119
		ValidTransaction,
120
	},
121
	DispatchError, RuntimeDebug,
122
};
123
#[cfg(any(feature = "std", test))]
124
use sp_std::map;
125
use sp_version::RuntimeVersion;
126

            
127
use codec::{Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen};
128
#[cfg(feature = "std")]
129
use frame_support::traits::BuildGenesisConfig;
130
use frame_support::{
131
	dispatch::{
132
		extract_actual_pays_fee, extract_actual_weight, DispatchClass, DispatchInfo,
133
		DispatchResult, DispatchResultWithPostInfo, PerDispatchClass, PostDispatchInfo,
134
	},
135
	ensure, impl_ensure_origin_with_arg_ignoring_arg,
136
	migrations::MultiStepMigrator,
137
	pallet_prelude::Pays,
138
	storage::{self, StorageStreamIter},
139
	traits::{
140
		ConstU32, Contains, EnsureOrigin, EnsureOriginWithArg, Get, HandleLifetime,
141
		OnKilledAccount, OnNewAccount, OnRuntimeUpgrade, OriginTrait, PalletInfo, SortedMembers,
142
		StoredMap, TypedGet,
143
	},
144
	Parameter,
145
};
146
use scale_info::TypeInfo;
147
use sp_core::storage::well_known_keys;
148
use sp_weights::{RuntimeDbWeight, Weight};
149

            
150
#[cfg(any(feature = "std", test))]
151
use sp_io::TestExternalities;
152

            
153
pub mod limits;
154
#[cfg(test)]
155
pub(crate) mod mock;
156

            
157
pub mod offchain;
158

            
159
mod extensions;
160
#[cfg(feature = "std")]
161
pub mod mocking;
162
#[cfg(test)]
163
mod tests;
164
pub mod weights;
165

            
166
pub mod migrations;
167

            
168
pub use extensions::{
169
	check_genesis::CheckGenesis, check_mortality::CheckMortality,
170
	check_non_zero_sender::CheckNonZeroSender, check_nonce::CheckNonce,
171
	check_spec_version::CheckSpecVersion, check_tx_version::CheckTxVersion,
172
	check_weight::CheckWeight,
173
};
174
// Backward compatible re-export.
175
pub use extensions::check_mortality::CheckMortality as CheckEra;
176
pub use frame_support::dispatch::RawOrigin;
177
use frame_support::traits::{PostInherents, PostTransactions, PreInherents};
178
pub use weights::WeightInfo;
179

            
180
const LOG_TARGET: &str = "runtime::system";
181

            
182
/// Compute the trie root of a list of extrinsics.
183
///
184
/// The merkle proof is using the same trie as runtime state with
185
/// `state_version` 0.
186
pub fn extrinsics_root<H: Hash, E: codec::Encode>(extrinsics: &[E]) -> H::Output {
187
	extrinsics_data_root::<H>(extrinsics.iter().map(codec::Encode::encode).collect())
188
}
189

            
190
/// Compute the trie root of a list of extrinsics.
191
///
192
/// The merkle proof is using the same trie as runtime state with
193
/// `state_version` 0.
194
194763
pub fn extrinsics_data_root<H: Hash>(xts: Vec<Vec<u8>>) -> H::Output {
195
194763
	H::ordered_trie_root(xts, sp_core::storage::StateVersion::V0)
196
194763
}
197

            
198
/// An object to track the currently used extrinsic weight in a block.
199
pub type ConsumedWeight = PerDispatchClass<Weight>;
200

            
201
pub use pallet::*;
202

            
203
/// Do something when we should be setting the code.
204
pub trait SetCode<T: Config> {
205
	/// Set the code to the given blob.
206
	fn set_code(code: Vec<u8>) -> DispatchResult;
207
}
208

            
209
impl<T: Config> SetCode<T> for () {
210
	fn set_code(code: Vec<u8>) -> DispatchResult {
211
		<Pallet<T>>::update_code_in_storage(&code);
212
		Ok(())
213
	}
214
}
215

            
216
/// Numeric limits over the ability to add a consumer ref using `inc_consumers`.
217
pub trait ConsumerLimits {
218
	/// The number of consumers over which `inc_consumers` will cease to work.
219
	fn max_consumers() -> RefCount;
220
	/// The maximum number of additional consumers expected to be over be added at once using
221
	/// `inc_consumers_without_limit`.
222
	///
223
	/// Note: This is not enforced and it's up to the chain's author to ensure this reflects the
224
	/// actual situation.
225
	fn max_overflow() -> RefCount;
226
}
227

            
228
impl<const Z: u32> ConsumerLimits for ConstU32<Z> {
229
5856
	fn max_consumers() -> RefCount {
230
5856
		Z
231
5856
	}
232
	fn max_overflow() -> RefCount {
233
		Z
234
	}
235
}
236

            
237
impl<MaxNormal: Get<u32>, MaxOverflow: Get<u32>> ConsumerLimits for (MaxNormal, MaxOverflow) {
238
	fn max_consumers() -> RefCount {
239
		MaxNormal::get()
240
	}
241
	fn max_overflow() -> RefCount {
242
		MaxOverflow::get()
243
	}
244
}
245

            
246
/// Information needed when a new runtime binary is submitted and needs to be authorized before
247
/// replacing the current runtime.
248
#[derive(Decode, Encode, Default, PartialEq, Eq, MaxEncodedLen, TypeInfo)]
249
#[scale_info(skip_type_params(T))]
250
pub struct CodeUpgradeAuthorization<T>
251
where
252
	T: Config,
253
{
254
	/// Hash of the new runtime binary.
255
	code_hash: T::Hash,
256
	/// Whether or not to carry out version checks.
257
	check_version: bool,
258
}
259

            
260
2526
#[frame_support::pallet]
261
pub mod pallet {
262
	use crate::{self as frame_system, pallet_prelude::*, *};
263
	use frame_support::pallet_prelude::*;
264

            
265
	/// Default implementations of [`DefaultConfig`], which can be used to implement [`Config`].
266
	pub mod config_preludes {
267
		use super::{inject_runtime_type, DefaultConfig};
268
		use frame_support::{derive_impl, traits::Get};
269

            
270
		/// A predefined adapter that covers `BlockNumberFor<T>` for `Config::Block::BlockNumber` of
271
		/// the types `u32`, `u64`, and `u128`.
272
		///
273
		/// NOTE: Avoids overriding `BlockHashCount` when using `mocking::{MockBlock, MockBlockU32,
274
		/// MockBlockU128}`.
275
		pub struct TestBlockHashCount<C: Get<u32>>(core::marker::PhantomData<C>);
276
		impl<I: From<u32>, C: Get<u32>> Get<I> for TestBlockHashCount<C> {
277
			fn get() -> I {
278
				C::get().into()
279
			}
280
		}
281

            
282
		/// Provides a viable default config that can be used with
283
		/// [`derive_impl`](`frame_support::derive_impl`) to derive a testing pallet config
284
		/// based on this one.
285
		///
286
		/// See `Test` in the `default-config` example pallet's `test.rs` for an example of
287
		/// a downstream user of this particular `TestDefaultConfig`
288
		pub struct TestDefaultConfig;
289

            
290
		#[frame_support::register_default_impl(TestDefaultConfig)]
291
		impl DefaultConfig for TestDefaultConfig {
292
			type Nonce = u32;
293
			type Hash = sp_core::hash::H256;
294
			type Hashing = sp_runtime::traits::BlakeTwo256;
295
			type AccountId = u64;
296
			type Lookup = sp_runtime::traits::IdentityLookup<u64>;
297
			type MaxConsumers = frame_support::traits::ConstU32<16>;
298
			type AccountData = ();
299
			type OnNewAccount = ();
300
			type OnKilledAccount = ();
301
			type SystemWeightInfo = ();
302
			type SS58Prefix = ();
303
			type Version = ();
304
			type BlockWeights = ();
305
			type BlockLength = ();
306
			type DbWeight = ();
307
			#[inject_runtime_type]
308
			type RuntimeEvent = ();
309
			#[inject_runtime_type]
310
			type RuntimeOrigin = ();
311
			#[inject_runtime_type]
312
			type RuntimeCall = ();
313
			#[inject_runtime_type]
314
			type PalletInfo = ();
315
			#[inject_runtime_type]
316
			type RuntimeTask = ();
317
			type BaseCallFilter = frame_support::traits::Everything;
318
			type BlockHashCount = TestBlockHashCount<frame_support::traits::ConstU32<10>>;
319
			type OnSetCode = ();
320
			type SingleBlockMigrations = ();
321
			type MultiBlockMigrator = ();
322
			type PreInherents = ();
323
			type PostInherents = ();
324
			type PostTransactions = ();
325
		}
326

            
327
		/// Default configurations of this pallet in a solochain environment.
328
		///
329
		/// ## Considerations:
330
		///
331
		/// By default, this type makes the following choices:
332
		///
333
		/// * Use a normal 32 byte account id, with a [`DefaultConfig::Lookup`] that implies no
334
		///   'account-indexing' pallet is being used.
335
		/// * Given that we don't know anything about the existence of a currency system in scope,
336
		///   an [`DefaultConfig::AccountData`] is chosen that has no addition data. Overwrite this
337
		///   if you use `pallet-balances` or similar.
338
		/// * Make sure to overwrite [`DefaultConfig::Version`].
339
		/// * 2s block time, and a default 5mb block size is used.
340
		pub struct SolochainDefaultConfig;
341

            
342
		#[frame_support::register_default_impl(SolochainDefaultConfig)]
343
		impl DefaultConfig for SolochainDefaultConfig {
344
			/// The default type for storing how many extrinsics an account has signed.
345
			type Nonce = u32;
346

            
347
			/// The default type for hashing blocks and tries.
348
			type Hash = sp_core::hash::H256;
349

            
350
			/// The default hashing algorithm used.
351
			type Hashing = sp_runtime::traits::BlakeTwo256;
352

            
353
			/// The default identifier used to distinguish between accounts.
354
			type AccountId = sp_runtime::AccountId32;
355

            
356
			/// The lookup mechanism to get account ID from whatever is passed in dispatchers.
357
			type Lookup = sp_runtime::traits::AccountIdLookup<Self::AccountId, ()>;
358

            
359
			/// The maximum number of consumers allowed on a single account. Using 128 as default.
360
			type MaxConsumers = frame_support::traits::ConstU32<128>;
361

            
362
			/// The default data to be stored in an account.
363
			type AccountData = crate::AccountInfo<Self::Nonce, ()>;
364

            
365
			/// What to do if a new account is created.
366
			type OnNewAccount = ();
367

            
368
			/// What to do if an account is fully reaped from the system.
369
			type OnKilledAccount = ();
370

            
371
			/// Weight information for the extrinsics of this pallet.
372
			type SystemWeightInfo = ();
373

            
374
			/// This is used as an identifier of the chain.
375
			type SS58Prefix = ();
376

            
377
			/// Version of the runtime.
378
			type Version = ();
379

            
380
			/// Block & extrinsics weights: base values and limits.
381
			type BlockWeights = ();
382

            
383
			/// The maximum length of a block (in bytes).
384
			type BlockLength = ();
385

            
386
			/// The weight of database operations that the runtime can invoke.
387
			type DbWeight = ();
388

            
389
			/// The ubiquitous event type injected by `construct_runtime!`.
390
			#[inject_runtime_type]
391
			type RuntimeEvent = ();
392

            
393
			/// The ubiquitous origin type injected by `construct_runtime!`.
394
			#[inject_runtime_type]
395
			type RuntimeOrigin = ();
396

            
397
			/// The aggregated dispatch type available for extrinsics, injected by
398
			/// `construct_runtime!`.
399
			#[inject_runtime_type]
400
			type RuntimeCall = ();
401

            
402
			/// The aggregated Task type, injected by `construct_runtime!`.
403
			#[inject_runtime_type]
404
			type RuntimeTask = ();
405

            
406
			/// Converts a module to the index of the module, injected by `construct_runtime!`.
407
			#[inject_runtime_type]
408
			type PalletInfo = ();
409

            
410
			/// The basic call filter to use in dispatchable. Supports everything as the default.
411
			type BaseCallFilter = frame_support::traits::Everything;
412

            
413
			/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
414
			/// Using 256 as default.
415
			type BlockHashCount = TestBlockHashCount<frame_support::traits::ConstU32<256>>;
416

            
417
			/// The set code logic, just the default since we're not a parachain.
418
			type OnSetCode = ();
419
			type SingleBlockMigrations = ();
420
			type MultiBlockMigrator = ();
421
			type PreInherents = ();
422
			type PostInherents = ();
423
			type PostTransactions = ();
424
		}
425

            
426
		/// Default configurations of this pallet in a relay-chain environment.
427
		pub struct RelayChainDefaultConfig;
428

            
429
		/// It currently uses the same configuration as `SolochainDefaultConfig`.
430
		#[derive_impl(SolochainDefaultConfig as DefaultConfig, no_aggregated_types)]
431
		#[frame_support::register_default_impl(RelayChainDefaultConfig)]
432
		impl DefaultConfig for RelayChainDefaultConfig {}
433

            
434
		/// Default configurations of this pallet in a parachain environment.
435
		pub struct ParaChainDefaultConfig;
436

            
437
		/// It currently uses the same configuration as `SolochainDefaultConfig`.
438
		#[derive_impl(SolochainDefaultConfig as DefaultConfig, no_aggregated_types)]
439
		#[frame_support::register_default_impl(ParaChainDefaultConfig)]
440
		impl DefaultConfig for ParaChainDefaultConfig {}
441
	}
442

            
443
	/// System configuration trait. Implemented by runtime.
444
	#[pallet::config(with_default)]
445
	#[pallet::disable_frame_system_supertrait_check]
446
	pub trait Config: 'static + Eq + Clone {
447
		/// The aggregated event type of the runtime.
448
		#[pallet::no_default_bounds]
449
		type RuntimeEvent: Parameter
450
			+ Member
451
			+ From<Event<Self>>
452
			+ Debug
453
			+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
454

            
455
		/// The basic call filter to use in Origin. All origins are built with this filter as base,
456
		/// except Root.
457
		///
458
		/// This works as a filter for each incoming call. The call needs to pass this filter in
459
		/// order to dispatch. Otherwise it will be rejected with `CallFiltered`. This can be
460
		/// bypassed via `dispatch_bypass_filter` which should only be accessible by root. The
461
		/// filter can be composed of sub-filters by nesting for example
462
		/// [`frame_support::traits::InsideBoth`], [`frame_support::traits::TheseExcept`] or
463
		/// [`frame_support::traits::EverythingBut`] et al. The default would be
464
		/// [`frame_support::traits::Everything`].
465
		#[pallet::no_default_bounds]
466
		type BaseCallFilter: Contains<Self::RuntimeCall>;
467

            
468
		/// Block & extrinsics weights: base values and limits.
469
		#[pallet::constant]
470
		type BlockWeights: Get<limits::BlockWeights>;
471

            
472
		/// The maximum length of a block (in bytes).
473
		#[pallet::constant]
474
		type BlockLength: Get<limits::BlockLength>;
475

            
476
		/// The `RuntimeOrigin` type used by dispatchable calls.
477
		#[pallet::no_default_bounds]
478
		type RuntimeOrigin: Into<Result<RawOrigin<Self::AccountId>, Self::RuntimeOrigin>>
479
			+ From<RawOrigin<Self::AccountId>>
480
			+ Clone
481
			+ OriginTrait<Call = Self::RuntimeCall, AccountId = Self::AccountId>;
482

            
483
		#[docify::export(system_runtime_call)]
484
		/// The aggregated `RuntimeCall` type.
485
		#[pallet::no_default_bounds]
486
		type RuntimeCall: Parameter
487
			+ Dispatchable<RuntimeOrigin = Self::RuntimeOrigin>
488
			+ Debug
489
			+ From<Call<Self>>;
490

            
491
		/// The aggregated `RuntimeTask` type.
492
		#[pallet::no_default_bounds]
493
		type RuntimeTask: Task;
494

            
495
		/// This stores the number of previous transactions associated with a sender account.
496
		type Nonce: Parameter
497
			+ Member
498
			+ MaybeSerializeDeserialize
499
			+ Debug
500
			+ Default
501
			+ MaybeDisplay
502
			+ AtLeast32Bit
503
			+ Copy
504
			+ MaxEncodedLen;
505

            
506
		/// The output of the `Hashing` function.
507
		type Hash: Parameter
508
			+ Member
509
			+ MaybeSerializeDeserialize
510
			+ Debug
511
			+ MaybeDisplay
512
			+ SimpleBitOps
513
			+ Ord
514
			+ Default
515
			+ Copy
516
			+ CheckEqual
517
			+ core::hash::Hash
518
			+ AsRef<[u8]>
519
			+ AsMut<[u8]>
520
			+ MaxEncodedLen;
521

            
522
		/// The hashing system (algorithm) being used in the runtime (e.g. Blake2).
523
		type Hashing: Hash<Output = Self::Hash> + TypeInfo;
524

            
525
		/// The user account identifier type for the runtime.
526
		type AccountId: Parameter
527
			+ Member
528
			+ MaybeSerializeDeserialize
529
			+ Debug
530
			+ MaybeDisplay
531
			+ Ord
532
			+ MaxEncodedLen;
533

            
534
		/// Converting trait to take a source type and convert to `AccountId`.
535
		///
536
		/// Used to define the type and conversion mechanism for referencing accounts in
537
		/// transactions. It's perfectly reasonable for this to be an identity conversion (with the
538
		/// source type being `AccountId`), but other pallets (e.g. Indices pallet) may provide more
539
		/// functional/efficient alternatives.
540
		type Lookup: StaticLookup<Target = Self::AccountId>;
541

            
542
		/// The Block type used by the runtime. This is used by `construct_runtime` to retrieve the
543
		/// extrinsics or other block specific data as needed.
544
		#[pallet::no_default]
545
		type Block: Parameter + Member + traits::Block<Hash = Self::Hash>;
546

            
547
		/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
548
		#[pallet::constant]
549
		#[pallet::no_default_bounds]
550
		type BlockHashCount: Get<BlockNumberFor<Self>>;
551

            
552
		/// The weight of runtime database operations the runtime can invoke.
553
		#[pallet::constant]
554
		type DbWeight: Get<RuntimeDbWeight>;
555

            
556
		/// Get the chain's in-code version.
557
		#[pallet::constant]
558
		type Version: Get<RuntimeVersion>;
559

            
560
		/// Provides information about the pallet setup in the runtime.
561
		///
562
		/// Expects the `PalletInfo` type that is being generated by `construct_runtime!` in the
563
		/// runtime.
564
		///
565
		/// For tests it is okay to use `()` as type, however it will provide "useless" data.
566
		#[pallet::no_default_bounds]
567
		type PalletInfo: PalletInfo;
568

            
569
		/// Data to be associated with an account (other than nonce/transaction counter, which this
570
		/// pallet does regardless).
571
		type AccountData: Member + FullCodec + Clone + Default + TypeInfo + MaxEncodedLen;
572

            
573
		/// Handler for when a new account has just been created.
574
		type OnNewAccount: OnNewAccount<Self::AccountId>;
575

            
576
		/// A function that is invoked when an account has been determined to be dead.
577
		///
578
		/// All resources should be cleaned up associated with the given account.
579
		type OnKilledAccount: OnKilledAccount<Self::AccountId>;
580

            
581
		type SystemWeightInfo: WeightInfo;
582

            
583
		/// The designated SS58 prefix of this chain.
584
		///
585
		/// This replaces the "ss58Format" property declared in the chain spec. Reason is
586
		/// that the runtime should know about the prefix in order to make use of it as
587
		/// an identifier of the chain.
588
		#[pallet::constant]
589
		type SS58Prefix: Get<u16>;
590

            
591
		/// What to do if the runtime wants to change the code to something new.
592
		///
593
		/// The default (`()`) implementation is responsible for setting the correct storage
594
		/// entry and emitting corresponding event and log item. (see
595
		/// [`Pallet::update_code_in_storage`]).
596
		/// It's unlikely that this needs to be customized, unless you are writing a parachain using
597
		/// `Cumulus`, where the actual code change is deferred.
598
		#[pallet::no_default_bounds]
599
		type OnSetCode: SetCode<Self>;
600

            
601
		/// The maximum number of consumers allowed on a single account.
602
		type MaxConsumers: ConsumerLimits;
603

            
604
		/// All migrations that should run in the next runtime upgrade.
605
		///
606
		/// These used to be formerly configured in `Executive`. Parachains need to ensure that
607
		/// running all these migrations in one block will not overflow the weight limit of a block.
608
		/// The migrations are run *before* the pallet `on_runtime_upgrade` hooks, just like the
609
		/// `OnRuntimeUpgrade` migrations.
610
		type SingleBlockMigrations: OnRuntimeUpgrade;
611

            
612
		/// The migrator that is used to run Multi-Block-Migrations.
613
		///
614
		/// Can be set to [`pallet-migrations`] or an alternative implementation of the interface.
615
		/// The diagram in `frame_executive::block_flowchart` explains when it runs.
616
		type MultiBlockMigrator: MultiStepMigrator;
617

            
618
		/// A callback that executes in *every block* directly before all inherents were applied.
619
		///
620
		/// See `frame_executive::block_flowchart` for a in-depth explanation when it runs.
621
		type PreInherents: PreInherents;
622

            
623
		/// A callback that executes in *every block* directly after all inherents were applied.
624
		///
625
		/// See `frame_executive::block_flowchart` for a in-depth explanation when it runs.
626
		type PostInherents: PostInherents;
627

            
628
		/// A callback that executes in *every block* directly after all transactions were applied.
629
		///
630
		/// See `frame_executive::block_flowchart` for a in-depth explanation when it runs.
631
		type PostTransactions: PostTransactions;
632
	}
633

            
634
1698
	#[pallet::pallet]
635
	pub struct Pallet<T>(_);
636

            
637
514679
	#[pallet::hooks]
638
	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
639
		#[cfg(feature = "std")]
640
53637
		fn integrity_test() {
641
53637
			T::BlockWeights::get().validate().expect("The weights are invalid.");
642
53637
		}
643
	}
644

            
645
685149
	#[pallet::call]
646
	impl<T: Config> Pallet<T> {
647
		/// Make some on-chain remark.
648
		///
649
		/// Can be executed by every `origin`.
650
		#[pallet::call_index(0)]
651
		#[pallet::weight(T::SystemWeightInfo::remark(remark.len() as u32))]
652
		pub fn remark(_origin: OriginFor<T>, remark: Vec<u8>) -> DispatchResultWithPostInfo {
653
			let _ = remark; // No need to check the weight witness.
654
			Ok(().into())
655
		}
656

            
657
		/// Set the number of pages in the WebAssembly environment's heap.
658
		#[pallet::call_index(1)]
659
		#[pallet::weight((T::SystemWeightInfo::set_heap_pages(), DispatchClass::Operational))]
660
		pub fn set_heap_pages(origin: OriginFor<T>, pages: u64) -> DispatchResultWithPostInfo {
661
			ensure_root(origin)?;
662
			storage::unhashed::put_raw(well_known_keys::HEAP_PAGES, &pages.encode());
663
			Self::deposit_log(generic::DigestItem::RuntimeEnvironmentUpdated);
664
			Ok(().into())
665
		}
666

            
667
		/// Set the new runtime code.
668
		#[pallet::call_index(2)]
669
		#[pallet::weight((T::SystemWeightInfo::set_code(), DispatchClass::Operational))]
670
		pub fn set_code(origin: OriginFor<T>, code: Vec<u8>) -> DispatchResultWithPostInfo {
671
			ensure_root(origin)?;
672
			Self::can_set_code(&code)?;
673
			T::OnSetCode::set_code(code)?;
674
			// consume the rest of the block to prevent further transactions
675
			Ok(Some(T::BlockWeights::get().max_block).into())
676
		}
677

            
678
		/// Set the new runtime code without doing any checks of the given `code`.
679
		///
680
		/// Note that runtime upgrades will not run if this is called with a not-increasing spec
681
		/// version!
682
		#[pallet::call_index(3)]
683
		#[pallet::weight((T::SystemWeightInfo::set_code(), DispatchClass::Operational))]
684
		pub fn set_code_without_checks(
685
			origin: OriginFor<T>,
686
			code: Vec<u8>,
687
		) -> DispatchResultWithPostInfo {
688
			ensure_root(origin)?;
689
			T::OnSetCode::set_code(code)?;
690
			Ok(Some(T::BlockWeights::get().max_block).into())
691
		}
692

            
693
		/// Set some items of storage.
694
		#[pallet::call_index(4)]
695
		#[pallet::weight((
696
			T::SystemWeightInfo::set_storage(items.len() as u32),
697
			DispatchClass::Operational,
698
		))]
699
		pub fn set_storage(
700
			origin: OriginFor<T>,
701
			items: Vec<KeyValue>,
702
		) -> DispatchResultWithPostInfo {
703
			ensure_root(origin)?;
704
			for i in &items {
705
				storage::unhashed::put_raw(&i.0, &i.1);
706
			}
707
			Ok(().into())
708
		}
709

            
710
		/// Kill some items from storage.
711
		#[pallet::call_index(5)]
712
		#[pallet::weight((
713
			T::SystemWeightInfo::kill_storage(keys.len() as u32),
714
			DispatchClass::Operational,
715
		))]
716
		pub fn kill_storage(origin: OriginFor<T>, keys: Vec<Key>) -> DispatchResultWithPostInfo {
717
			ensure_root(origin)?;
718
			for key in &keys {
719
				storage::unhashed::kill(key);
720
			}
721
			Ok(().into())
722
		}
723

            
724
		/// Kill all storage items with a key that starts with the given prefix.
725
		///
726
		/// **NOTE:** We rely on the Root origin to provide us the number of subkeys under
727
		/// the prefix we are removing to accurately calculate the weight of this function.
728
		#[pallet::call_index(6)]
729
		#[pallet::weight((
730
			T::SystemWeightInfo::kill_prefix(subkeys.saturating_add(1)),
731
			DispatchClass::Operational,
732
		))]
733
		pub fn kill_prefix(
734
			origin: OriginFor<T>,
735
			prefix: Key,
736
			subkeys: u32,
737
		) -> DispatchResultWithPostInfo {
738
			ensure_root(origin)?;
739
			let _ = storage::unhashed::clear_prefix(&prefix, Some(subkeys), None);
740
			Ok(().into())
741
		}
742

            
743
		/// Make some on-chain remark and emit event.
744
		#[pallet::call_index(7)]
745
		#[pallet::weight(T::SystemWeightInfo::remark_with_event(remark.len() as u32))]
746
		pub fn remark_with_event(
747
			origin: OriginFor<T>,
748
			remark: Vec<u8>,
749
		) -> DispatchResultWithPostInfo {
750
			let who = ensure_signed(origin)?;
751
			let hash = T::Hashing::hash(&remark[..]);
752
			Self::deposit_event(Event::Remarked { sender: who, hash });
753
			Ok(().into())
754
		}
755

            
756
		#[cfg(feature = "experimental")]
757
		#[pallet::call_index(8)]
758
		#[pallet::weight(task.weight())]
759
		pub fn do_task(_origin: OriginFor<T>, task: T::RuntimeTask) -> DispatchResultWithPostInfo {
760
			if !task.is_valid() {
761
				return Err(Error::<T>::InvalidTask.into())
762
			}
763

            
764
			Self::deposit_event(Event::TaskStarted { task: task.clone() });
765
			if let Err(err) = task.run() {
766
				Self::deposit_event(Event::TaskFailed { task, err });
767
				return Err(Error::<T>::FailedTask.into())
768
			}
769

            
770
			// Emit a success event, if your design includes events for this pallet.
771
			Self::deposit_event(Event::TaskCompleted { task });
772

            
773
			// Return success.
774
			Ok(().into())
775
		}
776

            
777
		/// Authorize an upgrade to a given `code_hash` for the runtime. The runtime can be supplied
778
		/// later.
779
		///
780
		/// This call requires Root origin.
781
		#[pallet::call_index(9)]
782
		#[pallet::weight((T::SystemWeightInfo::authorize_upgrade(), DispatchClass::Operational))]
783
		pub fn authorize_upgrade(origin: OriginFor<T>, code_hash: T::Hash) -> DispatchResult {
784
			ensure_root(origin)?;
785
			Self::do_authorize_upgrade(code_hash, true);
786
			Ok(())
787
		}
788

            
789
		/// Authorize an upgrade to a given `code_hash` for the runtime. The runtime can be supplied
790
		/// later.
791
		///
792
		/// WARNING: This authorizes an upgrade that will take place without any safety checks, for
793
		/// example that the spec name remains the same and that the version number increases. Not
794
		/// recommended for normal use. Use `authorize_upgrade` instead.
795
		///
796
		/// This call requires Root origin.
797
		#[pallet::call_index(10)]
798
		#[pallet::weight((T::SystemWeightInfo::authorize_upgrade(), DispatchClass::Operational))]
799
		pub fn authorize_upgrade_without_checks(
800
			origin: OriginFor<T>,
801
			code_hash: T::Hash,
802
		) -> DispatchResult {
803
			ensure_root(origin)?;
804
			Self::do_authorize_upgrade(code_hash, false);
805
			Ok(())
806
		}
807

            
808
		/// Provide the preimage (runtime binary) `code` for an upgrade that has been authorized.
809
		///
810
		/// If the authorization required a version check, this call will ensure the spec name
811
		/// remains unchanged and that the spec version has increased.
812
		///
813
		/// Depending on the runtime's `OnSetCode` configuration, this function may directly apply
814
		/// the new `code` in the same block or attempt to schedule the upgrade.
815
		///
816
		/// All origins are allowed.
817
		#[pallet::call_index(11)]
818
		#[pallet::weight((T::SystemWeightInfo::apply_authorized_upgrade(), DispatchClass::Operational))]
819
		pub fn apply_authorized_upgrade(
820
			_: OriginFor<T>,
821
			code: Vec<u8>,
822
		) -> DispatchResultWithPostInfo {
823
			let post = Self::do_apply_authorize_upgrade(code)?;
824
			Ok(post)
825
		}
826
	}
827

            
828
	/// Event for the System pallet.
829
	#[pallet::event]
830
	pub enum Event<T: Config> {
831
		/// An extrinsic completed successfully.
832
		ExtrinsicSuccess { dispatch_info: DispatchInfo },
833
		/// An extrinsic failed.
834
		ExtrinsicFailed { dispatch_error: DispatchError, dispatch_info: DispatchInfo },
835
		/// `:code` was updated.
836
		CodeUpdated,
837
		/// A new account was created.
838
		NewAccount { account: T::AccountId },
839
		/// An account was reaped.
840
		KilledAccount { account: T::AccountId },
841
		/// On on-chain remark happened.
842
		Remarked { sender: T::AccountId, hash: T::Hash },
843
		#[cfg(feature = "experimental")]
844
		/// A [`Task`] has started executing
845
		TaskStarted { task: T::RuntimeTask },
846
		#[cfg(feature = "experimental")]
847
		/// A [`Task`] has finished executing.
848
		TaskCompleted { task: T::RuntimeTask },
849
		#[cfg(feature = "experimental")]
850
		/// A [`Task`] failed during execution.
851
		TaskFailed { task: T::RuntimeTask, err: DispatchError },
852
		/// An upgrade was authorized.
853
		UpgradeAuthorized { code_hash: T::Hash, check_version: bool },
854
	}
855

            
856
	/// Error for the System pallet
857
3048
	#[pallet::error]
858
	pub enum Error<T> {
859
		/// The name of specification does not match between the current runtime
860
		/// and the new runtime.
861
		InvalidSpecName,
862
		/// The specification version is not allowed to decrease between the current runtime
863
		/// and the new runtime.
864
		SpecVersionNeedsToIncrease,
865
		/// Failed to extract the runtime version from the new runtime.
866
		///
867
		/// Either calling `Core_version` or decoding `RuntimeVersion` failed.
868
		FailedToExtractRuntimeVersion,
869
		/// Suicide called when the account has non-default composite data.
870
		NonDefaultComposite,
871
		/// There is a non-zero reference count preventing the account from being purged.
872
		NonZeroRefCount,
873
		/// The origin filter prevent the call to be dispatched.
874
		CallFiltered,
875
		/// A multi-block migration is ongoing and prevents the current code from being replaced.
876
		MultiBlockMigrationsOngoing,
877
		#[cfg(feature = "experimental")]
878
		/// The specified [`Task`] is not valid.
879
		InvalidTask,
880
		#[cfg(feature = "experimental")]
881
		/// The specified [`Task`] failed during execution.
882
		FailedTask,
883
		/// No upgrade authorized.
884
		NothingAuthorized,
885
		/// The submitted code is not authorized.
886
		Unauthorized,
887
	}
888

            
889
	/// Exposed trait-generic origin type.
890
	#[pallet::origin]
891
	pub type Origin<T> = RawOrigin<<T as Config>::AccountId>;
892

            
893
	/// The full account information for a particular account ID.
894
472926
	#[pallet::storage]
895
	#[pallet::getter(fn account)]
896
	pub type Account<T: Config> = StorageMap<
897
		_,
898
		Blake2_128Concat,
899
		T::AccountId,
900
		AccountInfo<T::Nonce, T::AccountData>,
901
		ValueQuery,
902
	>;
903

            
904
	/// Total extrinsics count for the current block.
905
779052
	#[pallet::storage]
906
	pub(super) type ExtrinsicCount<T: Config> = StorageValue<_, u32>;
907

            
908
	/// Whether all inherents have been applied.
909
1558104
	#[pallet::storage]
910
	pub type InherentsApplied<T: Config> = StorageValue<_, bool, ValueQuery>;
911

            
912
	/// The current weight for the block.
913
6066963
	#[pallet::storage]
914
	#[pallet::whitelist_storage]
915
	#[pallet::getter(fn block_weight)]
916
	pub type BlockWeight<T: Config> = StorageValue<_, ConsumedWeight, ValueQuery>;
917

            
918
	/// Total length (in bytes) for all extrinsics put together, for the current block.
919
1275852
	#[pallet::storage]
920
	pub(super) type AllExtrinsicsLen<T: Config> = StorageValue<_, u32>;
921

            
922
	/// Map of block numbers to block hashes.
923
313170
	#[pallet::storage]
924
	#[pallet::getter(fn block_hash)]
925
	pub type BlockHash<T: Config> =
926
		StorageMap<_, Twox64Concat, BlockNumberFor<T>, T::Hash, ValueQuery>;
927

            
928
	/// Extrinsics data for the current block (maps an extrinsic's index to its data).
929
389526
	#[pallet::storage]
930
	#[pallet::getter(fn extrinsic_data)]
931
	#[pallet::unbounded]
932
	pub(super) type ExtrinsicData<T: Config> =
933
		StorageMap<_, Twox64Concat, u32, Vec<u8>, ValueQuery>;
934

            
935
	/// The current block number being processed. Set by `execute_block`.
936
8459769
	#[pallet::storage]
937
	#[pallet::whitelist_storage]
938
	#[pallet::getter(fn block_number)]
939
	pub(super) type Number<T: Config> = StorageValue<_, BlockNumberFor<T>, ValueQuery>;
940

            
941
	/// Hash of the previous block.
942
3116214
	#[pallet::storage]
943
	#[pallet::getter(fn parent_hash)]
944
	pub(super) type ParentHash<T: Config> = StorageValue<_, T::Hash, ValueQuery>;
945

            
946
	/// Digest of the current block, also part of the block header.
947
2478312
	#[pallet::storage]
948
	#[pallet::unbounded]
949
	#[pallet::getter(fn digest)]
950
	pub(super) type Digest<T: Config> = StorageValue<_, generic::Digest, ValueQuery>;
951

            
952
	/// Events deposited for the current block.
953
	///
954
	/// NOTE: The item is unbound and should therefore never be read on chain.
955
	/// It could otherwise inflate the PoV size of a block.
956
	///
957
	/// Events have a large in-memory size. Box the events to not go out-of-memory
958
	/// just in case someone still reads them from within the runtime.
959
1584834
	#[pallet::storage]
960
	#[pallet::whitelist_storage]
961
	#[pallet::disable_try_decode_storage]
962
	#[pallet::unbounded]
963
	pub(super) type Events<T: Config> =
964
		StorageValue<_, Vec<Box<EventRecord<T::RuntimeEvent, T::Hash>>>, ValueQuery>;
965

            
966
	/// The number of events in the `Events<T>` list.
967
2780142
	#[pallet::storage]
968
	#[pallet::whitelist_storage]
969
	#[pallet::getter(fn event_count)]
970
	pub(super) type EventCount<T: Config> = StorageValue<_, EventIndex, ValueQuery>;
971

            
972
	/// Mapping between a topic (represented by T::Hash) and a vector of indexes
973
	/// of events in the `<Events<T>>` list.
974
	///
975
	/// All topic vectors have deterministic storage locations depending on the topic. This
976
	/// allows light-clients to leverage the changes trie storage tracking mechanism and
977
	/// in case of changes fetch the list of events of interest.
978
	///
979
	/// The value has the type `(BlockNumberFor<T>, EventIndex)` because if we used only just
980
	/// the `EventIndex` then in case if the topic has the same contents on the next block
981
	/// no notification will be triggered thus the event might be lost.
982
194763
	#[pallet::storage]
983
	#[pallet::unbounded]
984
	#[pallet::getter(fn event_topics)]
985
	pub(super) type EventTopics<T: Config> =
986
		StorageMap<_, Blake2_128Concat, T::Hash, Vec<(BlockNumberFor<T>, EventIndex)>, ValueQuery>;
987

            
988
	/// Stores the `spec_version` and `spec_name` of when the last runtime upgrade happened.
989
389532
	#[pallet::storage]
990
	#[pallet::unbounded]
991
	pub type LastRuntimeUpgrade<T: Config> = StorageValue<_, LastRuntimeUpgradeInfo>;
992

            
993
	/// True if we have upgraded so that `type RefCount` is `u32`. False (default) if not.
994
6
	#[pallet::storage]
995
	pub(super) type UpgradedToU32RefCount<T: Config> = StorageValue<_, bool, ValueQuery>;
996

            
997
	/// True if we have upgraded so that AccountInfo contains three types of `RefCount`. False
998
	/// (default) if not.
999
6
	#[pallet::storage]
	pub(super) type UpgradedToTripleRefCount<T: Config> = StorageValue<_, bool, ValueQuery>;
	/// The execution phase of the block.
3142938
	#[pallet::storage]
	#[pallet::whitelist_storage]
	pub(super) type ExecutionPhase<T: Config> = StorageValue<_, Phase>;
	/// `Some` if a code upgrade has been authorized.
	#[pallet::storage]
	#[pallet::getter(fn authorized_upgrade)]
	pub(super) type AuthorizedUpgrade<T: Config> =
		StorageValue<_, CodeUpgradeAuthorization<T>, OptionQuery>;
	#[derive(frame_support::DefaultNoBound)]
	#[pallet::genesis_config]
	pub struct GenesisConfig<T: Config> {
		#[serde(skip)]
		pub _config: core::marker::PhantomData<T>,
	}
	#[pallet::genesis_build]
	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
3
		fn build(&self) {
3
			<BlockHash<T>>::insert::<_, T::Hash>(BlockNumberFor::<T>::zero(), hash69());
3
			<ParentHash<T>>::put::<T::Hash>(hash69());
3
			<LastRuntimeUpgrade<T>>::put(LastRuntimeUpgradeInfo::from(T::Version::get()));
3
			<UpgradedToU32RefCount<T>>::put(true);
3
			<UpgradedToTripleRefCount<T>>::put(true);
3

            
3
			sp_io::storage::set(well_known_keys::EXTRINSIC_INDEX, &0u32.encode());
3
		}
	}
	#[pallet::validate_unsigned]
	impl<T: Config> sp_runtime::traits::ValidateUnsigned for Pallet<T> {
		type Call = Call<T>;
		fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity {
			if let Call::apply_authorized_upgrade { ref code } = call {
				if let Ok(hash) = Self::validate_authorized_upgrade(&code[..]) {
					return Ok(ValidTransaction {
						priority: 100,
						requires: Vec::new(),
						provides: vec![hash.as_ref().to_vec()],
						longevity: TransactionLongevity::max_value(),
						propagate: true,
					})
				}
			}
			#[cfg(feature = "experimental")]
			if let Call::do_task { ref task } = call {
				if task.is_valid() {
					return Ok(ValidTransaction {
						priority: u64::max_value(),
						requires: Vec::new(),
						provides: vec![T::Hashing::hash_of(&task.encode()).as_ref().to_vec()],
						longevity: TransactionLongevity::max_value(),
						propagate: true,
					})
				}
			}
			Err(InvalidTransaction::Call.into())
		}
	}
}
pub type Key = Vec<u8>;
pub type KeyValue = (Vec<u8>, Vec<u8>);
/// A phase of a block's execution.
#[derive(Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]
#[cfg_attr(feature = "std", derive(Serialize, PartialEq, Eq, Clone))]
pub enum Phase {
295455
	/// Applying an extrinsic.
295455
	ApplyExtrinsic(u32),
15873
	/// Finalizing the block.
15873
	Finalization,
286326
	/// Initializing the block.
286326
	Initialization,
}
impl Default for Phase {
	fn default() -> Self {
		Self::Initialization
	}
}
/// Record of an event happening.
#[derive(Encode, Decode, RuntimeDebug, TypeInfo)]
#[cfg_attr(feature = "std", derive(Serialize, PartialEq, Eq, Clone))]
pub struct EventRecord<E: Parameter + Member, T> {
	/// The phase of the block it happened in.
	pub phase: Phase,
	/// The event itself.
	pub event: E,
	/// The list of the topics this event has.
	pub topics: Vec<T>,
}
// Create a Hash with 69 for each byte,
// only used to build genesis config.
6
fn hash69<T: AsMut<[u8]> + Default>() -> T {
6
	let mut h = T::default();
192
	h.as_mut().iter_mut().for_each(|byte| *byte = 69);
6
	h
6
}
/// This type alias represents an index of an event.
///
/// We use `u32` here because this index is used as index for `Events<T>`
/// which can't contain more than `u32::MAX` items.
type EventIndex = u32;
/// Type used to encode the number of references an account has.
pub type RefCount = u32;
/// Information of an account.
#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)]
pub struct AccountInfo<Nonce, AccountData> {
	/// The number of transactions this account has sent.
	pub nonce: Nonce,
	/// The number of other modules that currently depend on this account's existence. The account
	/// cannot be reaped until this is zero.
	pub consumers: RefCount,
	/// The number of other modules that allow this account to exist. The account may not be reaped
	/// until this and `sufficients` are both zero.
	pub providers: RefCount,
	/// The number of modules that allow this account to exist for their own purposes only. The
	/// account may not be reaped until this and `providers` are both zero.
	pub sufficients: RefCount,
	/// The additional data that belongs to this account. Used to store the balance(s) in a lot of
	/// chains.
	pub data: AccountData,
}
/// Stores the `spec_version` and `spec_name` of when the last runtime upgrade
/// happened.
#[derive(sp_runtime::RuntimeDebug, Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "std", derive(PartialEq))]
pub struct LastRuntimeUpgradeInfo {
	pub spec_version: codec::Compact<u32>,
	pub spec_name: sp_runtime::RuntimeString,
}
impl LastRuntimeUpgradeInfo {
	/// Returns if the runtime was upgraded in comparison of `self` and `current`.
	///
	/// Checks if either the `spec_version` increased or the `spec_name` changed.
129842
	pub fn was_upgraded(&self, current: &sp_version::RuntimeVersion) -> bool {
129842
		current.spec_version > self.spec_version.0 || current.spec_name != self.spec_name
129842
	}
}
impl From<sp_version::RuntimeVersion> for LastRuntimeUpgradeInfo {
2
	fn from(version: sp_version::RuntimeVersion) -> Self {
2
		Self { spec_version: version.spec_version.into(), spec_name: version.spec_name }
2
	}
}
/// Ensure the origin is Root.
pub struct EnsureRoot<AccountId>(core::marker::PhantomData<AccountId>);
impl<O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>, AccountId>
	EnsureOrigin<O> for EnsureRoot<AccountId>
{
	type Success = ();
14460
	fn try_origin(o: O) -> Result<Self::Success, O> {
14460
		o.into().and_then(|o| match o {
			RawOrigin::Root => Ok(()),
14460
			r => Err(O::from(r)),
14460
		})
14460
	}
	#[cfg(feature = "runtime-benchmarks")]
	fn try_successful_origin() -> Result<O, ()> {
		Ok(O::from(RawOrigin::Root))
	}
}
impl_ensure_origin_with_arg_ignoring_arg! {
	impl< { O: .., AccountId: Decode, T } >
		EnsureOriginWithArg<O, T> for EnsureRoot<AccountId>
	{}
}
/// Ensure the origin is Root and return the provided `Success` value.
pub struct EnsureRootWithSuccess<AccountId, Success>(
	core::marker::PhantomData<(AccountId, Success)>,
);
impl<
		O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>,
		AccountId,
		Success: TypedGet,
	> EnsureOrigin<O> for EnsureRootWithSuccess<AccountId, Success>
{
	type Success = Success::Type;
2724
	fn try_origin(o: O) -> Result<Self::Success, O> {
2724
		o.into().and_then(|o| match o {
			RawOrigin::Root => Ok(Success::get()),
2724
			r => Err(O::from(r)),
2724
		})
2724
	}
	#[cfg(feature = "runtime-benchmarks")]
	fn try_successful_origin() -> Result<O, ()> {
		Ok(O::from(RawOrigin::Root))
	}
}
impl_ensure_origin_with_arg_ignoring_arg! {
	impl< { O: .., AccountId: Decode, Success: TypedGet, T } >
		EnsureOriginWithArg<O, T> for EnsureRootWithSuccess<AccountId, Success>
	{}
}
/// Ensure the origin is provided `Ensure` origin and return the provided `Success` value.
pub struct EnsureWithSuccess<Ensure, AccountId, Success>(
	core::marker::PhantomData<(Ensure, AccountId, Success)>,
);
impl<
		O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>,
		Ensure: EnsureOrigin<O>,
		AccountId,
		Success: TypedGet,
	> EnsureOrigin<O> for EnsureWithSuccess<Ensure, AccountId, Success>
{
	type Success = Success::Type;
	fn try_origin(o: O) -> Result<Self::Success, O> {
		Ensure::try_origin(o).map(|_| Success::get())
	}
	#[cfg(feature = "runtime-benchmarks")]
	fn try_successful_origin() -> Result<O, ()> {
		Ensure::try_successful_origin()
	}
}
/// Ensure the origin is any `Signed` origin.
pub struct EnsureSigned<AccountId>(core::marker::PhantomData<AccountId>);
impl<O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>, AccountId: Decode>
	EnsureOrigin<O> for EnsureSigned<AccountId>
{
	type Success = AccountId;
1749
	fn try_origin(o: O) -> Result<Self::Success, O> {
1749
		o.into().and_then(|o| match o {
1749
			RawOrigin::Signed(who) => Ok(who),
			r => Err(O::from(r)),
1749
		})
1749
	}
	#[cfg(feature = "runtime-benchmarks")]
	fn try_successful_origin() -> Result<O, ()> {
		let zero_account_id =
			AccountId::decode(&mut TrailingZeroInput::zeroes()).map_err(|_| ())?;
		Ok(O::from(RawOrigin::Signed(zero_account_id)))
	}
}
impl_ensure_origin_with_arg_ignoring_arg! {
	impl< { O: .., AccountId: Decode, T } >
		EnsureOriginWithArg<O, T> for EnsureSigned<AccountId>
	{}
}
/// Ensure the origin is `Signed` origin from the given `AccountId`.
pub struct EnsureSignedBy<Who, AccountId>(core::marker::PhantomData<(Who, AccountId)>);
impl<
		O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>,
		Who: SortedMembers<AccountId>,
		AccountId: PartialEq + Clone + Ord + Decode,
	> EnsureOrigin<O> for EnsureSignedBy<Who, AccountId>
{
	type Success = AccountId;
	fn try_origin(o: O) -> Result<Self::Success, O> {
		o.into().and_then(|o| match o {
			RawOrigin::Signed(ref who) if Who::contains(who) => Ok(who.clone()),
			r => Err(O::from(r)),
		})
	}
	#[cfg(feature = "runtime-benchmarks")]
	fn try_successful_origin() -> Result<O, ()> {
		let first_member = match Who::sorted_members().first() {
			Some(account) => account.clone(),
			None => AccountId::decode(&mut TrailingZeroInput::zeroes()).map_err(|_| ())?,
		};
		Ok(O::from(RawOrigin::Signed(first_member)))
	}
}
impl_ensure_origin_with_arg_ignoring_arg! {
	impl< { O: .., Who: SortedMembers<AccountId>, AccountId: PartialEq + Clone + Ord + Decode, T } >
		EnsureOriginWithArg<O, T> for EnsureSignedBy<Who, AccountId>
	{}
}
/// Ensure the origin is `None`. i.e. unsigned transaction.
pub struct EnsureNone<AccountId>(core::marker::PhantomData<AccountId>);
impl<O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>, AccountId>
	EnsureOrigin<O> for EnsureNone<AccountId>
{
	type Success = ();
	fn try_origin(o: O) -> Result<Self::Success, O> {
		o.into().and_then(|o| match o {
			RawOrigin::None => Ok(()),
			r => Err(O::from(r)),
		})
	}
	#[cfg(feature = "runtime-benchmarks")]
	fn try_successful_origin() -> Result<O, ()> {
		Ok(O::from(RawOrigin::None))
	}
}
impl_ensure_origin_with_arg_ignoring_arg! {
	impl< { O: .., AccountId, T } >
		EnsureOriginWithArg<O, T> for EnsureNone<AccountId>
	{}
}
/// Always fail.
pub struct EnsureNever<Success>(core::marker::PhantomData<Success>);
impl<O, Success> EnsureOrigin<O> for EnsureNever<Success> {
	type Success = Success;
804
	fn try_origin(o: O) -> Result<Self::Success, O> {
804
		Err(o)
804
	}
	#[cfg(feature = "runtime-benchmarks")]
	fn try_successful_origin() -> Result<O, ()> {
		Err(())
	}
}
impl_ensure_origin_with_arg_ignoring_arg! {
	impl< { O, Success, T } >
		EnsureOriginWithArg<O, T> for EnsureNever<Success>
	{}
}
#[docify::export]
/// Ensure that the origin `o` represents a signed extrinsic (i.e. transaction).
/// Returns `Ok` with the account that signed the extrinsic or an `Err` otherwise.
80967
pub fn ensure_signed<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<AccountId, BadOrigin>
80967
where
80967
	OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
80967
{
80967
	match o.into() {
78132
		Ok(RawOrigin::Signed(t)) => Ok(t),
2835
		_ => Err(BadOrigin),
	}
80967
}
/// Ensure that the origin `o` represents either a signed extrinsic (i.e. transaction) or the root.
/// Returns `Ok` with the account that signed the extrinsic, `None` if it was root,  or an `Err`
/// otherwise.
13452
pub fn ensure_signed_or_root<OuterOrigin, AccountId>(
13452
	o: OuterOrigin,
13452
) -> Result<Option<AccountId>, BadOrigin>
13452
where
13452
	OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
13452
{
13452
	match o.into() {
		Ok(RawOrigin::Root) => Ok(None),
13452
		Ok(RawOrigin::Signed(t)) => Ok(Some(t)),
		_ => Err(BadOrigin),
	}
13452
}
/// Ensure that the origin `o` represents the root. Returns `Ok` or an `Err` otherwise.
125640
pub fn ensure_root<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<(), BadOrigin>
125640
where
125640
	OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
125640
{
125640
	match o.into() {
64212
		Ok(RawOrigin::Root) => Ok(()),
61428
		_ => Err(BadOrigin),
	}
125640
}
/// Ensure that the origin `o` represents an unsigned extrinsic. Returns `Ok` or an `Err` otherwise.
611994
pub fn ensure_none<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<(), BadOrigin>
611994
where
611994
	OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
611994
{
611994
	match o.into() {
584289
		Ok(RawOrigin::None) => Ok(()),
27705
		_ => Err(BadOrigin),
	}
611994
}
/// Reference status; can be either referenced or unreferenced.
#[derive(RuntimeDebug)]
pub enum RefStatus {
	Referenced,
	Unreferenced,
}
/// Some resultant status relevant to incrementing a provider/self-sufficient reference.
#[derive(Eq, PartialEq, RuntimeDebug)]
pub enum IncRefStatus {
	/// Account was created.
	Created,
	/// Account already existed.
	Existed,
}
/// Some resultant status relevant to decrementing a provider/self-sufficient reference.
#[derive(Eq, PartialEq, RuntimeDebug)]
pub enum DecRefStatus {
	/// Account was destroyed.
	Reaped,
	/// Account still exists.
	Exists,
}
impl<T: Config> Pallet<T> {
	/// Returns the `spec_version` of the last runtime upgrade.
	///
	/// This function is useful for writing guarded runtime migrations in the runtime. A runtime
	/// migration can use the `spec_version` to ensure that it isn't applied twice. This works
	/// similar as the storage version for pallets.
	///
	/// This functions returns the `spec_version` of the last runtime upgrade while executing the
	/// runtime migrations
	/// [`on_runtime_upgrade`](frame_support::traits::OnRuntimeUpgrade::on_runtime_upgrade)
	/// function. After all migrations are executed, this will return the `spec_version` of the
	/// current runtime until there is another runtime upgrade.
	///
	/// Example:
	#[doc = docify::embed!("src/tests.rs", last_runtime_upgrade_spec_version_usage)]
	pub fn last_runtime_upgrade_spec_version() -> u32 {
		LastRuntimeUpgrade::<T>::get().map_or(0, |l| l.spec_version.0)
	}
	/// Returns true if the given account exists.
1575
	pub fn account_exists(who: &T::AccountId) -> bool {
1575
		Account::<T>::contains_key(who)
1575
	}
	/// Write code to the storage and emit related events and digest items.
	///
	/// Note this function almost never should be used directly. It is exposed
	/// for `OnSetCode` implementations that defer actual code being written to
	/// the storage (for instance in case of parachains).
	pub fn update_code_in_storage(code: &[u8]) {
		storage::unhashed::put_raw(well_known_keys::CODE, code);
		Self::deposit_log(generic::DigestItem::RuntimeEnvironmentUpdated);
		Self::deposit_event(Event::CodeUpdated);
	}
	/// Whether all inherents have been applied.
194763
	pub fn inherents_applied() -> bool {
194763
		InherentsApplied::<T>::get()
194763
	}
	/// Note that all inherents have been applied.
	///
	/// Should be called immediately after all inherents have been applied. Must be called at least
	/// once per block.
194763
	pub fn note_inherents_applied() {
194763
		InherentsApplied::<T>::put(true);
194763
	}
	/// Increment the reference counter on an account.
	#[deprecated = "Use `inc_consumers` instead"]
	pub fn inc_ref(who: &T::AccountId) {
		let _ = Self::inc_consumers(who);
	}
	/// Decrement the reference counter on an account. This *MUST* only be done once for every time
	/// you called `inc_consumers` on `who`.
	#[deprecated = "Use `dec_consumers` instead"]
	pub fn dec_ref(who: &T::AccountId) {
		let _ = Self::dec_consumers(who);
	}
	/// The number of outstanding references for the account `who`.
	#[deprecated = "Use `consumers` instead"]
	pub fn refs(who: &T::AccountId) -> RefCount {
		Self::consumers(who)
	}
	/// True if the account has no outstanding references.
	#[deprecated = "Use `!is_provider_required` instead"]
	pub fn allow_death(who: &T::AccountId) -> bool {
		!Self::is_provider_required(who)
	}
	/// Increment the provider reference counter on an account.
702
	pub fn inc_providers(who: &T::AccountId) -> IncRefStatus {
936
		Account::<T>::mutate(who, |a| {
702
			if a.providers == 0 && a.sufficients == 0 {
				// Account is being created.
702
				a.providers = 1;
702
				Self::on_created_account(who.clone(), a);
702
				IncRefStatus::Created
			} else {
				a.providers = a.providers.saturating_add(1);
				IncRefStatus::Existed
			}
936
		})
702
	}
	/// Decrement the provider reference counter on an account.
	///
	/// This *MUST* only be done once for every time you called `inc_providers` on `who`.
159
	pub fn dec_providers(who: &T::AccountId) -> Result<DecRefStatus, DispatchError> {
212
		Account::<T>::try_mutate_exists(who, |maybe_account| {
159
			if let Some(mut account) = maybe_account.take() {
159
				if account.providers == 0 {
					// Logic error - cannot decrement beyond zero.
					log::error!(
						target: LOG_TARGET,
						"Logic error: Unexpected underflow in reducing provider",
					);
					account.providers = 1;
159
				}
159
				match (account.providers, account.consumers, account.sufficients) {
					(1, 0, 0) => {
						// No providers left (and no consumers) and no sufficients. Account dead.
159
						Pallet::<T>::on_killed_account(who.clone());
159
						Ok(DecRefStatus::Reaped)
					},
					(1, c, _) if c > 0 => {
						// Cannot remove last provider if there are consumers.
						Err(DispatchError::ConsumerRemaining)
					},
					(x, _, _) => {
						// Account will continue to exist as there is either > 1 provider or
						// > 0 sufficients.
						account.providers = x - 1;
						*maybe_account = Some(account);
						Ok(DecRefStatus::Exists)
					},
				}
			} else {
				log::error!(
					target: LOG_TARGET,
					"Logic error: Account already dead when reducing provider",
				);
				Ok(DecRefStatus::Reaped)
			}
212
		})
159
	}
	/// Increment the self-sufficient reference counter on an account.
	pub fn inc_sufficients(who: &T::AccountId) -> IncRefStatus {
		Account::<T>::mutate(who, |a| {
			if a.providers + a.sufficients == 0 {
				// Account is being created.
				a.sufficients = 1;
				Self::on_created_account(who.clone(), a);
				IncRefStatus::Created
			} else {
				a.sufficients = a.sufficients.saturating_add(1);
				IncRefStatus::Existed
			}
		})
	}
	/// Decrement the sufficients reference counter on an account.
	///
	/// This *MUST* only be done once for every time you called `inc_sufficients` on `who`.
	pub fn dec_sufficients(who: &T::AccountId) -> DecRefStatus {
		Account::<T>::mutate_exists(who, |maybe_account| {
			if let Some(mut account) = maybe_account.take() {
				if account.sufficients == 0 {
					// Logic error - cannot decrement beyond zero.
					log::error!(
						target: LOG_TARGET,
						"Logic error: Unexpected underflow in reducing sufficients",
					);
				}
				match (account.sufficients, account.providers) {
					(0, 0) | (1, 0) => {
						Pallet::<T>::on_killed_account(who.clone());
						DecRefStatus::Reaped
					},
					(x, _) => {
						account.sufficients = x - 1;
						*maybe_account = Some(account);
						DecRefStatus::Exists
					},
				}
			} else {
				log::error!(
					target: LOG_TARGET,
					"Logic error: Account already dead when reducing provider",
				);
				DecRefStatus::Reaped
			}
		})
	}
	/// The number of outstanding provider references for the account `who`.
29652
	pub fn providers(who: &T::AccountId) -> RefCount {
29652
		Account::<T>::get(who).providers
29652
	}
	/// The number of outstanding sufficient references for the account `who`.
960
	pub fn sufficients(who: &T::AccountId) -> RefCount {
960
		Account::<T>::get(who).sufficients
960
	}
	/// The number of outstanding provider and sufficient references for the account `who`.
	pub fn reference_count(who: &T::AccountId) -> RefCount {
		let a = Account::<T>::get(who);
		a.providers + a.sufficients
	}
	/// Increment the reference counter on an account.
	///
	/// The account `who`'s `providers` must be non-zero and the current number of consumers must
	/// be less than `MaxConsumers::max_consumers()` or this will return an error.
4080
	pub fn inc_consumers(who: &T::AccountId) -> Result<(), DispatchError> {
5440
		Account::<T>::try_mutate(who, |a| {
4080
			if a.providers > 0 {
4080
				if a.consumers < T::MaxConsumers::max_consumers() {
4080
					a.consumers = a.consumers.saturating_add(1);
4080
					Ok(())
				} else {
					Err(DispatchError::TooManyConsumers)
				}
			} else {
				Err(DispatchError::NoProviders)
			}
5440
		})
4080
	}
	/// Increment the reference counter on an account, ignoring the `MaxConsumers` limits.
	///
	/// The account `who`'s `providers` must be non-zero or this will return an error.
12
	pub fn inc_consumers_without_limit(who: &T::AccountId) -> Result<(), DispatchError> {
16
		Account::<T>::try_mutate(who, |a| {
12
			if a.providers > 0 {
12
				a.consumers = a.consumers.saturating_add(1);
12
				Ok(())
			} else {
				Err(DispatchError::NoProviders)
			}
16
		})
12
	}
	/// Decrement the reference counter on an account. This *MUST* only be done once for every time
	/// you called `inc_consumers` on `who`.
855
	pub fn dec_consumers(who: &T::AccountId) {
1140
		Account::<T>::mutate(who, |a| {
855
			if a.consumers > 0 {
855
				a.consumers -= 1;
855
			} else {
				log::error!(
					target: LOG_TARGET,
					"Logic error: Unexpected underflow in reducing consumer",
				);
			}
1140
		})
855
	}
	/// The number of outstanding references for the account `who`.
10455
	pub fn consumers(who: &T::AccountId) -> RefCount {
10455
		Account::<T>::get(who).consumers
10455
	}
	/// True if the account has some outstanding consumer references.
	pub fn is_provider_required(who: &T::AccountId) -> bool {
		Account::<T>::get(who).consumers != 0
	}
	/// True if the account has no outstanding consumer references or more than one provider.
13770
	pub fn can_dec_provider(who: &T::AccountId) -> bool {
13770
		let a = Account::<T>::get(who);
13770
		a.consumers == 0 || a.providers > 1
13770
	}
	/// True if the account has at least one provider reference and adding `amount` consumer
	/// references would not take it above the the maximum.
1806
	pub fn can_accrue_consumers(who: &T::AccountId, amount: u32) -> bool {
1806
		let a = Account::<T>::get(who);
1806
		match a.consumers.checked_add(amount) {
1806
			Some(c) => a.providers > 0 && c <= T::MaxConsumers::max_consumers(),
			None => false,
		}
1806
	}
	/// True if the account has at least one provider reference and fewer consumer references than
	/// the maximum.
1806
	pub fn can_inc_consumer(who: &T::AccountId) -> bool {
1806
		Self::can_accrue_consumers(who, 1)
1806
	}
	/// Deposits an event into this block's event record.
	///
	/// NOTE: Events not registered at the genesis block and quietly omitted.
597693
	pub fn deposit_event(event: impl Into<T::RuntimeEvent>) {
597693
		Self::deposit_event_indexed(&[], event.into());
597693
	}
	/// Deposits an event into this block's event record adding this event
	/// to the corresponding topic indexes.
	///
	/// This will update storage entries that correspond to the specified topics.
	/// It is expected that light-clients could subscribe to this topics.
	///
	/// NOTE: Events not registered at the genesis block and quietly omitted.
597693
	pub fn deposit_event_indexed(topics: &[T::Hash], event: T::RuntimeEvent) {
597693
		let block_number = Self::block_number();
597693

            
597693
		// Don't populate events on genesis.
597693
		if block_number.is_zero() {
39
			return
597654
		}
597654

            
597654
		let phase = ExecutionPhase::<T>::get().unwrap_or_default();
597654
		let event = EventRecord { phase, event, topics: topics.to_vec() };
		// Index of the event to be added.
597654
		let event_idx = {
597654
			let old_event_count = EventCount::<T>::get();
597654
			let new_event_count = match old_event_count.checked_add(1) {
				// We've reached the maximum number of events at this block, just
				// don't do anything and leave the event_count unaltered.
				None => return,
597654
				Some(nc) => nc,
597654
			};
597654
			EventCount::<T>::put(new_event_count);
597654
			old_event_count
597654
		};
597654

            
597654
		Events::<T>::append(event);
597654
		for topic in topics {
			<EventTopics<T>>::append(topic, &(block_number, event_idx));
		}
597693
	}
	/// Gets the index of extrinsic that is currently executing.
390267
	pub fn extrinsic_index() -> Option<u32> {
390267
		storage::unhashed::get(well_known_keys::EXTRINSIC_INDEX)
390267
	}
	/// Gets extrinsics count.
	pub fn extrinsic_count() -> u32 {
		ExtrinsicCount::<T>::get().unwrap_or_default()
	}
194763
	pub fn all_extrinsics_len() -> u32 {
194763
		AllExtrinsicsLen::<T>::get().unwrap_or_default()
194763
	}
	/// Inform the system pallet of some additional weight that should be accounted for, in the
	/// current block.
	///
	/// NOTE: use with extra care; this function is made public only be used for certain pallets
	/// that need it. A runtime that does not have dynamic calls should never need this and should
	/// stick to static weights. A typical use case for this is inner calls or smart contract calls.
	/// Furthermore, it only makes sense to use this when it is presumably  _cheap_ to provide the
	/// argument `weight`; In other words, if this function is to be used to account for some
	/// unknown, user provided call's weight, it would only make sense to use it if you are sure you
	/// can rapidly compute the weight of the inner call.
	///
	/// Even more dangerous is to note that this function does NOT take any action, if the new sum
	/// of block weight is more than the block weight limit. This is what the _unchecked_.
	///
	/// Another potential use-case could be for the `on_initialize` and `on_finalize` hooks.
449061
	pub fn register_extra_weight_unchecked(weight: Weight, class: DispatchClass) {
598748
		BlockWeight::<T>::mutate(|current_weight| {
449061
			current_weight.accrue(weight, class);
598748
		});
449061
	}
	/// Start the execution of a particular block.
194763
	pub fn initialize(number: &BlockNumberFor<T>, parent_hash: &T::Hash, digest: &generic::Digest) {
194763
		// populate environment
194763
		ExecutionPhase::<T>::put(Phase::Initialization);
194763
		storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &0u32);
194763
		let entropy = (b"frame_system::initialize", parent_hash).using_encoded(blake2_256);
194763
		storage::unhashed::put_raw(well_known_keys::INTRABLOCK_ENTROPY, &entropy[..]);
194763
		<Number<T>>::put(number);
194763
		<Digest<T>>::put(digest);
194763
		<ParentHash<T>>::put(parent_hash);
194763
		<BlockHash<T>>::insert(*number - One::one(), parent_hash);
194763
		<InherentsApplied<T>>::kill();
194763

            
194763
		// Remove previous block data from storage
194763
		BlockWeight::<T>::kill();
194763
	}
	/// Remove temporary "environment" entries in storage, compute the storage root and return the
	/// resulting header for this block.
194763
	pub fn finalize() -> HeaderFor<T> {
194763
		log::debug!(
			target: LOG_TARGET,
			"[{:?}] {} extrinsics, length: {} (normal {}%, op: {}%, mandatory {}%) / normal weight:\
			 {} ({}%) op weight {} ({}%) / mandatory weight {} ({}%)",
			Self::block_number(),
			Self::extrinsic_count(),
			Self::all_extrinsics_len(),
			sp_runtime::Percent::from_rational(
				Self::all_extrinsics_len(),
				*T::BlockLength::get().max.get(DispatchClass::Normal)
			).deconstruct(),
			sp_runtime::Percent::from_rational(
				Self::all_extrinsics_len(),
				*T::BlockLength::get().max.get(DispatchClass::Operational)
			).deconstruct(),
			sp_runtime::Percent::from_rational(
				Self::all_extrinsics_len(),
				*T::BlockLength::get().max.get(DispatchClass::Mandatory)
			).deconstruct(),
			Self::block_weight().get(DispatchClass::Normal),
			sp_runtime::Percent::from_rational(
				Self::block_weight().get(DispatchClass::Normal).ref_time(),
				T::BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap_or(Bounded::max_value()).ref_time()
			).deconstruct(),
			Self::block_weight().get(DispatchClass::Operational),
			sp_runtime::Percent::from_rational(
				Self::block_weight().get(DispatchClass::Operational).ref_time(),
				T::BlockWeights::get().get(DispatchClass::Operational).max_total.unwrap_or(Bounded::max_value()).ref_time()
			).deconstruct(),
			Self::block_weight().get(DispatchClass::Mandatory),
			sp_runtime::Percent::from_rational(
				Self::block_weight().get(DispatchClass::Mandatory).ref_time(),
				T::BlockWeights::get().get(DispatchClass::Mandatory).max_total.unwrap_or(Bounded::max_value()).ref_time()
			).deconstruct(),
		);
194763
		ExecutionPhase::<T>::kill();
194763
		AllExtrinsicsLen::<T>::kill();
194763
		storage::unhashed::kill(well_known_keys::INTRABLOCK_ENTROPY);
194763
		InherentsApplied::<T>::kill();
194763

            
194763
		// The following fields
194763
		//
194763
		// - <Events<T>>
194763
		// - <EventCount<T>>
194763
		// - <EventTopics<T>>
194763
		// - <Number<T>>
194763
		// - <ParentHash<T>>
194763
		// - <Digest<T>>
194763
		//
194763
		// stay to be inspected by the client and will be cleared by `Self::initialize`.
194763
		let number = <Number<T>>::get();
194763
		let parent_hash = <ParentHash<T>>::get();
194763
		let digest = <Digest<T>>::get();
194763

            
194763
		let extrinsics = (0..ExtrinsicCount::<T>::take().unwrap_or_default())
194763
			.map(ExtrinsicData::<T>::take)
194763
			.collect();
194763
		let extrinsics_root = extrinsics_data_root::<T::Hashing>(extrinsics);
194763

            
194763
		// move block hash pruning window by one block
194763
		let block_hash_count = T::BlockHashCount::get();
194763
		let to_remove = number.saturating_sub(block_hash_count).saturating_sub(One::one());
194763

            
194763
		// keep genesis hash
194763
		if !to_remove.is_zero() {
118404
			<BlockHash<T>>::remove(to_remove);
118404
		}
194763
		let version = T::Version::get().state_version();
194763
		let storage_root = T::Hash::decode(&mut &sp_io::storage::root(version)[..])
194763
			.expect("Node is configured to use the same hash; qed");
194763

            
194763
		HeaderFor::<T>::new(number, extrinsics_root, storage_root, parent_hash, digest)
194763
	}
	/// Deposits a log and ensures it matches the block's log data.
263811
	pub fn deposit_log(item: generic::DigestItem) {
263811
		<Digest<T>>::append(item);
263811
	}
	/// Get the basic externalities for this pallet, useful for tests.
	#[cfg(any(feature = "std", test))]
	pub fn externalities() -> TestExternalities {
		TestExternalities::new(sp_core::storage::Storage {
			top: map![
				<BlockHash<T>>::hashed_key_for(BlockNumberFor::<T>::zero()) => [69u8; 32].encode(),
				<Number<T>>::hashed_key().to_vec() => BlockNumberFor::<T>::one().encode(),
				<ParentHash<T>>::hashed_key().to_vec() => [69u8; 32].encode()
			],
			children_default: map![],
		})
	}
	/// Get the current events deposited by the runtime.
	///
	/// NOTE: This should only be used in tests. Reading events from the runtime can have a large
	/// impact on the PoV size of a block. Users should use alternative and well bounded storage
	/// items for any behavior like this.
	///
	/// NOTE: Events not registered at the genesis block and quietly omitted.
	#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
	pub fn events() -> Vec<EventRecord<T::RuntimeEvent, T::Hash>> {
		// Dereferencing the events here is fine since we are not in the memory-restricted runtime.
		Self::read_events_no_consensus().map(|e| *e).collect()
	}
	/// Get a single event at specified index.
	///
	/// Should only be called if you know what you are doing and outside of the runtime block
	/// execution else it can have a large impact on the PoV size of a block.
	pub fn event_no_consensus(index: usize) -> Option<T::RuntimeEvent> {
		Self::read_events_no_consensus().nth(index).map(|e| e.event.clone())
	}
	/// Get the current events deposited by the runtime.
	///
	/// Should only be called if you know what you are doing and outside of the runtime block
	/// execution else it can have a large impact on the PoV size of a block.
	pub fn read_events_no_consensus(
	) -> impl Iterator<Item = Box<EventRecord<T::RuntimeEvent, T::Hash>>> {
		Events::<T>::stream_iter()
	}
	/// Read and return the events of a specific pallet, as denoted by `E`.
	///
	/// This is useful for a pallet that wishes to read only the events it has deposited into
	/// `frame_system` using the standard `fn deposit_event`.
	pub fn read_events_for_pallet<E>() -> Vec<E>
	where
		T::RuntimeEvent: TryInto<E>,
	{
		Events::<T>::get()
			.into_iter()
			.map(|er| er.event)
			.filter_map(|e| e.try_into().ok())
			.collect::<_>()
	}
	/// Set the block number to something in particular. Can be used as an alternative to
	/// `initialize` for tests that don't need to bother with the other environment entries.
	#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
	pub fn set_block_number(n: BlockNumberFor<T>) {
		<Number<T>>::put(n);
	}
	/// Sets the index of extrinsic that is currently executing.
	#[cfg(any(feature = "std", test))]
	pub fn set_extrinsic_index(extrinsic_index: u32) {
		storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &extrinsic_index)
	}
	/// Set the parent hash number to something in particular. Can be used as an alternative to
	/// `initialize` for tests that don't need to bother with the other environment entries.
	#[cfg(any(feature = "std", test))]
	pub fn set_parent_hash(n: T::Hash) {
		<ParentHash<T>>::put(n);
	}
	/// Set the current block weight. This should only be used in some integration tests.
	#[cfg(any(feature = "std", test))]
53637
	pub fn set_block_consumed_resources(weight: Weight, len: usize) {
71516
		BlockWeight::<T>::mutate(|current_weight| {
53637
			current_weight.set(weight, DispatchClass::Normal)
71516
		});
53637
		AllExtrinsicsLen::<T>::put(len as u32);
53637
	}
	/// Reset events.
	///
	/// This needs to be used in prior calling [`initialize`](Self::initialize) for each new block
	/// to clear events from previous block.
194763
	pub fn reset_events() {
194763
		<Events<T>>::kill();
194763
		EventCount::<T>::kill();
194763
		let _ = <EventTopics<T>>::clear(u32::max_value(), None);
194763
	}
	/// Assert the given `event` exists.
	///
	/// NOTE: Events not registered at the genesis block and quietly omitted.
	#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
	pub fn assert_has_event(event: T::RuntimeEvent) {
		let events = Self::events();
		assert!(
			events.iter().any(|record| record.event == event),
			"expected event {event:?} not found in events {events:?}",
		);
	}
	/// Assert the last event equal to the given `event`.
	///
	/// NOTE: Events not registered at the genesis block and quietly omitted.
	#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
	pub fn assert_last_event(event: T::RuntimeEvent) {
		let last_event = Self::events().last().expect("events expected").event.clone();
		assert_eq!(
			last_event, event,
			"expected event {event:?} is not equal to the last event {last_event:?}",
		);
	}
	/// Return the chain's current runtime version.
	pub fn runtime_version() -> RuntimeVersion {
		T::Version::get()
	}
	/// Retrieve the account transaction counter from storage.
	pub fn account_nonce(who: impl EncodeLike<T::AccountId>) -> T::Nonce {
		Account::<T>::get(who).nonce
	}
	/// Increment a particular account's nonce by 1.
	pub fn inc_account_nonce(who: impl EncodeLike<T::AccountId>) {
		Account::<T>::mutate(who, |a| a.nonce += T::Nonce::one());
	}
	/// Note what the extrinsic data of the current extrinsic index is.
	///
	/// This is required to be called before applying an extrinsic. The data will used
	/// in [`Self::finalize`] to calculate the correct extrinsics root.
194763
	pub fn note_extrinsic(encoded_xt: Vec<u8>) {
194763
		ExtrinsicData::<T>::insert(Self::extrinsic_index().unwrap_or_default(), encoded_xt);
194763
	}
	/// To be called immediately after an extrinsic has been applied.
	///
	/// Emits an `ExtrinsicSuccess` or `ExtrinsicFailed` event depending on the outcome.
	/// The emitted event contains the post-dispatch corrected weight including
	/// the base-weight for its dispatch class.
194763
	pub fn note_applied_extrinsic(r: &DispatchResultWithPostInfo, mut info: DispatchInfo) {
194763
		info.weight = extract_actual_weight(r, &info)
194763
			.saturating_add(T::BlockWeights::get().get(info.class).base_extrinsic);
194763
		info.pays_fee = extract_actual_pays_fee(r, &info);
194763

            
194763
		Self::deposit_event(match r {
194763
			Ok(_) => Event::ExtrinsicSuccess { dispatch_info: info },
			Err(err) => {
				log::trace!(
					target: LOG_TARGET,
					"Extrinsic failed at block({:?}): {:?}",
					Self::block_number(),
					err,
				);
				Event::ExtrinsicFailed { dispatch_error: err.error, dispatch_info: info }
			},
		});
194763
		let next_extrinsic_index = Self::extrinsic_index().unwrap_or_default() + 1u32;
194763

            
194763
		storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &next_extrinsic_index);
194763
		ExecutionPhase::<T>::put(Phase::ApplyExtrinsic(next_extrinsic_index));
194763
	}
	/// To be called immediately after `note_applied_extrinsic` of the last extrinsic of the block
	/// has been called.
194763
	pub fn note_finished_extrinsics() {
194763
		let extrinsic_index: u32 =
194763
			storage::unhashed::take(well_known_keys::EXTRINSIC_INDEX).unwrap_or_default();
194763
		ExtrinsicCount::<T>::put(extrinsic_index);
194763
		ExecutionPhase::<T>::put(Phase::Finalization);
194763
	}
	/// To be called immediately after finishing the initialization of the block
	/// (e.g., called `on_initialize` for all pallets).
194763
	pub fn note_finished_initialize() {
194763
		ExecutionPhase::<T>::put(Phase::ApplyExtrinsic(0))
194763
	}
	/// An account is being created.
702
	pub fn on_created_account(who: T::AccountId, _a: &mut AccountInfo<T::Nonce, T::AccountData>) {
702
		T::OnNewAccount::on_new_account(&who);
702
		Self::deposit_event(Event::NewAccount { account: who });
702
	}
	/// Do anything that needs to be done after an account has been killed.
159
	fn on_killed_account(who: T::AccountId) {
159
		T::OnKilledAccount::on_killed_account(&who);
159
		Self::deposit_event(Event::KilledAccount { account: who });
159
	}
	/// Determine whether or not it is possible to update the code.
	///
	/// Checks the given code if it is a valid runtime wasm blob by instantiating
	/// it and extracting the runtime version of it. It checks that the runtime version
	/// of the old and new runtime has the same spec name and that the spec version is increasing.
	pub fn can_set_code(code: &[u8]) -> Result<(), sp_runtime::DispatchError> {
		if T::MultiBlockMigrator::ongoing() {
			return Err(Error::<T>::MultiBlockMigrationsOngoing.into())
		}
		let current_version = T::Version::get();
		let new_version = sp_io::misc::runtime_version(code)
			.and_then(|v| RuntimeVersion::decode(&mut &v[..]).ok())
			.ok_or(Error::<T>::FailedToExtractRuntimeVersion)?;
		cfg_if::cfg_if! {
			if #[cfg(all(feature = "runtime-benchmarks", not(test)))] {
					// Let's ensure the compiler doesn't optimize our fetching of the runtime version away.
					core::hint::black_box((new_version, current_version));
					Ok(())
			} else {
				if new_version.spec_name != current_version.spec_name {
					return Err(Error::<T>::InvalidSpecName.into())
				}
				if new_version.spec_version <= current_version.spec_version {
					return Err(Error::<T>::SpecVersionNeedsToIncrease.into())
				}
				Ok(())
			}
		}
	}
	/// To be called after any origin/privilege checks. Put the code upgrade authorization into
	/// storage and emit an event. Infallible.
	pub fn do_authorize_upgrade(code_hash: T::Hash, check_version: bool) {
		AuthorizedUpgrade::<T>::put(CodeUpgradeAuthorization { code_hash, check_version });
		Self::deposit_event(Event::UpgradeAuthorized { code_hash, check_version });
	}
	/// Apply an authorized upgrade, performing any validation checks, and remove the authorization.
	/// Whether or not the code is set directly depends on the `OnSetCode` configuration of the
	/// runtime.
	pub fn do_apply_authorize_upgrade(code: Vec<u8>) -> Result<PostDispatchInfo, DispatchError> {
		Self::validate_authorized_upgrade(&code[..])?;
		T::OnSetCode::set_code(code)?;
		AuthorizedUpgrade::<T>::kill();
		let post = PostDispatchInfo {
			// consume the rest of the block to prevent further transactions
			actual_weight: Some(T::BlockWeights::get().max_block),
			// no fee for valid upgrade
			pays_fee: Pays::No,
		};
		Ok(post)
	}
	/// Check that provided `code` can be upgraded to. Namely, check that its hash matches an
	/// existing authorization and that it meets the specification requirements of `can_set_code`.
	pub fn validate_authorized_upgrade(code: &[u8]) -> Result<T::Hash, DispatchError> {
		let authorization = AuthorizedUpgrade::<T>::get().ok_or(Error::<T>::NothingAuthorized)?;
		let actual_hash = T::Hashing::hash(code);
		ensure!(actual_hash == authorization.code_hash, Error::<T>::Unauthorized);
		if authorization.check_version {
			Self::can_set_code(code)?
		}
		Ok(actual_hash)
	}
}
/// Returns a 32 byte datum which is guaranteed to be universally unique. `entropy` is provided
/// as a facility to reduce the potential for precalculating results.
6927
pub fn unique(entropy: impl Encode) -> [u8; 32] {
6927
	let mut last = [0u8; 32];
6927
	sp_io::storage::read(well_known_keys::INTRABLOCK_ENTROPY, &mut last[..], 0);
6927
	let next = (b"frame_system::unique", entropy, last).using_encoded(blake2_256);
6927
	sp_io::storage::set(well_known_keys::INTRABLOCK_ENTROPY, &next);
6927
	next
6927
}
/// Event handler which registers a provider when created.
pub struct Provider<T>(PhantomData<T>);
impl<T: Config> HandleLifetime<T::AccountId> for Provider<T> {
	fn created(t: &T::AccountId) -> Result<(), DispatchError> {
		Pallet::<T>::inc_providers(t);
		Ok(())
	}
	fn killed(t: &T::AccountId) -> Result<(), DispatchError> {
		Pallet::<T>::dec_providers(t).map(|_| ())
	}
}
/// Event handler which registers a self-sufficient when created.
pub struct SelfSufficient<T>(PhantomData<T>);
impl<T: Config> HandleLifetime<T::AccountId> for SelfSufficient<T> {
	fn created(t: &T::AccountId) -> Result<(), DispatchError> {
		Pallet::<T>::inc_sufficients(t);
		Ok(())
	}
	fn killed(t: &T::AccountId) -> Result<(), DispatchError> {
		Pallet::<T>::dec_sufficients(t);
		Ok(())
	}
}
/// Event handler which registers a consumer when created.
pub struct Consumer<T>(PhantomData<T>);
impl<T: Config> HandleLifetime<T::AccountId> for Consumer<T> {
	fn created(t: &T::AccountId) -> Result<(), DispatchError> {
		Pallet::<T>::inc_consumers(t)
	}
	fn killed(t: &T::AccountId) -> Result<(), DispatchError> {
		Pallet::<T>::dec_consumers(t);
		Ok(())
	}
}
impl<T: Config> BlockNumberProvider for Pallet<T> {
	type BlockNumber = BlockNumberFor<T>;
	fn current_block_number() -> Self::BlockNumber {
		Pallet::<T>::block_number()
	}
	#[cfg(feature = "runtime-benchmarks")]
	fn set_block_number(n: BlockNumberFor<T>) {
		Self::set_block_number(n)
	}
}
/// Implement StoredMap for a simple single-item, provide-when-not-default system. This works fine
/// for storing a single item which allows the account to continue existing as long as it's not
/// empty/default.
///
/// Anything more complex will need more sophisticated logic.
impl<T: Config> StoredMap<T::AccountId, T::AccountData> for Pallet<T> {
261882
	fn get(k: &T::AccountId) -> T::AccountData {
261882
		Account::<T>::get(k).data
261882
	}
20781
	fn try_mutate_exists<R, E: From<DispatchError>>(
20781
		k: &T::AccountId,
20781
		f: impl FnOnce(&mut Option<T::AccountData>) -> Result<R, E>,
20781
	) -> Result<R, E> {
20781
		let account = Account::<T>::get(k);
20781
		let is_default = account.data == T::AccountData::default();
20781
		let mut some_data = if is_default { None } else { Some(account.data) };
20781
		let result = f(&mut some_data)?;
18963
		if Self::providers(k) > 0 || Self::sufficients(k) > 0 {
24004
			Account::<T>::mutate(k, |a| a.data = some_data.unwrap_or_default());
18003
		} else {
960
			Account::<T>::remove(k)
		}
18963
		Ok(result)
20781
	}
}
/// Split an `option` into two constituent options, as defined by a `splitter` function.
pub fn split_inner<T, R, S>(
	option: Option<T>,
	splitter: impl FnOnce(T) -> (R, S),
) -> (Option<R>, Option<S>) {
	match option {
		Some(inner) => {
			let (r, s) = splitter(inner);
			(Some(r), Some(s))
		},
		None => (None, None),
	}
}
pub struct ChainContext<T>(PhantomData<T>);
impl<T> Default for ChainContext<T> {
194763
	fn default() -> Self {
194763
		ChainContext(PhantomData)
194763
	}
}
impl<T: Config> Lookup for ChainContext<T> {
	type Source = <T::Lookup as StaticLookup>::Source;
	type Target = <T::Lookup as StaticLookup>::Target;
	fn lookup(&self, s: Self::Source) -> Result<Self::Target, LookupError> {
		<T::Lookup as StaticLookup>::lookup(s)
	}
}
/// Prelude to be used alongside pallet macro, for ease of use.
pub mod pallet_prelude {
	pub use crate::{ensure_none, ensure_root, ensure_signed, ensure_signed_or_root};
	/// Type alias for the `Origin` associated type of system config.
	pub type OriginFor<T> = <T as crate::Config>::RuntimeOrigin;
	/// Type alias for the `Header`.
	pub type HeaderFor<T> =
		<<T as crate::Config>::Block as sp_runtime::traits::HeaderProvider>::HeaderT;
	/// Type alias for the `BlockNumber` associated type of system config.
	pub type BlockNumberFor<T> = <HeaderFor<T> as sp_runtime::traits::Header>::Number;
	/// Type alias for the `Extrinsic` associated type of system config.
	pub type ExtrinsicFor<T> =
		<<T as crate::Config>::Block as sp_runtime::traits::Block>::Extrinsic;
	/// Type alias for the `RuntimeCall` associated type of system config.
	pub type RuntimeCallFor<T> = <T as crate::Config>::RuntimeCall;
}