#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "std")]
use serde::Serialize;
use tetcore_std::prelude::*;
#[cfg(any(feature = "std", test))]
use tetcore_std::map;
use tetcore_std::marker::PhantomData;
use tetcore_std::fmt::Debug;
use tp_version::RuntimeVersion;
use tp_runtime::{
RuntimeDebug, Perbill, DispatchError, Either, generic,
traits::{
self, CheckEqual, AtLeast32Bit, Zero, Lookup, LookupError,
SimpleBitOps, Hash, Member, MaybeDisplay, BadOrigin,
MaybeSerialize, MaybeSerializeDeserialize, MaybeMallocSizeOf, StaticLookup, One, Bounded,
Dispatchable, AtLeast32BitUnsigned, Saturating, StoredMapError,
},
offchain::storage_lock::BlockNumberProvider,
};
use tet_core::{ChangesTrieConfiguration, storage::well_known_keys};
use fabric_support::{
Parameter, debug, storage,
traits::{
Contains, Get, NobleInfo, OnNewAccount, OnKilledAccount, HandleLifetime,
StoredMap, EnsureOrigin, OriginTrait, Filter,
},
weights::{
Weight, RuntimeDbWeight, DispatchInfo, DispatchClass,
extract_actual_weight, PerDispatchClass,
},
dispatch::DispatchResultWithPostInfo,
};
use codec::{Encode, Decode, FullCodec, EncodeLike};
#[cfg(feature = "std")]
use fabric_support::traits::GenesisBuild;
#[cfg(any(feature = "std", test))]
use tet_io::TestExternalities;
pub mod offchain;
pub mod limits;
#[cfg(test)]
pub(crate) mod mock;
mod extensions;
pub mod weights;
#[cfg(test)]
mod tests;
#[cfg(feature = "std")]
pub mod mocking;
pub use extensions::{
check_mortality::CheckMortality, check_genesis::CheckGenesis, check_nonce::CheckNonce,
check_spec_version::CheckSpecVersion, check_tx_version::CheckTxVersion,
check_weight::CheckWeight,
};
pub use extensions::check_mortality::CheckMortality as CheckEra;
pub use weights::WeightInfo;
pub fn extrinsics_root<H: Hash, E: codec::Encode>(extrinsics: &[E]) -> H::Output {
extrinsics_data_root::<H>(extrinsics.iter().map(codec::Encode::encode).collect())
}
pub fn extrinsics_data_root<H: Hash>(xts: Vec<Vec<u8>>) -> H::Output {
H::ordered_trie_root(xts)
}
pub type ConsumedWeight = PerDispatchClass<Weight>;
pub use noble::*;
#[fabric_support::noble]
pub mod noble {
use crate::{*, noble_prelude::*, self as fabric_system};
use fabric_support::noble_prelude::*;
#[noble::config]
#[noble::disable_fabric_system_supertrait_check]
pub trait Config: 'static + Eq + Clone {
type BaseCallFilter: Filter<Self::Call>;
#[noble::constant]
type BlockWeights: Get<limits::BlockWeights>;
#[noble::constant]
type BlockLength: Get<limits::BlockLength>;
type Origin:
Into<Result<RawOrigin<Self::AccountId>, Self::Origin>>
+ From<RawOrigin<Self::AccountId>>
+ Clone
+ OriginTrait<Call=Self::Call>;
type Call: Dispatchable + Debug;
type Index:
Parameter + Member + MaybeSerialize + Debug + Default + MaybeDisplay + AtLeast32Bit
+ Copy;
type BlockNumber:
Parameter + Member + MaybeSerializeDeserialize + Debug + MaybeDisplay +
AtLeast32BitUnsigned + Default + Bounded + Copy + tetcore_std::hash::Hash +
tetcore_std::str::FromStr + MaybeMallocSizeOf;
type Hash:
Parameter + Member + MaybeSerializeDeserialize + Debug + MaybeDisplay + SimpleBitOps + Ord
+ Default + Copy + CheckEqual + tetcore_std::hash::Hash + AsRef<[u8]> + AsMut<[u8]> + MaybeMallocSizeOf;
type Hashing: Hash<Output=Self::Hash>;
type AccountId: Parameter + Member + MaybeSerializeDeserialize + Debug + MaybeDisplay + Ord
+ Default;
type Lookup: StaticLookup<Target=Self::AccountId>;
type Header: Parameter + traits::Header<
Number=Self::BlockNumber,
Hash=Self::Hash,
>;
type Event: Parameter + Member + From<Event<Self>> + Debug + IsType<<Self as fabric_system::Config>::Event>;
#[noble::constant]
type BlockHashCount: Get<Self::BlockNumber>;
#[noble::constant]
type DbWeight: Get<RuntimeDbWeight>;
#[noble::constant]
type Version: Get<RuntimeVersion>;
type NobleInfo: NobleInfo;
type AccountData: Member + FullCodec + Clone + Default;
type OnNewAccount: OnNewAccount<Self::AccountId>;
type OnKilledAccount: OnKilledAccount<Self::AccountId>;
type SystemWeightInfo: WeightInfo;
#[noble::constant]
type SS58Prefix: Get<u8>;
}
#[noble::noble]
#[noble::generate_store(pub (super) trait Store)]
pub struct Noble<T>(PhantomData<T>);
#[noble::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Noble<T> {
fn on_runtime_upgrade() -> fabric_support::weights::Weight {
if !UpgradedToDualRefCount::<T>::get() {
UpgradedToDualRefCount::<T>::put(true);
migrations::migrate_to_dual_ref_count::<T>()
} else {
0
}
}
fn integrity_test() {
T::BlockWeights::get()
.validate()
.expect("The weights are invalid.");
}
}
#[noble::call]
impl<T: Config> Noble<T> {
#[noble::weight(*_ratio * T::BlockWeights::get().max_block)]
pub(crate) fn fill_block(origin: OriginFor<T>, _ratio: Perbill) -> DispatchResultWithPostInfo {
ensure_root(origin)?;
Ok(().into())
}
#[noble::weight(T::SystemWeightInfo::remark(_remark.len() as u32))]
pub(crate) fn remark(origin: OriginFor<T>, _remark: Vec<u8>) -> DispatchResultWithPostInfo {
ensure_signed(origin)?;
Ok(().into())
}
#[noble::weight((T::SystemWeightInfo::set_heap_pages(), DispatchClass::Operational))]
pub(crate) fn set_heap_pages(origin: OriginFor<T>, pages: u64) -> DispatchResultWithPostInfo {
ensure_root(origin)?;
storage::unhashed::put_raw(well_known_keys::HEAP_PAGES, &pages.encode());
Ok(().into())
}
#[noble::weight((T::BlockWeights::get().max_block, DispatchClass::Operational))]
pub fn set_code(origin: OriginFor<T>, code: Vec<u8>) -> DispatchResultWithPostInfo {
ensure_root(origin)?;
Self::can_set_code(&code)?;
storage::unhashed::put_raw(well_known_keys::CODE, &code);
Self::deposit_event(Event::CodeUpdated);
Ok(().into())
}
#[noble::weight((T::BlockWeights::get().max_block, DispatchClass::Operational))]
pub fn set_code_without_checks(
origin: OriginFor<T>,
code: Vec<u8>,
) -> DispatchResultWithPostInfo {
ensure_root(origin)?;
storage::unhashed::put_raw(well_known_keys::CODE, &code);
Self::deposit_event(Event::CodeUpdated);
Ok(().into())
}
#[noble::weight((T::SystemWeightInfo::set_changes_trie_config(), DispatchClass::Operational))]
pub fn set_changes_trie_config(
origin: OriginFor<T>,
changes_trie_config: Option<ChangesTrieConfiguration>,
) -> DispatchResultWithPostInfo {
ensure_root(origin)?;
match changes_trie_config.clone() {
Some(changes_trie_config) => storage::unhashed::put_raw(
well_known_keys::CHANGES_TRIE_CONFIG,
&changes_trie_config.encode(),
),
None => storage::unhashed::kill(well_known_keys::CHANGES_TRIE_CONFIG),
}
let log = generic::DigestItem::ChangesTrieSignal(
generic::ChangesTrieSignal::NewConfiguration(changes_trie_config),
);
Self::deposit_log(log.into());
Ok(().into())
}
#[noble::weight((
T::SystemWeightInfo::set_storage(items.len() as u32),
DispatchClass::Operational,
))]
pub(crate) 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())
}
#[noble::weight((
T::SystemWeightInfo::kill_storage(keys.len() as u32),
DispatchClass::Operational,
))]
pub(crate) fn kill_storage(origin: OriginFor<T>, keys: Vec<Key>) -> DispatchResultWithPostInfo {
ensure_root(origin)?;
for key in &keys {
storage::unhashed::kill(&key);
}
Ok(().into())
}
#[noble::weight((
T::SystemWeightInfo::kill_prefix(_tetkeys.saturating_add(1)),
DispatchClass::Operational,
))]
pub(crate) fn kill_prefix(
origin: OriginFor<T>,
prefix: Key,
_tetkeys: u32,
) -> DispatchResultWithPostInfo {
ensure_root(origin)?;
storage::unhashed::kill_prefix(&prefix);
Ok(().into())
}
}
#[noble::event]
#[noble::metadata(T::AccountId = "AccountId")]
pub enum Event<T: Config> {
ExtrinsicSuccess(DispatchInfo),
ExtrinsicFailed(DispatchError, DispatchInfo),
CodeUpdated,
NewAccount(T::AccountId),
KilledAccount(T::AccountId),
}
#[deprecated(note = "use `Event` instead")]
pub type RawEvent<T> = Event<T>;
#[noble::error]
pub enum Error<T> {
InvalidSpecName,
SpecVersionNeedsToIncrease,
FailedToExtractRuntimeVersion,
NonDefaultComposite,
NonZeroRefCount,
}
#[noble::origin]
pub type Origin<T> = RawOrigin<<T as Config>::AccountId>;
#[noble::storage]
#[noble::getter(fn account)]
pub type Account<T: Config> = StorageMap<
_,
Blake2_128Concat,
T::AccountId,
AccountInfo<T::Index, T::AccountData>,
ValueQuery,
>;
#[noble::storage]
pub(super) type ExtrinsicCount<T: Config> = StorageValue<_, u32>;
#[noble::storage]
#[noble::getter(fn block_weight)]
pub(super) type BlockWeight<T: Config> = StorageValue<_, ConsumedWeight, ValueQuery>;
#[noble::storage]
pub(super) type AllExtrinsicsLen<T: Config> = StorageValue<_, u32>;
#[noble::storage]
#[noble::getter(fn block_hash)]
pub type BlockHash<T: Config> =
StorageMap<_, Twox64Concat, T::BlockNumber, T::Hash, ValueQuery>;
#[noble::storage]
#[noble::getter(fn extrinsic_data)]
pub(super) type ExtrinsicData<T: Config> =
StorageMap<_, Twox64Concat, u32, Vec<u8>, ValueQuery>;
#[noble::storage]
#[noble::getter(fn block_number)]
pub(super) type Number<T: Config> = StorageValue<_, T::BlockNumber, ValueQuery>;
#[noble::storage]
#[noble::getter(fn parent_hash)]
pub(super) type ParentHash<T: Config> = StorageValue<_, T::Hash, ValueQuery>;
#[noble::storage]
#[noble::getter(fn digest)]
pub(super) type Digest<T: Config> = StorageValue<_, DigestOf<T>, ValueQuery>;
#[noble::storage]
#[noble::getter(fn events)]
pub(super) type Events<T: Config> =
StorageValue<_, Vec<EventRecord<T::Event, T::Hash>>, ValueQuery>;
#[noble::storage]
#[noble::getter(fn event_count)]
pub(super) type EventCount<T: Config> = StorageValue<_, EventIndex, ValueQuery>;
#[noble::storage]
#[noble::getter(fn event_topics)]
pub(super) type EventTopics<T: Config> =
StorageMap<_, Blake2_128Concat, T::Hash, Vec<(T::BlockNumber, EventIndex)>, ValueQuery>;
#[noble::storage]
pub type LastRuntimeUpgrade<T: Config> = StorageValue<_, LastRuntimeUpgradeInfo>;
#[noble::storage]
pub(super) type UpgradedToU32RefCount<T: Config> = StorageValue<_, bool, ValueQuery>;
#[noble::storage]
pub(super) type UpgradedToDualRefCount<T: Config> = StorageValue<_, bool, ValueQuery>;
#[noble::storage]
pub(super) type ExecutionPhase<T: Config> = StorageValue<_, Phase>;
#[noble::genesis_config]
pub struct GenesisConfig {
pub changes_trie_config: Option<ChangesTrieConfiguration>,
#[serde(with = "tet_core::bytes")]
pub code: Vec<u8>,
}
#[cfg(feature = "std")]
impl Default for GenesisConfig {
fn default() -> Self {
Self {
changes_trie_config: Default::default(),
code: Default::default(),
}
}
}
#[noble::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig {
fn build(&self) {
<BlockHash<T>>::insert::<_, T::Hash>(T::BlockNumber::zero(), hash69());
<ParentHash<T>>::put::<T::Hash>(hash69());
<LastRuntimeUpgrade<T>>::put(LastRuntimeUpgradeInfo::from(T::Version::get()));
<UpgradedToU32RefCount<T>>::put(true);
<UpgradedToDualRefCount<T>>::put(true);
tet_io::storage::set(well_known_keys::CODE, &self.code);
tet_io::storage::set(well_known_keys::EXTRINSIC_INDEX, &0u32.encode());
if let Some(ref changes_trie_config) = self.changes_trie_config {
tet_io::storage::set(well_known_keys::CHANGES_TRIE_CONFIG, &changes_trie_config.encode());
}
}
}
}
mod migrations {
use super::*;
#[allow(dead_code)]
pub fn migrate_all<T: Config>() -> fabric_support::weights::Weight {
Account::<T>::translate::<(T::Index, u8, T::AccountData), _>(|_key, (nonce, rc, data)|
Some(AccountInfo { nonce, consumers: rc as RefCount, providers: 1, data })
);
T::BlockWeights::get().max_block
}
pub fn migrate_to_dual_ref_count<T: Config>() -> fabric_support::weights::Weight {
Account::<T>::translate::<(T::Index, RefCount, T::AccountData), _>(|_key, (nonce, rc, data)|
Some(AccountInfo { nonce, consumers: rc as RefCount, providers: 1, data })
);
T::BlockWeights::get().max_block
}
}
#[cfg(feature = "std")]
impl GenesisConfig {
pub fn build_storage<T: Config>(&self) -> Result<tp_runtime::Storage, String> {
<Self as GenesisBuild<T>>::build_storage(self)
}
pub fn assimilate_storage<T: Config>(
&self,
storage: &mut tp_runtime::Storage
) -> Result<(), String> {
<Self as GenesisBuild<T>>::assimilate_storage(self, storage)
}
}
pub type DigestOf<T> = generic::Digest<<T as Config>::Hash>;
pub type DigestItemOf<T> = generic::DigestItem<<T as Config>::Hash>;
pub type Key = Vec<u8>;
pub type KeyValue = (Vec<u8>, Vec<u8>);
#[derive(Encode, Decode, RuntimeDebug)]
#[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)]
#[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>,
}
#[derive(PartialEq, Eq, Clone, RuntimeDebug, Encode, Decode)]
pub enum RawOrigin<AccountId> {
Root,
Signed(AccountId),
None,
}
impl<AccountId> From<Option<AccountId>> for RawOrigin<AccountId> {
fn from(s: Option<AccountId>) -> RawOrigin<AccountId> {
match s {
Some(who) => RawOrigin::Signed(who),
None => RawOrigin::None,
}
}
}
#[cfg(feature = "std")]
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)]
pub struct AccountInfo<Index, AccountData> {
pub nonce: Index,
pub consumers: RefCount,
pub providers: RefCount,
pub data: AccountData,
}
#[derive(tp_runtime::RuntimeDebug, Encode, Decode)]
#[cfg_attr(feature = "std", derive(PartialEq))]
pub struct LastRuntimeUpgradeInfo {
pub spec_version: codec::Compact<u32>,
pub spec_name: tp_runtime::RuntimeString,
}
impl LastRuntimeUpgradeInfo {
pub fn was_upgraded(&self, current: &tp_version::RuntimeVersion) -> bool {
current.spec_version > self.spec_version.0 || current.spec_name != self.spec_name
}
}
impl From<tp_version::RuntimeVersion> for LastRuntimeUpgradeInfo {
fn from(version: tp_version::RuntimeVersion) -> Self {
Self {
spec_version: version.spec_version.into(),
spec_name: version.spec_name,
}
}
}
pub struct EnsureRoot<AccountId>(tetcore_std::marker::PhantomData<AccountId>);
impl<
O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>,
AccountId,
> EnsureOrigin<O> for EnsureRoot<AccountId> {
type Success = ();
fn try_origin(o: O) -> Result<Self::Success, O> {
o.into().and_then(|o| match o {
RawOrigin::Root => Ok(()),
r => Err(O::from(r)),
})
}
#[cfg(feature = "runtime-benchmarks")]
fn successful_origin() -> O {
O::from(RawOrigin::Root)
}
}
pub struct EnsureSigned<AccountId>(tetcore_std::marker::PhantomData<AccountId>);
impl<
O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>,
AccountId: Default,
> EnsureOrigin<O> for EnsureSigned<AccountId> {
type Success = AccountId;
fn try_origin(o: O) -> Result<Self::Success, O> {
o.into().and_then(|o| match o {
RawOrigin::Signed(who) => Ok(who),
r => Err(O::from(r)),
})
}
#[cfg(feature = "runtime-benchmarks")]
fn successful_origin() -> O {
O::from(RawOrigin::Signed(Default::default()))
}
}
pub struct EnsureSignedBy<Who, AccountId>(tetcore_std::marker::PhantomData<(Who, AccountId)>);
impl<
O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>,
Who: Contains<AccountId>,
AccountId: PartialEq + Clone + Ord + Default,
> 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 successful_origin() -> O {
let members = Who::sorted_members();
let first_member = match members.get(0) {
Some(account) => account.clone(),
None => Default::default(),
};
O::from(RawOrigin::Signed(first_member.clone()))
}
}
pub struct EnsureNone<AccountId>(tetcore_std::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 successful_origin() -> O {
O::from(RawOrigin::None)
}
}
pub struct EnsureNever<T>(tetcore_std::marker::PhantomData<T>);
impl<O, T> EnsureOrigin<O> for EnsureNever<T> {
type Success = T;
fn try_origin(o: O) -> Result<Self::Success, O> {
Err(o)
}
#[cfg(feature = "runtime-benchmarks")]
fn successful_origin() -> O {
unimplemented!()
}
}
pub struct EnsureOneOf<AccountId, L, R>(tetcore_std::marker::PhantomData<(AccountId, L, R)>);
impl<
AccountId,
O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>,
L: EnsureOrigin<O>,
R: EnsureOrigin<O>,
> EnsureOrigin<O> for EnsureOneOf<AccountId, L, R> {
type Success = Either<L::Success, R::Success>;
fn try_origin(o: O) -> Result<Self::Success, O> {
L::try_origin(o).map_or_else(
|o| R::try_origin(o).map(|o| Either::Right(o)),
|o| Ok(Either::Left(o)),
)
}
#[cfg(feature = "runtime-benchmarks")]
fn successful_origin() -> O {
L::successful_origin()
}
}
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_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),
}
}
pub enum InitKind {
Inspection,
Full,
}
impl Default for InitKind {
fn default() -> Self {
InitKind::Full
}
}
#[derive(RuntimeDebug)]
pub enum RefStatus {
Referenced,
Unreferenced,
}
#[derive(RuntimeDebug)]
pub enum IncRefStatus {
Created,
Existed,
}
#[derive(RuntimeDebug)]
pub enum DecRefStatus {
Reaped,
Exists,
}
#[derive(RuntimeDebug)]
pub enum DecRefError {
ConsumerRemaining,
}
#[derive(RuntimeDebug)]
pub enum IncRefError {
NoProviders,
}
impl<T: Config> Module<T> {
pub fn account_exists(who: &T::AccountId) -> bool {
Account::<T>::contains_key(who)
}
#[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.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, DecRefError> {
Account::<T>::try_mutate_exists(who, |maybe_account| {
if let Some(mut account) = maybe_account.take() {
match (account.providers, account.consumers) {
(0, _) => {
debug::print!("Logic error: Unexpected underflow in reducing provider");
Ok(DecRefStatus::Reaped)
},
(1, 0) => {
Module::<T>::on_killed_account(who.clone());
Ok(DecRefStatus::Reaped)
}
(1, _) => {
Err(DecRefError::ConsumerRemaining)
}
(x, _) => {
account.providers = x - 1;
*maybe_account = Some(account);
Ok(DecRefStatus::Exists)
}
}
} else {
debug::print!("Logic error: Account already dead when reducing provider");
Ok(DecRefStatus::Reaped)
}
})
}
pub fn providers(who: &T::AccountId) -> RefCount {
Account::<T>::get(who).providers
}
pub fn inc_consumers(who: &T::AccountId) -> Result<(), IncRefError> {
Account::<T>::try_mutate(who, |a| if a.providers > 0 {
a.consumers = a.consumers.saturating_add(1);
Ok(())
} else {
Err(IncRefError::NoProviders)
})
}
pub fn dec_consumers(who: &T::AccountId) {
Account::<T>::mutate(who, |a| if a.consumers > 0 {
a.consumers -= 1;
} else {
debug::print!("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 deposit_event(event: impl Into<T::Event>) {
Self::deposit_event_indexed(&[], event.into());
}
pub fn deposit_event_indexed(topics: &[T::Hash], event: T::Event) {
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.iter().cloned().collect::<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.add(weight, class);
});
}
pub fn initialize(
number: &T::BlockNumber,
parent_hash: &T::Hash,
digest: &DigestOf<T>,
kind: InitKind,
) {
ExecutionPhase::<T>::put(Phase::Initialization);
storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &0u32);
<Number<T>>::put(number);
<Digest<T>>::put(digest);
<ParentHash<T>>::put(parent_hash);
<BlockHash<T>>::insert(*number - One::one(), parent_hash);
BlockWeight::<T>::kill();
if let InitKind::Full = kind {
<Events<T>>::kill();
EventCount::<T>::kill();
<EventTopics<T>>::remove_all();
}
}
pub fn finalize() -> T::Header {
ExecutionPhase::<T>::kill();
AllExtrinsicsLen::<T>::kill();
let number = <Number<T>>::get();
let parent_hash = <ParentHash<T>>::get();
let mut digest = <Digest<T>>::get();
let extrinsics = (0..ExtrinsicCount::<T>::take().unwrap_or_default())
.map(ExtrinsicData::<T>::take)
.collect();
let extrinsics_root = extrinsics_data_root::<T::Hashing>(extrinsics);
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 storage_root = T::Hash::decode(&mut &tet_io::storage::root()[..])
.expect("Node is configured to use the same hash; qed");
let storage_changes_root = tet_io::storage::changes_root(&parent_hash.encode());
if let Some(storage_changes_root) = storage_changes_root {
let item = generic::DigestItem::ChangesTrieRoot(
T::Hash::decode(&mut &storage_changes_root[..])
.expect("Node is configured to use the same hash; qed")
);
digest.push(item);
}
<T::Header as traits::Header>::new(number, extrinsics_root, storage_root, parent_hash, digest)
}
pub fn deposit_log(item: DigestItemOf<T>) {
<Digest<T>>::append(item);
}
#[cfg(any(feature = "std", test))]
pub fn externalities() -> TestExternalities {
TestExternalities::new(tet_core::storage::Storage {
top: map![
<BlockHash<T>>::hashed_key_for(T::BlockNumber::zero()) => [69u8; 32].encode(),
<Number<T>>::hashed_key().to_vec() => T::BlockNumber::one().encode(),
<ParentHash<T>>::hashed_key().to_vec() => [69u8; 32].encode()
],
children_default: map![],
})
}
#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
pub fn set_block_number(n: T::BlockNumber) {
<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);
}
#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
pub fn reset_events() {
<Events<T>>::kill();
EventCount::<T>::kill();
<EventTopics<T>>::remove_all();
}
pub fn runtime_version() -> RuntimeVersion { T::Version::get() }
pub fn account_nonce(who: impl EncodeLike<T::AccountId>) -> T::Index {
Account::<T>::get(who).nonce
}
pub fn inc_account_nonce(who: impl EncodeLike<T::AccountId>) {
Account::<T>::mutate(who, |a| a.nonce += T::Index::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, mut info: DispatchInfo) {
info.weight = extract_actual_weight(r, &info);
Self::deposit_event(
match r {
Ok(_) => Event::ExtrinsicSuccess(info),
Err(err) => {
tp_runtime::print(err);
Event::ExtrinsicFailed(err.error, info)
},
}
);
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));
}
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::Index, T::AccountData>) {
T::OnNewAccount::on_new_account(&who);
Self::deposit_event(Event::NewAccount(who));
}
fn on_killed_account(who: T::AccountId) {
T::OnKilledAccount::on_killed_account(&who);
Self::deposit_event(Event::KilledAccount(who));
}
pub fn can_set_code(code: &[u8]) -> Result<(), tp_runtime::DispatchError> {
let current_version = T::Version::get();
let new_version = tet_io::misc::runtime_version(&code)
.and_then(|v| RuntimeVersion::decode(&mut &v[..]).ok())
.ok_or_else(|| Error::<T>::FailedToExtractRuntimeVersion)?;
if new_version.spec_name != current_version.spec_name {
Err(Error::<T>::InvalidSpecName)?
}
if new_version.spec_version <= current_version.spec_version {
Err(Error::<T>::SpecVersionNeedsToIncrease)?
}
Ok(())
}
}
pub struct Provider<T>(PhantomData<T>);
impl<T: Config> HandleLifetime<T::AccountId> for Provider<T> {
fn created(t: &T::AccountId) -> Result<(), StoredMapError> {
Module::<T>::inc_providers(t);
Ok(())
}
fn killed(t: &T::AccountId) -> Result<(), StoredMapError> {
Module::<T>::dec_providers(t)
.map(|_| ())
.or_else(|e| match e {
DecRefError::ConsumerRemaining => Err(StoredMapError::ConsumerRemaining),
})
}
}
pub struct Consumer<T>(PhantomData<T>);
impl<T: Config> HandleLifetime<T::AccountId> for Consumer<T> {
fn created(t: &T::AccountId) -> Result<(), StoredMapError> {
Module::<T>::inc_consumers(t)
.map_err(|e| match e {
IncRefError::NoProviders => StoredMapError::NoProviders
})
}
fn killed(t: &T::AccountId) -> Result<(), StoredMapError> {
Module::<T>::dec_consumers(t);
Ok(())
}
}
impl<T: Config> BlockNumberProvider for Noble<T>
{
type BlockNumber = <T as Config>::BlockNumber;
fn current_block_number() -> Self::BlockNumber {
Noble::<T>::block_number()
}
}
fn is_providing<T: Default + Eq>(d: &T) -> bool {
d != &T::default()
}
impl<T: Config> StoredMap<T::AccountId, T::AccountData> for Noble<T> {
fn get(k: &T::AccountId) -> T::AccountData {
Account::<T>::get(k).data
}
fn try_mutate_exists<R, E: From<StoredMapError>>(
k: &T::AccountId,
f: impl FnOnce(&mut Option<T::AccountData>) -> Result<R, E>,
) -> Result<R, E> {
let account = Account::<T>::get(k);
let was_providing = is_providing(&account.data);
let mut some_data = if was_providing { Some(account.data) } else { None };
let result = f(&mut some_data)?;
let is_providing = some_data.is_some();
if !was_providing && is_providing {
Self::inc_providers(k);
} else if was_providing && !is_providing {
match Self::dec_providers(k) {
Err(DecRefError::ConsumerRemaining) => Err(StoredMapError::ConsumerRemaining)?,
Ok(DecRefStatus::Reaped) => return Ok(result),
Ok(DecRefStatus::Exists) => {
}
}
} else if !was_providing && !is_providing {
return Ok(result)
}
Account::<T>::mutate(k, |a| a.data = some_data.unwrap_or_default());
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)
}
}
pub mod noble_prelude {
pub use crate::{ensure_signed, ensure_none, ensure_root};
pub type OriginFor<T> = <T as crate::Config>::Origin;
pub type BlockNumberFor<T> = <T as crate::Config>::BlockNumber;
}