#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;
use alloc::{borrow::Cow, boxed::Box, vec, vec::Vec};
use core::{fmt::Debug, marker::PhantomData};
use pallet_prelude::{BlockNumberFor, HeaderFor};
#[cfg(feature = "std")]
use serde::Serialize;
use sp_io::hashing::blake2_256;
#[cfg(feature = "runtime-benchmarks")]
use sp_runtime::traits::TrailingZeroInput;
use sp_runtime::{
generic,
traits::{
self, AtLeast32Bit, BadOrigin, BlockNumberProvider, Bounded, CheckEqual, Dispatchable,
Hash, Header, Lookup, LookupError, MaybeDisplay, MaybeSerializeDeserialize, Member, One,
Saturating, SimpleBitOps, StaticLookup, Zero,
},
transaction_validity::{
InvalidTransaction, TransactionLongevity, TransactionSource, TransactionValidity,
ValidTransaction,
},
DispatchError, RuntimeDebug,
};
use sp_version::RuntimeVersion;
use codec::{Decode, DecodeWithMemTracking, Encode, EncodeLike, FullCodec, MaxEncodedLen};
#[cfg(feature = "std")]
use frame_support::traits::BuildGenesisConfig;
use frame_support::{
dispatch::{
extract_actual_pays_fee, extract_actual_weight, DispatchClass, DispatchInfo,
DispatchResult, DispatchResultWithPostInfo, GetDispatchInfo, PerDispatchClass,
PostDispatchInfo,
},
ensure, impl_ensure_origin_with_arg_ignoring_arg,
migrations::MultiStepMigrator,
pallet_prelude::Pays,
storage::{self, StorageStreamIter},
traits::{
ConstU32, Contains, EnsureOrigin, EnsureOriginWithArg, Get, HandleLifetime,
OnKilledAccount, OnNewAccount, OnRuntimeUpgrade, OriginTrait, PalletInfo, SortedMembers,
StoredMap, TypedGet,
},
Parameter,
};
use scale_info::TypeInfo;
use sp_core::storage::well_known_keys;
use sp_runtime::{
traits::{DispatchInfoOf, PostDispatchInfoOf},
transaction_validity::TransactionValidityError,
};
use sp_weights::{RuntimeDbWeight, Weight};
#[cfg(any(feature = "std", test))]
use sp_io::TestExternalities;
pub mod limits;
#[cfg(test)]
pub(crate) mod mock;
pub mod offchain;
mod extensions;
#[cfg(feature = "std")]
pub mod mocking;
#[cfg(test)]
mod tests;
pub mod weights;
pub mod migrations;
pub use extensions::{
check_genesis::CheckGenesis, check_mortality::CheckMortality,
check_non_zero_sender::CheckNonZeroSender, check_nonce::CheckNonce,
check_spec_version::CheckSpecVersion, check_tx_version::CheckTxVersion,
check_weight::CheckWeight, weight_reclaim::WeightReclaim,
weights::SubstrateWeight as SubstrateExtensionsWeight, WeightInfo as ExtensionsWeightInfo,
};
pub use extensions::check_mortality::CheckMortality as CheckEra;
pub use frame_support::dispatch::RawOrigin;
use frame_support::traits::{PostInherents, PostTransactions, PreInherents};
use sp_core::storage::StateVersion;
pub use weights::WeightInfo;
const LOG_TARGET: &str = "runtime::system";
pub fn extrinsics_root<H: Hash, E: codec::Encode>(
extrinsics: &[E],
state_version: StateVersion,
) -> H::Output {
extrinsics_data_root::<H>(extrinsics.iter().map(codec::Encode::encode).collect(), state_version)
}
pub fn extrinsics_data_root<H: Hash>(xts: Vec<Vec<u8>>, state_version: StateVersion) -> H::Output {
H::ordered_trie_root(xts, state_version)
}
pub type ConsumedWeight = PerDispatchClass<Weight>;
pub use pallet::*;
pub trait SetCode<T: Config> {
fn set_code(code: Vec<u8>) -> DispatchResult;
}
impl<T: Config> SetCode<T> for () {
fn set_code(code: Vec<u8>) -> DispatchResult {
<Pallet<T>>::update_code_in_storage(&code);
Ok(())
}
}
pub trait ConsumerLimits {
fn max_consumers() -> RefCount;
fn max_overflow() -> RefCount;
}
impl<const Z: u32> ConsumerLimits for ConstU32<Z> {
fn max_consumers() -> RefCount {
Z
}
fn max_overflow() -> RefCount {
Z
}
}
impl<MaxNormal: Get<u32>, MaxOverflow: Get<u32>> ConsumerLimits for (MaxNormal, MaxOverflow) {
fn max_consumers() -> RefCount {
MaxNormal::get()
}
fn max_overflow() -> RefCount {
MaxOverflow::get()
}
}
#[derive(Decode, Encode, Default, PartialEq, Eq, MaxEncodedLen, TypeInfo)]
#[scale_info(skip_type_params(T))]
pub struct CodeUpgradeAuthorization<T>
where
T: Config,
{
code_hash: T::Hash,
check_version: bool,
}
#[derive(
Clone,
Copy,
Eq,
PartialEq,
Default,
RuntimeDebug,
Encode,
Decode,
DecodeWithMemTracking,
TypeInfo,
)]
pub struct DispatchEventInfo {
pub weight: Weight,
pub class: DispatchClass,
pub pays_fee: Pays,
}
#[frame_support::pallet]
pub mod pallet {
use crate::{self as frame_system, pallet_prelude::*, *};
use codec::HasCompact;
use frame_support::pallet_prelude::*;
pub mod config_preludes {
use super::{inject_runtime_type, DefaultConfig};
use frame_support::{derive_impl, traits::Get};
pub struct TestBlockHashCount<C: Get<u32>>(core::marker::PhantomData<C>);
impl<I: From<u32>, C: Get<u32>> Get<I> for TestBlockHashCount<C> {
fn get() -> I {
C::get().into()
}
}
pub struct TestDefaultConfig;
#[frame_support::register_default_impl(TestDefaultConfig)]
impl DefaultConfig for TestDefaultConfig {
type Nonce = u32;
type Hash = sp_core::hash::H256;
type Hashing = sp_runtime::traits::BlakeTwo256;
type AccountId = u64;
type Lookup = sp_runtime::traits::IdentityLookup<Self::AccountId>;
type MaxConsumers = frame_support::traits::ConstU32<16>;
type AccountData = ();
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type ExtensionsWeightInfo = ();
type SS58Prefix = ();
type Version = ();
type BlockWeights = ();
type BlockLength = ();
type DbWeight = ();
#[inject_runtime_type]
type RuntimeEvent = ();
#[inject_runtime_type]
type RuntimeOrigin = ();
#[inject_runtime_type]
type RuntimeCall = ();
#[inject_runtime_type]
type PalletInfo = ();
#[inject_runtime_type]
type RuntimeTask = ();
type BaseCallFilter = frame_support::traits::Everything;
type BlockHashCount = TestBlockHashCount<frame_support::traits::ConstU32<10>>;
type OnSetCode = ();
type SingleBlockMigrations = ();
type MultiBlockMigrator = ();
type PreInherents = ();
type PostInherents = ();
type PostTransactions = ();
}
pub struct SolochainDefaultConfig;
#[frame_support::register_default_impl(SolochainDefaultConfig)]
impl DefaultConfig for SolochainDefaultConfig {
type Nonce = u32;
type Hash = sp_core::hash::H256;
type Hashing = sp_runtime::traits::BlakeTwo256;
type AccountId = sp_runtime::AccountId32;
type Lookup = sp_runtime::traits::AccountIdLookup<Self::AccountId, ()>;
type MaxConsumers = frame_support::traits::ConstU32<128>;
type AccountData = ();
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type ExtensionsWeightInfo = ();
type SS58Prefix = ();
type Version = ();
type BlockWeights = ();
type BlockLength = ();
type DbWeight = ();
#[inject_runtime_type]
type RuntimeEvent = ();
#[inject_runtime_type]
type RuntimeOrigin = ();
#[inject_runtime_type]
type RuntimeCall = ();
#[inject_runtime_type]
type RuntimeTask = ();
#[inject_runtime_type]
type PalletInfo = ();
type BaseCallFilter = frame_support::traits::Everything;
type BlockHashCount = TestBlockHashCount<frame_support::traits::ConstU32<256>>;
type OnSetCode = ();
type SingleBlockMigrations = ();
type MultiBlockMigrator = ();
type PreInherents = ();
type PostInherents = ();
type PostTransactions = ();
}
pub struct RelayChainDefaultConfig;
#[derive_impl(SolochainDefaultConfig as DefaultConfig, no_aggregated_types)]
#[frame_support::register_default_impl(RelayChainDefaultConfig)]
impl DefaultConfig for RelayChainDefaultConfig {}
pub struct ParaChainDefaultConfig;
#[derive_impl(SolochainDefaultConfig as DefaultConfig, no_aggregated_types)]
#[frame_support::register_default_impl(ParaChainDefaultConfig)]
impl DefaultConfig for ParaChainDefaultConfig {}
}
#[pallet::config(with_default)]
#[pallet::disable_frame_system_supertrait_check]
pub trait Config: 'static + Eq + Clone {
#[pallet::no_default_bounds]
type RuntimeEvent: Parameter
+ Member
+ From<Event<Self>>
+ Debug
+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
#[pallet::no_default_bounds]
type BaseCallFilter: Contains<Self::RuntimeCall>;
#[pallet::constant]
type BlockWeights: Get<limits::BlockWeights>;
#[pallet::constant]
type BlockLength: Get<limits::BlockLength>;
#[pallet::no_default_bounds]
type RuntimeOrigin: Into<Result<RawOrigin<Self::AccountId>, Self::RuntimeOrigin>>
+ From<RawOrigin<Self::AccountId>>
+ Clone
+ OriginTrait<Call = Self::RuntimeCall, AccountId = Self::AccountId>;
#[docify::export(system_runtime_call)]
#[pallet::no_default_bounds]
type RuntimeCall: Parameter
+ Dispatchable<RuntimeOrigin = Self::RuntimeOrigin>
+ Debug
+ GetDispatchInfo
+ From<Call<Self>>;
#[pallet::no_default_bounds]
type RuntimeTask: Task;
type Nonce: Parameter
+ HasCompact<Type: DecodeWithMemTracking>
+ Member
+ MaybeSerializeDeserialize
+ Debug
+ Default
+ MaybeDisplay
+ AtLeast32Bit
+ Copy
+ MaxEncodedLen;
type Hash: Parameter
+ Member
+ MaybeSerializeDeserialize
+ Debug
+ MaybeDisplay
+ SimpleBitOps
+ Ord
+ Default
+ Copy
+ CheckEqual
+ core::hash::Hash
+ AsRef<[u8]>
+ AsMut<[u8]>
+ MaxEncodedLen;
type Hashing: Hash<Output = Self::Hash> + TypeInfo;
type AccountId: Parameter
+ Member
+ MaybeSerializeDeserialize
+ Debug
+ MaybeDisplay
+ Ord
+ MaxEncodedLen;
type Lookup: StaticLookup<Target = Self::AccountId>;
#[pallet::no_default]
type Block: Parameter + Member + traits::Block<Hash = Self::Hash>;
#[pallet::constant]
#[pallet::no_default_bounds]
type BlockHashCount: Get<BlockNumberFor<Self>>;
#[pallet::constant]
type DbWeight: Get<RuntimeDbWeight>;
#[pallet::constant]
type Version: Get<RuntimeVersion>;
#[pallet::no_default_bounds]
type PalletInfo: PalletInfo;
type AccountData: Member + FullCodec + Clone + Default + TypeInfo + MaxEncodedLen;
type OnNewAccount: OnNewAccount<Self::AccountId>;
type OnKilledAccount: OnKilledAccount<Self::AccountId>;
type SystemWeightInfo: WeightInfo;
type ExtensionsWeightInfo: extensions::WeightInfo;
#[pallet::constant]
type SS58Prefix: Get<u16>;
#[pallet::no_default_bounds]
type OnSetCode: SetCode<Self>;
type MaxConsumers: ConsumerLimits;
type SingleBlockMigrations: OnRuntimeUpgrade;
type MultiBlockMigrator: MultiStepMigrator;
type PreInherents: PreInherents;
type PostInherents: PostInherents;
type PostTransactions: PostTransactions;
}
#[pallet::pallet]
pub struct Pallet<T>(_);
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
#[cfg(feature = "std")]
fn integrity_test() {
T::BlockWeights::get().validate().expect("The weights are invalid.");
}
}
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight(T::SystemWeightInfo::remark(remark.len() as u32))]
pub fn remark(_origin: OriginFor<T>, remark: Vec<u8>) -> DispatchResultWithPostInfo {
let _ = remark; Ok(().into())
}
#[pallet::call_index(1)]
#[pallet::weight((T::SystemWeightInfo::set_heap_pages(), DispatchClass::Operational))]
pub fn set_heap_pages(origin: OriginFor<T>, pages: u64) -> DispatchResultWithPostInfo {
ensure_root(origin)?;
storage::unhashed::put_raw(well_known_keys::HEAP_PAGES, &pages.encode());
Self::deposit_log(generic::DigestItem::RuntimeEnvironmentUpdated);
Ok(().into())
}
#[pallet::call_index(2)]
#[pallet::weight((T::SystemWeightInfo::set_code(), DispatchClass::Operational))]
pub fn set_code(origin: OriginFor<T>, code: Vec<u8>) -> DispatchResultWithPostInfo {
ensure_root(origin)?;
Self::can_set_code(&code, true).into_result()?;
T::OnSetCode::set_code(code)?;
Ok(Some(T::BlockWeights::get().max_block).into())
}
#[pallet::call_index(3)]
#[pallet::weight((T::SystemWeightInfo::set_code(), DispatchClass::Operational))]
pub fn set_code_without_checks(
origin: OriginFor<T>,
code: Vec<u8>,
) -> DispatchResultWithPostInfo {
ensure_root(origin)?;
Self::can_set_code(&code, false).into_result()?;
T::OnSetCode::set_code(code)?;
Ok(Some(T::BlockWeights::get().max_block).into())
}
#[pallet::call_index(4)]
#[pallet::weight((
T::SystemWeightInfo::set_storage(items.len() as u32),
DispatchClass::Operational,
))]
pub fn set_storage(
origin: OriginFor<T>,
items: Vec<KeyValue>,
) -> DispatchResultWithPostInfo {
ensure_root(origin)?;
for i in &items {
storage::unhashed::put_raw(&i.0, &i.1);
}
Ok(().into())
}
#[pallet::call_index(5)]
#[pallet::weight((
T::SystemWeightInfo::kill_storage(keys.len() as u32),
DispatchClass::Operational,
))]
pub fn kill_storage(origin: OriginFor<T>, keys: Vec<Key>) -> DispatchResultWithPostInfo {
ensure_root(origin)?;
for key in &keys {
storage::unhashed::kill(key);
}
Ok(().into())
}
#[pallet::call_index(6)]
#[pallet::weight((
T::SystemWeightInfo::kill_prefix(subkeys.saturating_add(1)),
DispatchClass::Operational,
))]
pub fn kill_prefix(
origin: OriginFor<T>,
prefix: Key,
subkeys: u32,
) -> DispatchResultWithPostInfo {
ensure_root(origin)?;
let _ = storage::unhashed::clear_prefix(&prefix, Some(subkeys), None);
Ok(().into())
}
#[pallet::call_index(7)]
#[pallet::weight(T::SystemWeightInfo::remark_with_event(remark.len() as u32))]
pub fn remark_with_event(
origin: OriginFor<T>,
remark: Vec<u8>,
) -> DispatchResultWithPostInfo {
let who = ensure_signed(origin)?;
let hash = T::Hashing::hash(&remark[..]);
Self::deposit_event(Event::Remarked { sender: who, hash });
Ok(().into())
}
#[cfg(feature = "experimental")]
#[pallet::call_index(8)]
#[pallet::weight(task.weight())]
pub fn do_task(_origin: OriginFor<T>, task: T::RuntimeTask) -> DispatchResultWithPostInfo {
if !task.is_valid() {
return Err(Error::<T>::InvalidTask.into())
}
Self::deposit_event(Event::TaskStarted { task: task.clone() });
if let Err(err) = task.run() {
Self::deposit_event(Event::TaskFailed { task, err });
return Err(Error::<T>::FailedTask.into())
}
Self::deposit_event(Event::TaskCompleted { task });
Ok(().into())
}
#[pallet::call_index(9)]
#[pallet::weight((T::SystemWeightInfo::authorize_upgrade(), DispatchClass::Operational))]
pub fn authorize_upgrade(origin: OriginFor<T>, code_hash: T::Hash) -> DispatchResult {
ensure_root(origin)?;
Self::do_authorize_upgrade(code_hash, true);
Ok(())
}
#[pallet::call_index(10)]
#[pallet::weight((T::SystemWeightInfo::authorize_upgrade(), DispatchClass::Operational))]
pub fn authorize_upgrade_without_checks(
origin: OriginFor<T>,
code_hash: T::Hash,
) -> DispatchResult {
ensure_root(origin)?;
Self::do_authorize_upgrade(code_hash, false);
Ok(())
}
#[pallet::call_index(11)]
#[pallet::weight((T::SystemWeightInfo::apply_authorized_upgrade(), DispatchClass::Operational))]
pub fn apply_authorized_upgrade(
_: OriginFor<T>,
code: Vec<u8>,
) -> DispatchResultWithPostInfo {
let res = Self::validate_code_is_authorized(&code)?;
AuthorizedUpgrade::<T>::kill();
match Self::can_set_code(&code, res.check_version) {
CanSetCodeResult::Ok => {},
CanSetCodeResult::MultiBlockMigrationsOngoing =>
return Err(Error::<T>::MultiBlockMigrationsOngoing.into()),
CanSetCodeResult::InvalidVersion(error) => {
Self::deposit_event(Event::RejectedInvalidAuthorizedUpgrade {
code_hash: res.code_hash,
error: error.into(),
});
return Ok(Pays::No.into())
},
};
T::OnSetCode::set_code(code)?;
Ok(PostDispatchInfo {
actual_weight: Some(T::BlockWeights::get().max_block),
pays_fee: Pays::No,
})
}
}
#[pallet::event]
pub enum Event<T: Config> {
ExtrinsicSuccess { dispatch_info: DispatchEventInfo },
ExtrinsicFailed { dispatch_error: DispatchError, dispatch_info: DispatchEventInfo },
CodeUpdated,
NewAccount { account: T::AccountId },
KilledAccount { account: T::AccountId },
Remarked { sender: T::AccountId, hash: T::Hash },
#[cfg(feature = "experimental")]
TaskStarted { task: T::RuntimeTask },
#[cfg(feature = "experimental")]
TaskCompleted { task: T::RuntimeTask },
#[cfg(feature = "experimental")]
TaskFailed { task: T::RuntimeTask, err: DispatchError },
UpgradeAuthorized { code_hash: T::Hash, check_version: bool },
RejectedInvalidAuthorizedUpgrade { code_hash: T::Hash, error: DispatchError },
}
#[pallet::error]
pub enum Error<T> {
InvalidSpecName,
SpecVersionNeedsToIncrease,
FailedToExtractRuntimeVersion,
NonDefaultComposite,
NonZeroRefCount,
CallFiltered,
MultiBlockMigrationsOngoing,
#[cfg(feature = "experimental")]
InvalidTask,
#[cfg(feature = "experimental")]
FailedTask,
NothingAuthorized,
Unauthorized,
}
#[pallet::origin]
pub type Origin<T> = RawOrigin<<T as Config>::AccountId>;
#[pallet::storage]
#[pallet::getter(fn account)]
pub type Account<T: Config> = StorageMap<
_,
Blake2_128Concat,
T::AccountId,
AccountInfo<T::Nonce, T::AccountData>,
ValueQuery,
>;
#[pallet::storage]
pub(super) type ExtrinsicCount<T: Config> = StorageValue<_, u32>;
#[pallet::storage]
pub type InherentsApplied<T: Config> = StorageValue<_, bool, ValueQuery>;
#[pallet::storage]
#[pallet::whitelist_storage]
#[pallet::getter(fn block_weight)]
pub type BlockWeight<T: Config> = StorageValue<_, ConsumedWeight, ValueQuery>;
#[pallet::storage]
#[pallet::whitelist_storage]
pub type AllExtrinsicsLen<T: Config> = StorageValue<_, u32>;
#[pallet::storage]
#[pallet::getter(fn block_hash)]
pub type BlockHash<T: Config> =
StorageMap<_, Twox64Concat, BlockNumberFor<T>, T::Hash, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn extrinsic_data)]
#[pallet::unbounded]
pub(super) type ExtrinsicData<T: Config> =
StorageMap<_, Twox64Concat, u32, Vec<u8>, ValueQuery>;
#[pallet::storage]
#[pallet::whitelist_storage]
#[pallet::getter(fn block_number)]
pub(super) type Number<T: Config> = StorageValue<_, BlockNumberFor<T>, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn parent_hash)]
pub(super) type ParentHash<T: Config> = StorageValue<_, T::Hash, ValueQuery>;
#[pallet::storage]
#[pallet::whitelist_storage]
#[pallet::unbounded]
#[pallet::getter(fn digest)]
pub(super) type Digest<T: Config> = StorageValue<_, generic::Digest, ValueQuery>;
#[pallet::storage]
#[pallet::whitelist_storage]
#[pallet::disable_try_decode_storage]
#[pallet::unbounded]
pub(super) type Events<T: Config> =
StorageValue<_, Vec<Box<EventRecord<T::RuntimeEvent, T::Hash>>>, ValueQuery>;
#[pallet::storage]
#[pallet::whitelist_storage]
#[pallet::getter(fn event_count)]
pub(super) type EventCount<T: Config> = StorageValue<_, EventIndex, ValueQuery>;
#[pallet::storage]
#[pallet::unbounded]
#[pallet::getter(fn event_topics)]
pub(super) type EventTopics<T: Config> =
StorageMap<_, Blake2_128Concat, T::Hash, Vec<(BlockNumberFor<T>, EventIndex)>, ValueQuery>;
#[pallet::storage]
#[pallet::unbounded]
pub type LastRuntimeUpgrade<T: Config> = StorageValue<_, LastRuntimeUpgradeInfo>;
#[pallet::storage]
pub(super) type UpgradedToU32RefCount<T: Config> = StorageValue<_, bool, ValueQuery>;
#[pallet::storage]
pub(super) type UpgradedToTripleRefCount<T: Config> = StorageValue<_, bool, ValueQuery>;
#[pallet::storage]
#[pallet::whitelist_storage]
pub(super) type ExecutionPhase<T: Config> = StorageValue<_, Phase>;
#[pallet::storage]
#[pallet::getter(fn authorized_upgrade)]
pub(super) type AuthorizedUpgrade<T: Config> =
StorageValue<_, CodeUpgradeAuthorization<T>, OptionQuery>;
#[pallet::storage]
#[pallet::whitelist_storage]
pub type ExtrinsicWeightReclaimed<T: Config> = StorageValue<_, Weight, ValueQuery>;
#[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> {
fn build(&self) {
<BlockHash<T>>::insert::<_, T::Hash>(BlockNumberFor::<T>::zero(), hash69());
<ParentHash<T>>::put::<T::Hash>(hash69());
<LastRuntimeUpgrade<T>>::put(LastRuntimeUpgradeInfo::from(T::Version::get()));
<UpgradedToU32RefCount<T>>::put(true);
<UpgradedToTripleRefCount<T>>::put(true);
sp_io::storage::set(well_known_keys::EXTRINSIC_INDEX, &0u32.encode());
}
}
#[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(res) = Self::validate_code_is_authorized(&code[..]) {
if Self::can_set_code(&code, false).is_ok() {
return Ok(ValidTransaction {
priority: u64::max_value(),
requires: Vec::new(),
provides: vec![res.code_hash.encode()],
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>);
#[derive(Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]
#[cfg_attr(feature = "std", derive(Serialize, PartialEq, Eq, Clone))]
pub enum Phase {
ApplyExtrinsic(u32),
Finalization,
Initialization,
}
impl Default for Phase {
fn default() -> Self {
Self::Initialization
}
}
#[derive(Encode, Decode, RuntimeDebug, TypeInfo)]
#[cfg_attr(feature = "std", derive(Serialize, PartialEq, Eq, Clone))]
pub struct EventRecord<E: Parameter + Member, T> {
pub phase: Phase,
pub event: E,
pub topics: Vec<T>,
}
fn hash69<T: AsMut<[u8]> + Default>() -> T {
let mut h = T::default();
h.as_mut().iter_mut().for_each(|byte| *byte = 69);
h
}
type EventIndex = u32;
pub type RefCount = u32;
#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)]
pub struct AccountInfo<Nonce, AccountData> {
pub nonce: Nonce,
pub consumers: RefCount,
pub providers: RefCount,
pub sufficients: RefCount,
pub data: AccountData,
}
#[derive(RuntimeDebug, Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "std", derive(PartialEq))]
pub struct LastRuntimeUpgradeInfo {
pub spec_version: codec::Compact<u32>,
pub spec_name: Cow<'static, str>,
}
impl LastRuntimeUpgradeInfo {
pub fn was_upgraded(&self, current: &RuntimeVersion) -> bool {
current.spec_version > self.spec_version.0 || current.spec_name != self.spec_name
}
}
impl From<RuntimeVersion> for LastRuntimeUpgradeInfo {
fn from(version: RuntimeVersion) -> Self {
Self { spec_version: version.spec_version.into(), spec_name: version.spec_name }
}
}
pub struct EnsureRoot<AccountId>(core::marker::PhantomData<AccountId>);
impl<O: OriginTrait, AccountId> EnsureOrigin<O> for EnsureRoot<AccountId> {
type Success = ();
fn try_origin(o: O) -> Result<Self::Success, O> {
match o.as_system_ref() {
Some(RawOrigin::Root) => Ok(()),
_ => Err(o),
}
}
#[cfg(feature = "runtime-benchmarks")]
fn try_successful_origin() -> Result<O, ()> {
Ok(O::root())
}
}
impl_ensure_origin_with_arg_ignoring_arg! {
impl< { O: .., AccountId: Decode, T } >
EnsureOriginWithArg<O, T> for EnsureRoot<AccountId>
{}
}
pub struct EnsureRootWithSuccess<AccountId, Success>(
core::marker::PhantomData<(AccountId, Success)>,
);
impl<O: OriginTrait, AccountId, Success: TypedGet> EnsureOrigin<O>
for EnsureRootWithSuccess<AccountId, Success>
{
type Success = Success::Type;
fn try_origin(o: O) -> Result<Self::Success, O> {
match o.as_system_ref() {
Some(RawOrigin::Root) => Ok(Success::get()),
_ => Err(o),
}
}
#[cfg(feature = "runtime-benchmarks")]
fn try_successful_origin() -> Result<O, ()> {
Ok(O::root())
}
}
impl_ensure_origin_with_arg_ignoring_arg! {
impl< { O: .., AccountId: Decode, Success: TypedGet, T } >
EnsureOriginWithArg<O, T> for EnsureRootWithSuccess<AccountId, Success>
{}
}
pub struct EnsureWithSuccess<Ensure, AccountId, Success>(
core::marker::PhantomData<(Ensure, AccountId, Success)>,
);
impl<O: OriginTrait, 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()
}
}
pub struct EnsureSigned<AccountId>(core::marker::PhantomData<AccountId>);
impl<O: OriginTrait<AccountId = AccountId>, AccountId: Decode + Clone> EnsureOrigin<O>
for EnsureSigned<AccountId>
{
type Success = AccountId;
fn try_origin(o: O) -> Result<Self::Success, O> {
match o.as_system_ref() {
Some(RawOrigin::Signed(who)) => Ok(who.clone()),
_ => Err(o),
}
}
#[cfg(feature = "runtime-benchmarks")]
fn try_successful_origin() -> Result<O, ()> {
let zero_account_id =
AccountId::decode(&mut TrailingZeroInput::zeroes()).map_err(|_| ())?;
Ok(O::signed(zero_account_id))
}
}
impl_ensure_origin_with_arg_ignoring_arg! {
impl< { O: OriginTrait<AccountId = AccountId>, AccountId: Decode + Clone, T } >
EnsureOriginWithArg<O, T> for EnsureSigned<AccountId>
{}
}
pub struct EnsureSignedBy<Who, AccountId>(core::marker::PhantomData<(Who, AccountId)>);
impl<
O: OriginTrait<AccountId = 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> {
match o.as_system_ref() {
Some(RawOrigin::Signed(ref who)) if Who::contains(who) => Ok(who.clone()),
_ => Err(o),
}
}
#[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::signed(first_member))
}
}
impl_ensure_origin_with_arg_ignoring_arg! {
impl< { O: OriginTrait<AccountId = AccountId>, Who: SortedMembers<AccountId>, AccountId: PartialEq + Clone + Ord + Decode, T } >
EnsureOriginWithArg<O, T> for EnsureSignedBy<Who, AccountId>
{}
}
pub struct EnsureNone<AccountId>(core::marker::PhantomData<AccountId>);
impl<O: OriginTrait<AccountId = AccountId>, AccountId> EnsureOrigin<O> for EnsureNone<AccountId> {
type Success = ();
fn try_origin(o: O) -> Result<Self::Success, O> {
match o.as_system_ref() {
Some(RawOrigin::None) => Ok(()),
_ => Err(o),
}
}
#[cfg(feature = "runtime-benchmarks")]
fn try_successful_origin() -> Result<O, ()> {
Ok(O::none())
}
}
impl_ensure_origin_with_arg_ignoring_arg! {
impl< { O: OriginTrait<AccountId = AccountId>, AccountId, T } >
EnsureOriginWithArg<O, T> for EnsureNone<AccountId>
{}
}
pub struct EnsureNever<Success>(core::marker::PhantomData<Success>);
impl<O, Success> EnsureOrigin<O> for EnsureNever<Success> {
type Success = Success;
fn try_origin(o: O) -> Result<Self::Success, O> {
Err(o)
}
#[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]
pub fn ensure_signed<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<AccountId, BadOrigin>
where
OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
{
match o.into() {
Ok(RawOrigin::Signed(t)) => Ok(t),
_ => Err(BadOrigin),
}
}
pub fn ensure_signed_or_root<OuterOrigin, AccountId>(
o: OuterOrigin,
) -> Result<Option<AccountId>, BadOrigin>
where
OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
{
match o.into() {
Ok(RawOrigin::Root) => Ok(None),
Ok(RawOrigin::Signed(t)) => Ok(Some(t)),
_ => Err(BadOrigin),
}
}
pub fn ensure_root<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<(), BadOrigin>
where
OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
{
match o.into() {
Ok(RawOrigin::Root) => Ok(()),
_ => Err(BadOrigin),
}
}
pub fn ensure_none<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<(), BadOrigin>
where
OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
{
match o.into() {
Ok(RawOrigin::None) => Ok(()),
_ => Err(BadOrigin),
}
}
#[derive(RuntimeDebug)]
pub enum RefStatus {
Referenced,
Unreferenced,
}
#[derive(Eq, PartialEq, RuntimeDebug)]
pub enum IncRefStatus {
Created,
Existed,
}
#[derive(Eq, PartialEq, RuntimeDebug)]
pub enum DecRefStatus {
Reaped,
Exists,
}
pub enum CanSetCodeResult<T: Config> {
Ok,
MultiBlockMigrationsOngoing,
InvalidVersion(Error<T>),
}
impl<T: Config> CanSetCodeResult<T> {
pub fn into_result(self) -> Result<(), DispatchError> {
match self {
Self::Ok => Ok(()),
Self::MultiBlockMigrationsOngoing =>
Err(Error::<T>::MultiBlockMigrationsOngoing.into()),
Self::InvalidVersion(err) => Err(err.into()),
}
}
pub fn is_ok(&self) -> bool {
matches!(self, Self::Ok)
}
}
impl<T: Config> Pallet<T> {
#[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)
}
pub fn account_exists(who: &T::AccountId) -> bool {
Account::<T>::contains_key(who)
}
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);
}
pub fn inherents_applied() -> bool {
InherentsApplied::<T>::get()
}
pub fn note_inherents_applied() {
InherentsApplied::<T>::put(true);
}
#[deprecated = "Use `inc_consumers` instead"]
pub fn inc_ref(who: &T::AccountId) {
let _ = Self::inc_consumers(who);
}
#[deprecated = "Use `dec_consumers` instead"]
pub fn dec_ref(who: &T::AccountId) {
let _ = Self::dec_consumers(who);
}
#[deprecated = "Use `consumers` instead"]
pub fn refs(who: &T::AccountId) -> RefCount {
Self::consumers(who)
}
#[deprecated = "Use `!is_provider_required` instead"]
pub fn allow_death(who: &T::AccountId) -> bool {
!Self::is_provider_required(who)
}
pub fn inc_providers(who: &T::AccountId) -> IncRefStatus {
Account::<T>::mutate(who, |a| {
if a.providers == 0 && a.sufficients == 0 {
a.providers = 1;
Self::on_created_account(who.clone(), a);
IncRefStatus::Created
} else {
a.providers = a.providers.saturating_add(1);
IncRefStatus::Existed
}
})
}
pub fn dec_providers(who: &T::AccountId) -> Result<DecRefStatus, DispatchError> {
Account::<T>::try_mutate_exists(who, |maybe_account| {
if let Some(mut account) = maybe_account.take() {
if account.providers == 0 {
log::error!(
target: LOG_TARGET,
"Logic error: Unexpected underflow in reducing provider",
);
account.providers = 1;
}
match (account.providers, account.consumers, account.sufficients) {
(1, 0, 0) => {
Pallet::<T>::on_killed_account(who.clone());
Ok(DecRefStatus::Reaped)
},
(1, c, _) if c > 0 => {
Err(DispatchError::ConsumerRemaining)
},
(x, _, _) => {
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)
}
})
}
pub fn inc_sufficients(who: &T::AccountId) -> IncRefStatus {
Account::<T>::mutate(who, |a| {
if a.providers + a.sufficients == 0 {
a.sufficients = 1;
Self::on_created_account(who.clone(), a);
IncRefStatus::Created
} else {
a.sufficients = a.sufficients.saturating_add(1);
IncRefStatus::Existed
}
})
}
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 {
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.saturating_sub(1);
*maybe_account = Some(account);
DecRefStatus::Exists
},
}
} else {
log::error!(
target: LOG_TARGET,
"Logic error: Account already dead when reducing provider",
);
DecRefStatus::Reaped
}
})
}
pub fn providers(who: &T::AccountId) -> RefCount {
Account::<T>::get(who).providers
}
pub fn sufficients(who: &T::AccountId) -> RefCount {
Account::<T>::get(who).sufficients
}
pub fn reference_count(who: &T::AccountId) -> RefCount {
let a = Account::<T>::get(who);
a.providers + a.sufficients
}
pub fn inc_consumers(who: &T::AccountId) -> Result<(), DispatchError> {
Account::<T>::try_mutate(who, |a| {
if a.providers > 0 {
if a.consumers < T::MaxConsumers::max_consumers() {
a.consumers = a.consumers.saturating_add(1);
Ok(())
} else {
Err(DispatchError::TooManyConsumers)
}
} else {
Err(DispatchError::NoProviders)
}
})
}
pub fn inc_consumers_without_limit(who: &T::AccountId) -> Result<(), DispatchError> {
Account::<T>::try_mutate(who, |a| {
if a.providers > 0 {
a.consumers = a.consumers.saturating_add(1);
Ok(())
} else {
Err(DispatchError::NoProviders)
}
})
}
pub fn dec_consumers(who: &T::AccountId) {
Account::<T>::mutate(who, |a| {
if a.consumers > 0 {
a.consumers -= 1;
} else {
log::error!(
target: LOG_TARGET,
"Logic error: Unexpected underflow in reducing consumer",
);
}
})
}
pub fn consumers(who: &T::AccountId) -> RefCount {
Account::<T>::get(who).consumers
}
pub fn is_provider_required(who: &T::AccountId) -> bool {
Account::<T>::get(who).consumers != 0
}
pub fn can_dec_provider(who: &T::AccountId) -> bool {
let a = Account::<T>::get(who);
a.consumers == 0 || a.providers > 1
}
pub fn can_accrue_consumers(who: &T::AccountId, amount: u32) -> bool {
let a = Account::<T>::get(who);
match a.consumers.checked_add(amount) {
Some(c) => a.providers > 0 && c <= T::MaxConsumers::max_consumers(),
None => false,
}
}
pub fn can_inc_consumer(who: &T::AccountId) -> bool {
Self::can_accrue_consumers(who, 1)
}
pub fn deposit_event(event: impl Into<T::RuntimeEvent>) {
Self::deposit_event_indexed(&[], event.into());
}
pub fn deposit_event_indexed(topics: &[T::Hash], event: T::RuntimeEvent) {
let block_number = Self::block_number();
if block_number.is_zero() {
return
}
let phase = ExecutionPhase::<T>::get().unwrap_or_default();
let event = EventRecord { phase, event, topics: topics.to_vec() };
let event_idx = {
let old_event_count = EventCount::<T>::get();
let new_event_count = match old_event_count.checked_add(1) {
None => return,
Some(nc) => nc,
};
EventCount::<T>::put(new_event_count);
old_event_count
};
Events::<T>::append(event);
for topic in topics {
<EventTopics<T>>::append(topic, &(block_number, event_idx));
}
}
pub fn extrinsic_index() -> Option<u32> {
storage::unhashed::get(well_known_keys::EXTRINSIC_INDEX)
}
pub fn extrinsic_count() -> u32 {
ExtrinsicCount::<T>::get().unwrap_or_default()
}
pub fn all_extrinsics_len() -> u32 {
AllExtrinsicsLen::<T>::get().unwrap_or_default()
}
pub fn register_extra_weight_unchecked(weight: Weight, class: DispatchClass) {
BlockWeight::<T>::mutate(|current_weight| {
current_weight.accrue(weight, class);
});
}
pub fn initialize(number: &BlockNumberFor<T>, parent_hash: &T::Hash, digest: &generic::Digest) {
ExecutionPhase::<T>::put(Phase::Initialization);
storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &0u32);
let entropy = (b"frame_system::initialize", parent_hash).using_encoded(blake2_256);
storage::unhashed::put_raw(well_known_keys::INTRABLOCK_ENTROPY, &entropy[..]);
<Number<T>>::put(number);
<Digest<T>>::put(digest);
<ParentHash<T>>::put(parent_hash);
<BlockHash<T>>::insert(*number - One::one(), parent_hash);
<InherentsApplied<T>>::kill();
BlockWeight::<T>::kill();
}
pub fn finalize() -> HeaderFor<T> {
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(),
);
ExecutionPhase::<T>::kill();
AllExtrinsicsLen::<T>::kill();
storage::unhashed::kill(well_known_keys::INTRABLOCK_ENTROPY);
InherentsApplied::<T>::kill();
let number = <Number<T>>::get();
let parent_hash = <ParentHash<T>>::get();
let digest = <Digest<T>>::get();
let extrinsics = (0..ExtrinsicCount::<T>::take().unwrap_or_default())
.map(ExtrinsicData::<T>::take)
.collect();
let extrinsics_root_state_version = T::Version::get().extrinsics_root_state_version();
let extrinsics_root =
extrinsics_data_root::<T::Hashing>(extrinsics, extrinsics_root_state_version);
let block_hash_count = T::BlockHashCount::get();
let to_remove = number.saturating_sub(block_hash_count).saturating_sub(One::one());
if !to_remove.is_zero() {
<BlockHash<T>>::remove(to_remove);
}
let version = T::Version::get().state_version();
let storage_root = T::Hash::decode(&mut &sp_io::storage::root(version)[..])
.expect("Node is configured to use the same hash; qed");
HeaderFor::<T>::new(number, extrinsics_root, storage_root, parent_hash, digest)
}
pub fn deposit_log(item: generic::DigestItem) {
<Digest<T>>::append(item);
}
#[cfg(any(feature = "std", test))]
pub fn externalities() -> TestExternalities {
TestExternalities::new(sp_core::storage::Storage {
top: [
(<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()),
]
.into_iter()
.collect(),
children_default: Default::default(),
})
}
#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
pub fn events() -> Vec<EventRecord<T::RuntimeEvent, T::Hash>> {
Self::read_events_no_consensus().map(|e| *e).collect()
}
pub fn event_no_consensus(index: usize) -> Option<T::RuntimeEvent> {
Self::read_events_no_consensus().nth(index).map(|e| e.event.clone())
}
pub fn read_events_no_consensus(
) -> impl Iterator<Item = Box<EventRecord<T::RuntimeEvent, T::Hash>>> {
Events::<T>::stream_iter()
}
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::<_>()
}
#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
pub fn run_to_block_with<AllPalletsWithSystem>(
n: BlockNumberFor<T>,
mut hooks: RunToBlockHooks<T>,
) where
AllPalletsWithSystem: frame_support::traits::OnInitialize<BlockNumberFor<T>>
+ frame_support::traits::OnFinalize<BlockNumberFor<T>>,
{
let mut bn = Self::block_number();
while bn < n {
if !bn.is_zero() {
(hooks.before_finalize)(bn);
AllPalletsWithSystem::on_finalize(bn);
(hooks.after_finalize)(bn);
}
bn += One::one();
Self::set_block_number(bn);
(hooks.before_initialize)(bn);
AllPalletsWithSystem::on_initialize(bn);
(hooks.after_initialize)(bn);
}
}
#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
pub fn run_to_block<AllPalletsWithSystem>(n: BlockNumberFor<T>)
where
AllPalletsWithSystem: frame_support::traits::OnInitialize<BlockNumberFor<T>>
+ frame_support::traits::OnFinalize<BlockNumberFor<T>>,
{
Self::run_to_block_with::<AllPalletsWithSystem>(n, Default::default());
}
#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
pub fn set_block_number(n: BlockNumberFor<T>) {
<Number<T>>::put(n);
}
#[cfg(any(feature = "std", test))]
pub fn set_extrinsic_index(extrinsic_index: u32) {
storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &extrinsic_index)
}
#[cfg(any(feature = "std", test))]
pub fn set_parent_hash(n: T::Hash) {
<ParentHash<T>>::put(n);
}
#[cfg(any(feature = "std", test))]
pub fn set_block_consumed_resources(weight: Weight, len: usize) {
BlockWeight::<T>::mutate(|current_weight| {
current_weight.set(weight, DispatchClass::Normal)
});
AllExtrinsicsLen::<T>::put(len as u32);
}
pub fn reset_events() {
<Events<T>>::kill();
EventCount::<T>::kill();
let _ = <EventTopics<T>>::clear(u32::max_value(), None);
}
#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
#[track_caller]
pub fn assert_has_event(event: T::RuntimeEvent) {
let warn = if Self::block_number().is_zero() {
"WARNING: block number is zero, and events are not registered at block number zero.\n"
} else {
""
};
let events = Self::events();
assert!(
events.iter().any(|record| record.event == event),
"{warn}expected event {event:?} not found in events {events:?}",
);
}
#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
#[track_caller]
pub fn assert_last_event(event: T::RuntimeEvent) {
let warn = if Self::block_number().is_zero() {
"WARNING: block number is zero, and events are not registered at block number zero.\n"
} else {
""
};
let last_event = Self::events()
.last()
.expect(&alloc::format!("{warn}events expected"))
.event
.clone();
assert_eq!(
last_event, event,
"{warn}expected event {event:?} is not equal to the last event {last_event:?}",
);
}
pub fn runtime_version() -> RuntimeVersion {
T::Version::get()
}
pub fn account_nonce(who: impl EncodeLike<T::AccountId>) -> T::Nonce {
Account::<T>::get(who).nonce
}
pub fn inc_account_nonce(who: impl EncodeLike<T::AccountId>) {
Account::<T>::mutate(who, |a| a.nonce += T::Nonce::one());
}
pub fn note_extrinsic(encoded_xt: Vec<u8>) {
ExtrinsicData::<T>::insert(Self::extrinsic_index().unwrap_or_default(), encoded_xt);
}
pub fn note_applied_extrinsic(r: &DispatchResultWithPostInfo, info: DispatchInfo) {
let weight = extract_actual_weight(r, &info)
.saturating_add(T::BlockWeights::get().get(info.class).base_extrinsic);
let class = info.class;
let pays_fee = extract_actual_pays_fee(r, &info);
let dispatch_event_info = DispatchEventInfo { weight, class, pays_fee };
Self::deposit_event(match r {
Ok(_) => Event::ExtrinsicSuccess { dispatch_info: dispatch_event_info },
Err(err) => {
log::trace!(
target: LOG_TARGET,
"Extrinsic failed at block({:?}): {:?}",
Self::block_number(),
err,
);
Event::ExtrinsicFailed {
dispatch_error: err.error,
dispatch_info: dispatch_event_info,
}
},
});
log::trace!(
target: LOG_TARGET,
"Used block weight: {:?}",
BlockWeight::<T>::get(),
);
log::trace!(
target: LOG_TARGET,
"Used block length: {:?}",
Pallet::<T>::all_extrinsics_len(),
);
let next_extrinsic_index = Self::extrinsic_index().unwrap_or_default() + 1u32;
storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &next_extrinsic_index);
ExecutionPhase::<T>::put(Phase::ApplyExtrinsic(next_extrinsic_index));
ExtrinsicWeightReclaimed::<T>::kill();
}
pub fn note_finished_extrinsics() {
let extrinsic_index: u32 =
storage::unhashed::take(well_known_keys::EXTRINSIC_INDEX).unwrap_or_default();
ExtrinsicCount::<T>::put(extrinsic_index);
ExecutionPhase::<T>::put(Phase::Finalization);
}
pub fn note_finished_initialize() {
ExecutionPhase::<T>::put(Phase::ApplyExtrinsic(0))
}
pub fn on_created_account(who: T::AccountId, _a: &mut AccountInfo<T::Nonce, T::AccountData>) {
T::OnNewAccount::on_new_account(&who);
Self::deposit_event(Event::NewAccount { account: who });
}
fn on_killed_account(who: T::AccountId) {
T::OnKilledAccount::on_killed_account(&who);
Self::deposit_event(Event::KilledAccount { account: who });
}
pub fn can_set_code(code: &[u8], check_version: bool) -> CanSetCodeResult<T> {
if T::MultiBlockMigrator::ongoing() {
return CanSetCodeResult::MultiBlockMigrationsOngoing
}
if check_version {
let current_version = T::Version::get();
let Some(new_version) = sp_io::misc::runtime_version(code)
.and_then(|v| RuntimeVersion::decode(&mut &v[..]).ok())
else {
return CanSetCodeResult::InvalidVersion(Error::<T>::FailedToExtractRuntimeVersion)
};
cfg_if::cfg_if! {
if #[cfg(all(feature = "runtime-benchmarks", not(test)))] {
core::hint::black_box((new_version, current_version));
} else {
if new_version.spec_name != current_version.spec_name {
return CanSetCodeResult::InvalidVersion( Error::<T>::InvalidSpecName)
}
if new_version.spec_version <= current_version.spec_version {
return CanSetCodeResult::InvalidVersion(Error::<T>::SpecVersionNeedsToIncrease)
}
}
}
}
CanSetCodeResult::Ok
}
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 });
}
fn validate_code_is_authorized(
code: &[u8],
) -> Result<CodeUpgradeAuthorization<T>, 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);
Ok(authorization)
}
pub fn reclaim_weight(
info: &DispatchInfoOf<T::RuntimeCall>,
post_info: &PostDispatchInfoOf<T::RuntimeCall>,
) -> Result<(), TransactionValidityError>
where
T::RuntimeCall: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
{
let already_reclaimed = crate::ExtrinsicWeightReclaimed::<T>::get();
let unspent = post_info.calc_unspent(info);
let accurate_reclaim = already_reclaimed.max(unspent);
let to_reclaim_more = accurate_reclaim.saturating_sub(already_reclaimed);
if to_reclaim_more != Weight::zero() {
crate::BlockWeight::<T>::mutate(|current_weight| {
current_weight.reduce(to_reclaim_more, info.class);
});
crate::ExtrinsicWeightReclaimed::<T>::put(accurate_reclaim);
}
Ok(())
}
}
pub fn unique(entropy: impl Encode) -> [u8; 32] {
let mut last = [0u8; 32];
sp_io::storage::read(well_known_keys::INTRABLOCK_ENTROPY, &mut last[..], 0);
let next = (b"frame_system::unique", entropy, last).using_encoded(blake2_256);
sp_io::storage::set(well_known_keys::INTRABLOCK_ENTROPY, &next);
next
}
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(|_| ())
}
}
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(())
}
}
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)
}
}
impl<T: Config> StoredMap<T::AccountId, T::AccountData> for Pallet<T> {
fn get(k: &T::AccountId) -> T::AccountData {
Account::<T>::get(k).data
}
fn try_mutate_exists<R, E: From<DispatchError>>(
k: &T::AccountId,
f: impl FnOnce(&mut Option<T::AccountData>) -> Result<R, E>,
) -> Result<R, E> {
let account = Account::<T>::get(k);
let is_default = account.data == T::AccountData::default();
let mut some_data = if is_default { None } else { Some(account.data) };
let result = f(&mut some_data)?;
if Self::providers(k) > 0 || Self::sufficients(k) > 0 {
Account::<T>::mutate(k, |a| a.data = some_data.unwrap_or_default());
} else {
Account::<T>::remove(k)
}
Ok(result)
}
}
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> {
fn default() -> Self {
ChainContext(PhantomData)
}
}
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)
}
}
#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
pub struct RunToBlockHooks<'a, T>
where
T: 'a + Config,
{
before_initialize: Box<dyn 'a + FnMut(BlockNumberFor<T>)>,
after_initialize: Box<dyn 'a + FnMut(BlockNumberFor<T>)>,
before_finalize: Box<dyn 'a + FnMut(BlockNumberFor<T>)>,
after_finalize: Box<dyn 'a + FnMut(BlockNumberFor<T>)>,
}
#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
impl<'a, T> RunToBlockHooks<'a, T>
where
T: 'a + Config,
{
pub fn before_initialize<F>(mut self, f: F) -> Self
where
F: 'a + FnMut(BlockNumberFor<T>),
{
self.before_initialize = Box::new(f);
self
}
pub fn after_initialize<F>(mut self, f: F) -> Self
where
F: 'a + FnMut(BlockNumberFor<T>),
{
self.after_initialize = Box::new(f);
self
}
pub fn before_finalize<F>(mut self, f: F) -> Self
where
F: 'a + FnMut(BlockNumberFor<T>),
{
self.before_finalize = Box::new(f);
self
}
pub fn after_finalize<F>(mut self, f: F) -> Self
where
F: 'a + FnMut(BlockNumberFor<T>),
{
self.after_finalize = Box::new(f);
self
}
}
#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
impl<'a, T> Default for RunToBlockHooks<'a, T>
where
T: Config,
{
fn default() -> Self {
Self {
before_initialize: Box::new(|_| {}),
after_initialize: Box::new(|_| {}),
before_finalize: Box::new(|_| {}),
after_finalize: Box::new(|_| {}),
}
}
}
pub mod pallet_prelude {
pub use crate::{ensure_none, ensure_root, ensure_signed, ensure_signed_or_root};
pub type OriginFor<T> = <T as crate::Config>::RuntimeOrigin;
pub type HeaderFor<T> =
<<T as crate::Config>::Block as sp_runtime::traits::HeaderProvider>::HeaderT;
pub type BlockNumberFor<T> = <HeaderFor<T> as sp_runtime::traits::Header>::Number;
pub type ExtrinsicFor<T> =
<<T as crate::Config>::Block as sp_runtime::traits::Block>::Extrinsic;
pub type RuntimeCallFor<T> = <T as crate::Config>::RuntimeCall;
}