git.delta.rocks / unique-network / refs/commits / 915ff113b0bb

difftreelog

refactor use rpcs instead of api.query.common

Yaroslav Bolyukin2021-11-17parent: #516bf2b.patch.diff
in: master

33 files changed

modifiedclient/rpc/src/lib.rsdiffbeforeafterboth
--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -3,7 +3,7 @@
 use codec::Decode;
 use jsonrpc_core::{Error as RpcError, ErrorCode, Result};
 use jsonrpc_derive::rpc;
-use nft_data_structs::{CollectionId, TokenId};
+use nft_data_structs::{Collection, CollectionId, CollectionStats, TokenId};
 use sp_api::{BlockId, BlockT, ProvideRuntimeApi};
 use sp_blockchain::HeaderBackend;
 use up_rpc::NftApi as NftRuntimeApi;
@@ -86,8 +86,23 @@
 		collection: CollectionId,
 		at: Option<BlockHash>,
 	) -> Result<Vec<CrossAccountId>>;
+	#[rpc(name = "nft_allowed")]
+	fn allowed(
+		&self,
+		collection: CollectionId,
+		user: CrossAccountId,
+		at: Option<BlockHash>,
+	) -> Result<bool>;
 	#[rpc(name = "nft_lastTokenId")]
 	fn last_token_id(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<TokenId>;
+	#[rpc(name = "nft_collectionById")]
+	fn collection_by_id(
+		&self,
+		collection: CollectionId,
+		at: Option<BlockHash>,
+	) -> Result<Option<Collection<AccountId>>>;
+	#[rpc(name = "nft_collectionStats")]
+	fn collection_stats(&self, at: Option<BlockHash>) -> Result<CollectionStats>;
 }
 
 pub struct Nft<C, P> {
@@ -160,5 +175,8 @@
 
 	pass_method!(adminlist(collection: CollectionId) -> Vec<CrossAccountId>);
 	pass_method!(allowlist(collection: CollectionId) -> Vec<CrossAccountId>);
+	pass_method!(allowed(collection: CollectionId, user: CrossAccountId) -> bool);
 	pass_method!(last_token_id(collection: CollectionId) -> TokenId);
+	pass_method!(collection_by_id(collection: CollectionId) -> Option<Collection<AccountId>>);
+	pass_method!(collection_stats() -> CollectionStats);
 }
modifiedpallets/common/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -19,7 +19,7 @@
 pub fn create_collection_raw<T: Config, R>(
 	owner: T::AccountId,
 	mode: CollectionMode,
-	handler: impl FnOnce(Collection<T>) -> Result<CollectionId, DispatchError>,
+	handler: impl FnOnce(Collection<T::AccountId>) -> Result<CollectionId, DispatchError>,
 	cast: impl FnOnce(CollectionHandle<T>) -> R,
 ) -> Result<R, DispatchError> {
 	T::Currency::deposit_creating(&owner, T::CollectionCreationPrice::get());
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -12,7 +12,7 @@
 	COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,
 	MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_COLLECTION_NAME_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
 	COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo, TokenId, Weight,
-	WithdrawReasons,
+	WithdrawReasons, CollectionStats,
 };
 pub use pallet::*;
 use sp_core::H160;
@@ -26,7 +26,7 @@
 #[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]
 pub struct CollectionHandle<T: Config> {
 	pub id: CollectionId,
-	collection: Collection<T>,
+	collection: Collection<T::AccountId>,
 	pub recorder: pallet_evm_coder_substrate::SubstrateRecorder<T>,
 }
 impl<T: Config> CollectionHandle<T> {
@@ -78,7 +78,7 @@
 	}
 }
 impl<T: Config> Deref for CollectionHandle<T> {
-	type Target = Collection<T>;
+	type Target = Collection<T::AccountId>;
 
 	fn deref(&self) -> &Self::Target {
 		&self.collection
@@ -311,7 +311,7 @@
 	pub type CollectionById<T> = StorageMap<
 		Hasher = Blake2_128Concat,
 		Key = CollectionId,
-		Value = Collection<T>,
+		Value = Collection<<T as frame_system::Config>::AccountId>,
 		QueryKind = OptionQuery,
 	>;
 
@@ -344,6 +344,10 @@
 		Value = bool,
 		QueryKind = ValueQuery,
 	>;
+
+	/// Not used by code, exists only to provide some types to metadata
+	#[pallet::storage]
+	pub type DummyStorageValue<T> = StorageValue<Value = (CollectionStats, CollectionId, TokenId), QueryKind = OptionQuery>;
 }
 
 impl<T: Config> Pallet<T> {
@@ -355,10 +359,32 @@
 		);
 		Ok(())
 	}
+	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {
+		<IsAdmin<T>>::iter_prefix((collection,))
+			.map(|(a, _)| a)
+			.collect()
+	}
+	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {
+		<Allowlist<T>>::iter_prefix((collection,))
+			.map(|(a, _)| a)
+			.collect()
+	}
+	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {
+		<Allowlist<T>>::get((collection, user))
+	}
+	pub fn collection_stats() -> CollectionStats {
+		let created = <CreatedCollectionCount<T>>::get();
+		let destroyed = <DestroyedCollectionCount<T>>::get();
+		CollectionStats {
+			created: created.0,
+			destroyed: destroyed.0,
+			alive: created.0 - destroyed.0,
+		}
+	}
 }
 
 impl<T: Config> Pallet<T> {
-	pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {
+	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
 		{
 			ensure!(
 				data.name.len() <= MAX_COLLECTION_NAME_LENGTH,
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -91,8 +91,8 @@
 }
 
 impl<T: Config> Pallet<T> {
-	pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {
-		PalletCommon::init_collection(data)
+	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
+		<PalletCommon<T>>::init_collection(data)
 	}
 	pub fn destroy_collection(
 		collection: FungibleHandle<T>,
modifiedpallets/nft/src/eth/sponsoring.rsdiffbeforeafterboth
--- a/pallets/nft/src/eth/sponsoring.rs
+++ b/pallets/nft/src/eth/sponsoring.rs
@@ -25,7 +25,7 @@
 fn try_sponsor<T: Config>(
 	caller: &H160,
 	collection_id: CollectionId,
-	collection: &Collection<T>,
+	collection: &Collection<T::AccountId>,
 	call: &[u8],
 ) -> Result<(), AnyError> {
 	let (method_id, mut reader) = AbiReader::new_call(call).map_err(|_| AnyError)?;
@@ -109,7 +109,7 @@
 				if !collection.sponsorship.confirmed() {
 					return None;
 				}
-				if try_sponsor(who, collection_id, &collection, &call.1).is_ok() {
+				if try_sponsor::<T>(who, collection_id, &collection, &call.1).is_ok() {
 					return collection
 						.sponsorship
 						.sponsor()
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -42,8 +42,8 @@
 	CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
 };
 use pallet_common::{
-	account::CrossAccountId, CollectionHandle, IsAdmin, Pallet as PalletCommon,
-	Error as CommonError, CommonWeightInfo, Allowlist,
+	account::CrossAccountId, CollectionHandle, Pallet as PalletCommon, Error as CommonError,
+	CommonWeightInfo,
 };
 use pallet_refungible::{Pallet as PalletRefungible, RefungibleHandle};
 use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};
@@ -190,7 +190,7 @@
 			let who = ensure_signed(origin)?;
 
 			// Create new collection
-			let new_collection = Collection::<T> {
+			let new_collection = Collection {
 				owner: who.clone(),
 				name: collection_name,
 				mode: mode.clone(),
@@ -208,14 +208,14 @@
 			};
 
 			let _id = match mode {
-				CollectionMode::NFT => {PalletNonfungible::init_collection(new_collection)?},
+				CollectionMode::NFT => {<PalletNonfungible<T>>::init_collection(new_collection)?},
 				CollectionMode::Fungible(decimal_points) => {
 					// check params
 					ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);
-					PalletFungible::init_collection(new_collection)?
+					<PalletFungible<T>>::init_collection(new_collection)?
 				}
 				CollectionMode::ReFungible => {
-					PalletRefungible::init_collection(new_collection)?
+					<PalletRefungible<T>>::init_collection(new_collection)?
 				}
 			};
 
@@ -936,19 +936,5 @@
 
 			target_collection.save()
 		}
-	}
-}
-
-// TODO: limit returned entries?
-impl<T: Config> Pallet<T> {
-	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {
-		<IsAdmin<T>>::iter_prefix((collection,))
-			.map(|(a, _)| a)
-			.collect()
-	}
-	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {
-		<Allowlist<T>>::iter_prefix((collection,))
-			.map(|(a, _)| a)
-			.collect()
 	}
 }
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -133,8 +133,8 @@
 
 // unchecked calls skips any permission checks
 impl<T: Config> Pallet<T> {
-	pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {
-		PalletCommon::init_collection(data)
+	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
+		<PalletCommon<T>>::init_collection(data)
 	}
 	pub fn destroy_collection(
 		collection: NonfungibleHandle<T>,
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -156,8 +156,8 @@
 
 // unchecked calls skips any permission checks
 impl<T: Config> Pallet<T> {
-	pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {
-		PalletCommon::init_collection(data)
+	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
+		<PalletCommon<T>>::init_collection(data)
 	}
 	pub fn destroy_collection(
 		collection: RefungibleHandle<T>,
modifiedprimitives/nft/src/lib.rsdiffbeforeafterboth
--- a/primitives/nft/src/lib.rs
+++ b/primitives/nft/src/lib.rs
@@ -207,8 +207,8 @@
 
 #[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
-pub struct Collection<T: frame_system::Config> {
-	pub owner: T::AccountId,
+pub struct Collection<AccountId> {
+	pub owner: AccountId,
 	pub mode: CollectionMode,
 	pub access: AccessMode,
 	pub name: Vec<u16>,        // 64 include null escape char
@@ -217,7 +217,7 @@
 	pub mint_mode: bool,
 	pub offchain_schema: Vec<u8>,
 	pub schema_version: SchemaVersion,
-	pub sponsorship: SponsorshipState<T::AccountId>,
+	pub sponsorship: SponsorshipState<AccountId>,
 	pub limits: CollectionLimits,          // Collection private restrictions
 	pub variable_on_chain_schema: Vec<u8>, //
 	pub const_on_chain_schema: Vec<u8>,    //
@@ -413,3 +413,11 @@
 		CreateItemData::Fungible(item)
 	}
 }
+
+#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+pub struct CollectionStats {
+	pub created: u32,
+	pub destroyed: u32,
+	pub alive: u32,
+}
modifiedprimitives/rpc/src/lib.rsdiffbeforeafterboth
--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -1,6 +1,6 @@
 #![cfg_attr(not(feature = "std"), no_std)]
 
-use nft_data_structs::{CollectionId, TokenId};
+use nft_data_structs::{CollectionId, TokenId, Collection, CollectionStats};
 use sp_std::vec::Vec;
 use sp_core::H160;
 use codec::Decode;
@@ -32,6 +32,9 @@
 
 		fn adminlist(collection: CollectionId) -> Vec<CrossAccountId>;
 		fn allowlist(collection: CollectionId) -> Vec<CrossAccountId>;
+		fn allowed(collection: CollectionId, user: CrossAccountId) -> bool;
 		fn last_token_id(collection: CollectionId) -> TokenId;
+		fn collection_by_id(collection: CollectionId) -> Option<Collection<AccountId>>;
+		fn collection_stats() -> CollectionStats;
 	}
 }
modifiedruntime/src/lib.rsdiffbeforeafterboth
before · runtime/src/lib.rs
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "1024"]11#![allow(clippy::from_over_into, clippy::identity_op)]12#![allow(clippy::fn_to_numeric_cast_with_truncation)]13// Make the WASM binary available.14#[cfg(feature = "std")]15include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1617use sp_api::impl_runtime_apis;18use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};19// #[cfg(any(feature = "std", test))]20// pub use sp_runtime::BuildStorage;2122use sp_runtime::{23	Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,24	traits::{25		AccountIdLookup, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify,26		AccountIdConversion,27	},28	transaction_validity::{TransactionSource, TransactionValidity},29	ApplyExtrinsicResult, MultiSignature,30};3132use sp_std::prelude::*;3334#[cfg(feature = "std")]35use sp_version::NativeVersion;36use sp_version::RuntimeVersion;37pub use pallet_transaction_payment::{38	Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,39};40// A few exports that help ease life for downstream crates.41pub use pallet_balances::Call as BalancesCall;42pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};43pub use frame_support::{44	construct_runtime, match_type,45	dispatch::DispatchResult,46	PalletId, parameter_types, StorageValue, ConsensusEngineId,47	traits::{48		Everything, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem,49		LockIdentifier, OnUnbalanced, Randomness, FindAuthor,50	},51	weights::{52		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},53		DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,54		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,55	},56};57use nft_data_structs::*;58// use pallet_contracts::weights::WeightInfo;59// #[cfg(any(feature = "std", test))]60use frame_system::{61	self as system, EnsureRoot, EnsureSigned,62	limits::{BlockWeights, BlockLength},63};64use sp_arithmetic::{65	traits::{BaseArithmetic, Unsigned},66};67use smallvec::smallvec;68use codec::{Encode, Decode};69use pallet_evm::{Account as EVMAccount, FeeCalculator, OnMethodCall};70use fp_rpc::TransactionStatus;71use sp_core::crypto::Public;72use sp_runtime::{73	traits::{Dispatchable, PostDispatchInfoOf},74	transaction_validity::TransactionValidityError,75};7677// pub use pallet_timestamp::Call as TimestampCall;78pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;7980// Polkadot imports81use pallet_xcm::XcmPassthrough;82use polkadot_parachain::primitives::Sibling;83use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};84use xcm_builder::{85	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,86	EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset,87	ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,88	SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,89	SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,90};91use xcm_executor::{Config, XcmExecutor};9293// mod chain_extension;94// use crate::chain_extension::{NFTExtension, Imbalance};9596/// An index to a block.97pub type BlockNumber = u32;9899/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.100pub type Signature = MultiSignature;101102/// Some way of identifying an account on the chain. We intentionally make it equivalent103/// to the public key of our transaction signing scheme.104pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;105106pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;107108/// The type for looking up accounts. We don't expect more than 4 billion of them, but you109/// never know...110pub type AccountIndex = u32;111112/// Balance of an account.113pub type Balance = u128;114115/// Index of a transaction in the chain.116pub type Index = u32;117118/// A hash of some data used by the chain.119pub type Hash = sp_core::H256;120121/// Digest item type.122pub type DigestItem = generic::DigestItem<Hash>;123124/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know125/// the specifics of the runtime. They can then be made to be agnostic over specific formats126/// of data like extrinsics, allowing for them to continue syncing the network through upgrades127/// to even the core data structures.128pub mod opaque {129	use super::*;130131	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;132133	/// Opaque block type.134	pub type Block = generic::Block<Header, UncheckedExtrinsic>;135136	pub type SessionHandlers = ();137138	impl_opaque_keys! {139		pub struct SessionKeys {140			pub aura: Aura,141		}142	}143}144145/// This runtime version.146pub const VERSION: RuntimeVersion = RuntimeVersion {147	spec_name: create_runtime_str!("opal"),148	impl_name: create_runtime_str!("opal"),149	authoring_version: 1,150	spec_version: 912202,151	impl_version: 1,152	apis: RUNTIME_API_VERSIONS,153	transaction_version: 1,154};155156pub const MILLISECS_PER_BLOCK: u64 = 12000;157158pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;159160// These time units are defined in number of blocks.161pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);162pub const HOURS: BlockNumber = MINUTES * 60;163pub const DAYS: BlockNumber = HOURS * 24;164165parameter_types! {166	pub const DefaultSponsoringRateLimit: BlockNumber = 1 * DAYS;167}168169#[derive(codec::Encode, codec::Decode)]170pub enum XCMPMessage<XAccountId, XBalance> {171	/// Transfer tokens to the given account from the Parachain account.172	TransferToken(XAccountId, XBalance),173}174175/// The version information used to identify this runtime when compiled natively.176#[cfg(feature = "std")]177pub fn native_version() -> NativeVersion {178	NativeVersion {179		runtime_version: VERSION,180		can_author_with: Default::default(),181	}182}183184type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;185186pub struct DealWithFees;187impl OnUnbalanced<NegativeImbalance> for DealWithFees {188	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {189		if let Some(fees) = fees_then_tips.next() {190			// for fees, 100% to treasury191			let mut split = fees.ration(100, 0);192			if let Some(tips) = fees_then_tips.next() {193				// for tips, if any, 100% to treasury194				tips.ration_merge_into(100, 0, &mut split);195			}196			Treasury::on_unbalanced(split.0);197			// Author::on_unbalanced(split.1);198		}199	}200}201202/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.203/// This is used to limit the maximal weight of a single extrinsic.204const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);205/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used206/// by  Operational  extrinsics.207const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);208/// We allow for 2 seconds of compute with a 6 second average block time.209const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2;210211parameter_types! {212	pub const BlockHashCount: BlockNumber = 2400;213	pub RuntimeBlockLength: BlockLength =214		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);215	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);216	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;217	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()218		.base_block(BlockExecutionWeight::get())219		.for_class(DispatchClass::all(), |weights| {220			weights.base_extrinsic = ExtrinsicBaseWeight::get();221		})222		.for_class(DispatchClass::Normal, |weights| {223			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);224		})225		.for_class(DispatchClass::Operational, |weights| {226			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);227			// Operational transactions have some extra reserved space, so that they228			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.229			weights.reserved = Some(230				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT231			);232		})233		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)234		.build_or_panic();235	pub const Version: RuntimeVersion = VERSION;236	pub const SS58Prefix: u8 = 42;237}238239parameter_types! {240	pub const ChainId: u64 = 8888;241}242243pub struct FixedFee;244impl FeeCalculator for FixedFee {245	fn min_gas_price() -> U256 {246		1.into()247	}248}249250impl pallet_evm::Config for Runtime {251	type BlockGasLimit = BlockGasLimit;252	type FeeCalculator = FixedFee;253	type GasWeightMapping = ();254	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;255	type CallOrigin = EnsureAddressTruncated;256	type WithdrawOrigin = EnsureAddressTruncated;257	type AddressMapping = HashedAddressMapping<Self::Hashing>;258	type Precompiles = ();259	type Currency = Balances;260	type Event = Event;261	type OnMethodCall = (262		pallet_evm_migration::OnMethodCall<Self>,263		pallet_nft::NftErcSupport<Self>,264		pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,265	);266	type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;267	type ChainId = ChainId;268	type Runner = pallet_evm::runner::stack::Runner<Self>;269	type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;270	type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;271	type FindAuthor = EthereumFindAuthor<Aura>;272}273274impl pallet_evm_migration::Config for Runtime {275	type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;276}277278pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);279impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {280	fn find_author<'a, I>(digests: I) -> Option<H160>281	where282		I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,283	{284		if let Some(author_index) = F::find_author(digests) {285			let authority_id = Aura::authorities()[author_index as usize].clone();286			return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));287		}288		None289	}290}291292parameter_types! {293	pub BlockGasLimit: U256 = U256::from(u32::max_value());294}295296impl pallet_ethereum::Config for Runtime {297	type Event = Event;298	type StateRoot = pallet_ethereum::IntermediateStateRoot;299	type EvmSubmitLog = pallet_evm::Pallet<Self>;300}301302impl pallet_randomness_collective_flip::Config for Runtime {}303304impl system::Config for Runtime {305	/// The data to be stored in an account.306	type AccountData = pallet_balances::AccountData<Balance>;307	/// The identifier used to distinguish between accounts.308	type AccountId = AccountId;309	/// The basic call filter to use in dispatchable.310	type BaseCallFilter = Everything;311	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).312	type BlockHashCount = BlockHashCount;313	/// The maximum length of a block (in bytes).314	type BlockLength = RuntimeBlockLength;315	/// The index type for blocks.316	type BlockNumber = BlockNumber;317	/// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.318	type BlockWeights = RuntimeBlockWeights;319	/// The aggregated dispatch type that is available for extrinsics.320	type Call = Call;321	/// The weight of database operations that the runtime can invoke.322	type DbWeight = RocksDbWeight;323	/// The ubiquitous event type.324	type Event = Event;325	/// The type for hashing blocks and tries.326	type Hash = Hash;327	/// The hashing algorithm used.328	type Hashing = BlakeTwo256;329	/// The header type.330	type Header = generic::Header<BlockNumber, BlakeTwo256>;331	/// The index type for storing how many extrinsics an account has signed.332	type Index = Index;333	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.334	type Lookup = AccountIdLookup<AccountId, ()>;335	/// What to do if an account is fully reaped from the system.336	type OnKilledAccount = ();337	/// What to do if a new account is created.338	type OnNewAccount = ();339	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;340	/// The ubiquitous origin type.341	type Origin = Origin;342	/// This type is being generated by `construct_runtime!`.343	type PalletInfo = PalletInfo;344	/// This is used as an identifier of the chain. 42 is the generic substrate prefix.345	type SS58Prefix = SS58Prefix;346	/// Weight information for the extrinsics of this pallet.347	type SystemWeightInfo = system::weights::SubstrateWeight<Self>;348	/// Version of the runtime.349	type Version = Version;350}351352parameter_types! {353	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;354}355356impl pallet_timestamp::Config for Runtime {357	/// A timestamp: milliseconds since the unix epoch.358	type Moment = u64;359	type OnTimestampSet = ();360	type MinimumPeriod = MinimumPeriod;361	type WeightInfo = ();362}363364parameter_types! {365	// pub const ExistentialDeposit: u128 = 500;366	pub const ExistentialDeposit: u128 = 0;367	pub const MaxLocks: u32 = 50;368}369370impl pallet_balances::Config for Runtime {371	type MaxLocks = MaxLocks;372	type MaxReserves = ();373	type ReserveIdentifier = [u8; 8];374	/// The type for recording an account's balance.375	type Balance = Balance;376	/// The ubiquitous event type.377	type Event = Event;378	type DustRemoval = Treasury;379	type ExistentialDeposit = ExistentialDeposit;380	type AccountStore = System;381	type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;382}383384pub const MICROUNIQUE: Balance = 1_000_000_000;385pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;386pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;387pub const UNIQUE: Balance = 100 * CENTIUNIQUE;388389pub const fn deposit(items: u32, bytes: u32) -> Balance {390	items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE391}392393/*394parameter_types! {395	pub TombstoneDeposit: Balance = deposit(396		1,397		sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,398	);399	pub DepositPerContract: Balance = TombstoneDeposit::get();400	pub const DepositPerStorageByte: Balance = deposit(0, 1);401	pub const DepositPerStorageItem: Balance = deposit(1, 0);402	pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);403	pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;404	pub const SignedClaimHandicap: u32 = 2;405	pub const MaxDepth: u32 = 32;406	pub const MaxValueSize: u32 = 16 * 1024;407	pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb408	// The lazy deletion runs inside on_initialize.409	pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *410		RuntimeBlockWeights::get().max_block;411	// The weight needed for decoding the queue should be less or equal than a fifth412	// of the overall weight dedicated to the lazy deletion.413	pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (414			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -415			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)416		)) / 5) as u32;417	pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();418}419420impl pallet_contracts::Config for Runtime {421	type Time = Timestamp;422	type Randomness = RandomnessCollectiveFlip;423	type Currency = Balances;424	type Event = Event;425	type RentPayment = ();426	type SignedClaimHandicap = SignedClaimHandicap;427	type TombstoneDeposit = TombstoneDeposit;428	type DepositPerContract = DepositPerContract;429	type DepositPerStorageByte = DepositPerStorageByte;430	type DepositPerStorageItem = DepositPerStorageItem;431	type RentFraction = RentFraction;432	type SurchargeReward = SurchargeReward;433	type WeightPrice = pallet_transaction_payment::Pallet<Self>;434	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;435	type ChainExtension = NFTExtension;436	type DeletionQueueDepth = DeletionQueueDepth;437	type DeletionWeightLimit = DeletionWeightLimit;438	type Schedule = Schedule;439	type CallStack = [pallet_contracts::Frame<Self>; 31];440}441*/442443parameter_types! {444	pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer445	/// This value increases the priority of `Operational` transactions by adding446	/// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.447	pub const OperationalFeeMultiplier: u8 = 5;448}449450/// Linear implementor of `WeightToFeePolynomial`451pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);452453impl<T> WeightToFeePolynomial for LinearFee<T>454where455	T: BaseArithmetic + From<u32> + Copy + Unsigned,456{457	type Balance = T;458459	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {460		smallvec!(WeightToFeeCoefficient {461			coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer462			coeff_frac: Perbill::zero(),463			negative: false,464			degree: 1,465		})466	}467}468469impl pallet_transaction_payment::Config for Runtime {470	type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;471	type TransactionByteFee = TransactionByteFee;472	type OperationalFeeMultiplier = OperationalFeeMultiplier;473	type WeightToFee = LinearFee<Balance>;474	type FeeMultiplierUpdate = ();475}476477parameter_types! {478	pub const ProposalBond: Permill = Permill::from_percent(5);479	pub const ProposalBondMinimum: Balance = 1 * UNIQUE;480	pub const SpendPeriod: BlockNumber = 5 * MINUTES;481	pub const Burn: Permill = Permill::from_percent(0);482	pub const TipCountdown: BlockNumber = 1 * DAYS;483	pub const TipFindersFee: Percent = Percent::from_percent(20);484	pub const TipReportDepositBase: Balance = 1 * UNIQUE;485	pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;486	pub const BountyDepositBase: Balance = 1 * UNIQUE;487	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;488	pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");489	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;490	pub const MaximumReasonLength: u32 = 16384;491	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);492	pub const BountyValueMinimum: Balance = 5 * UNIQUE;493	pub const MaxApprovals: u32 = 100;494}495496impl pallet_treasury::Config for Runtime {497	type PalletId = TreasuryModuleId;498	type Currency = Balances;499	type ApproveOrigin = EnsureRoot<AccountId>;500	type RejectOrigin = EnsureRoot<AccountId>;501	type Event = Event;502	type OnSlash = ();503	type ProposalBond = ProposalBond;504	type ProposalBondMinimum = ProposalBondMinimum;505	type SpendPeriod = SpendPeriod;506	type Burn = Burn;507	type BurnDestination = ();508	type SpendFunds = ();509	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;510	type MaxApprovals = MaxApprovals;511}512513impl pallet_sudo::Config for Runtime {514	type Event = Event;515	type Call = Call;516}517518parameter_types! {519	pub const MinVestedTransfer: Balance = 10 * UNIQUE;520}521522impl pallet_vesting::Config for Runtime {523	type Event = Event;524	type Currency = Balances;525	type BlockNumberToBalance = ConvertInto;526	type MinVestedTransfer = MinVestedTransfer;527	type WeightInfo = ();528	const MAX_VESTING_SCHEDULES: u32 = 28;529}530531parameter_types! {532	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;533	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;534}535536impl cumulus_pallet_parachain_system::Config for Runtime {537	type Event = Event;538	type OnValidationData = ();539	type SelfParaId = parachain_info::Pallet<Self>;540	// type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<541	// 	MaxDownwardMessageWeight,542	// 	XcmExecutor<XcmConfig>,543	// 	Call,544	// >;545	type OutboundXcmpMessageSource = XcmpQueue;546	type DmpMessageHandler = DmpQueue;547	type ReservedDmpWeight = ReservedDmpWeight;548	type ReservedXcmpWeight = ReservedXcmpWeight;549	type XcmpMessageHandler = XcmpQueue;550}551552impl parachain_info::Config for Runtime {}553554impl cumulus_pallet_aura_ext::Config for Runtime {}555556parameter_types! {557	pub const RelayLocation: MultiLocation = MultiLocation::parent();558	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;559	pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();560	pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();561}562563/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used564/// when determining ownership of accounts for asset transacting and when attempting to use XCM565/// `Transact` in order to determine the dispatch Origin.566pub type LocationToAccountId = (567	// The parent (Relay-chain) origin converts to the default `AccountId`.568	ParentIsDefault<AccountId>,569	// Sibling parachain origins convert to AccountId via the `ParaId::into`.570	SiblingParachainConvertsVia<Sibling, AccountId>,571	// Straight up local `AccountId32` origins just alias directly to `AccountId`.572	AccountId32Aliases<RelayNetwork, AccountId>,573);574575/// Means for transacting assets on this chain.576pub type LocalAssetTransactor = CurrencyAdapter<577	// Use this currency:578	Balances,579	// Use this currency when it is a fungible asset matching the given location or name:580	IsConcrete<RelayLocation>,581	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:582	LocationToAccountId,583	// Our chain's account ID type (we can't get away without mentioning it explicitly):584	AccountId,585	// We don't track any teleports.586	(),587>;588589/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,590/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can591/// biases the kind of local `Origin` it will become.592pub type XcmOriginToTransactDispatchOrigin = (593	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location594	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for595	// foreign chains who want to have a local sovereign account on this chain which they control.596	SovereignSignedViaLocation<LocationToAccountId, Origin>,597	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when598	// recognised.599	RelayChainAsNative<RelayOrigin, Origin>,600	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when601	// recognised.602	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,603	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a604	// transaction from the Root origin.605	ParentAsSuperuser<Origin>,606	// Native signed account converter; this just converts an `AccountId32` origin into a normal607	// `Origin::Signed` origin of the same 32-byte value.608	SignedAccountId32AsNative<RelayNetwork, Origin>,609	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.610	XcmPassthrough<Origin>,611);612613parameter_types! {614	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.615	pub UnitWeightCost: Weight = 1_000_000;616	// 1200 UNIQUEs buy 1 second of weight.617	pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);618	pub const MaxInstructions: u32 = 100;619	pub const MaxAuthorities: u32 = 100_000;620}621622match_type! {623	pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {624		MultiLocation { parents: 1, interior: Here } |625		MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }626	};627}628629pub type Barrier = (630	TakeWeightCredit,631	AllowTopLevelPaidExecutionFrom<Everything>,632	AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,633	// ^^^ Parent & its unit plurality gets free execution634);635636pub struct XcmConfig;637impl Config for XcmConfig {638	type Call = Call;639	type XcmSender = XcmRouter;640	// How to withdraw and deposit an asset.641	type AssetTransactor = LocalAssetTransactor;642	type OriginConverter = XcmOriginToTransactDispatchOrigin;643	type IsReserve = NativeAsset;644	type IsTeleporter = (); // Teleportation is disabled645	type LocationInverter = LocationInverter<Ancestry>;646	type Barrier = Barrier;647	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;648	type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;649	type ResponseHandler = (); // Don't handle responses for now.650	type SubscriptionService = PolkadotXcm;651652	type AssetTrap = PolkadotXcm;653	type AssetClaims = PolkadotXcm;654}655656// parameter_types! {657// 	pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;658// }659660/// No local origins on this chain are allowed to dispatch XCM sends/executions.661pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);662663/// The means for routing XCM messages which are not for local execution into the right message664/// queues.665pub type XcmRouter = (666	// Two routers - use UMP to communicate with the relay chain:667	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,668	// ..and XCMP to communicate with the sibling chains.669	XcmpQueue,670);671672impl pallet_evm_coder_substrate::Config for Runtime {673	type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;674}675676impl pallet_xcm::Config for Runtime {677	type Event = Event;678	type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;679	type XcmRouter = XcmRouter;680	type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;681	type XcmExecuteFilter = Everything;682	type XcmExecutor = XcmExecutor<XcmConfig>;683	type XcmTeleportFilter = Everything;684	type XcmReserveTransferFilter = Everything;685	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;686	type LocationInverter = LocationInverter<Ancestry>;687	type Origin = Origin;688	type Call = Call;689	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;690	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;691}692693impl cumulus_pallet_xcm::Config for Runtime {694	type Event = Event;695	type XcmExecutor = XcmExecutor<XcmConfig>;696}697698impl cumulus_pallet_xcmp_queue::Config for Runtime {699	type Event = Event;700	type XcmExecutor = XcmExecutor<XcmConfig>;701	type ChannelInfo = ParachainSystem;702	type VersionWrapper = ();703}704705impl cumulus_pallet_dmp_queue::Config for Runtime {706	type Event = Event;707	type XcmExecutor = XcmExecutor<XcmConfig>;708	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;709}710711impl pallet_aura::Config for Runtime {712	type AuthorityId = AuraId;713	type DisabledValidators = ();714	type MaxAuthorities = MaxAuthorities;715}716717parameter_types! {718	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();719	pub const CollectionCreationPrice: Balance = 100 * UNIQUE;720}721722impl pallet_common::Config for Runtime {723	type Event = Event;724	type EvmBackwardsAddressMapping = pallet_common::account::MapBackwardsAddressTruncated;725	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;726	type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;727728	type Currency = Balances;729	type CollectionCreationPrice = CollectionCreationPrice;730	type TreasuryAccountId = TreasuryAccountId;731}732733impl pallet_fungible::Config for Runtime {734	type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;735}736impl pallet_refungible::Config for Runtime {737	type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;738}739impl pallet_nonfungible::Config for Runtime {740	type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;741}742743/// Used for the pallet nft in `./nft.rs`744impl pallet_nft::Config for Runtime {745	type WeightInfo = pallet_nft::weights::SubstrateWeight<Self>;746}747748parameter_types! {749	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied750}751752/// Used for the pallet inflation753impl pallet_inflation::Config for Runtime {754	type Currency = Balances;755	type TreasuryAccountId = TreasuryAccountId;756	type InflationBlockInterval = InflationBlockInterval;757}758759parameter_types! {760	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *761		RuntimeBlockWeights::get().max_block;762	pub const MaxScheduledPerBlock: u32 = 50;763}764765pub struct Sponsoring;766impl SponsoringResolve<AccountId, Call> for Sponsoring {767	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>768	where769		Call: Dispatchable<Info = DispatchInfo>,770		AccountId: AsRef<[u8]>,771	{772		pallet_nft_transaction_payment::Module::<Runtime>::withdraw_type(who, call)773	}774}775776type SponsorshipHandler = (777	pallet_nft::NftSponsorshipHandler<Runtime>,778	//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,779);780781impl pallet_unq_scheduler::Config for Runtime {782	type Event = Event;783	type Origin = Origin;784	type PalletsOrigin = OriginCaller;785	type Call = Call;786	type MaximumWeight = MaximumSchedulerWeight;787	type ScheduleOrigin = EnsureSigned<AccountId>;788	type MaxScheduledPerBlock = MaxScheduledPerBlock;789	type SponsorshipHandler = SponsorshipHandler;790	type WeightInfo = ();791}792793impl pallet_nft_transaction_payment::Config for Runtime {794	type SponsorshipHandler = SponsorshipHandler;795}796797impl pallet_evm_transaction_payment::Config for Runtime {798	type SponsorshipHandler = (799		pallet_nft::NftEthSponsorshipHandler<Self>,800		pallet_evm_contract_helpers::HelpersContractSponsoring<Self>,801	);802	type Currency = Balances;803}804805impl pallet_nft_charge_transaction::Config for Runtime {806	type SponsorshipHandler = pallet_nft::NftSponsorshipHandler<Runtime>;807}808809// impl pallet_contract_helpers::Config for Runtime {810//	 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;811// }812813parameter_types! {814	// 0x842899ECF380553E8a4de75bF534cdf6fBF64049815	pub const HelpersContractAddress: H160 = H160([816		0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,817	]);818}819820impl pallet_evm_contract_helpers::Config for Runtime {821	type ContractAddress = HelpersContractAddress;822	type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;823}824825construct_runtime!(826	pub enum Runtime where827		Block = Block,828		NodeBlock = opaque::Block,829		UncheckedExtrinsic = UncheckedExtrinsic830	{831		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,832		ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,833834		Aura: pallet_aura::{Pallet, Config<T>} = 22,835		AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,836837		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,838		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,839		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,840		TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,841		Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,842		Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,843		System: system::{Pallet, Call, Storage, Config, Event<T>} = 36,844		Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,845		// Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,846847		// XCM helpers.848		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,849		PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,850		CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,851		DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,852853		// Unique Pallets854		Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,855		Nft: pallet_nft::{Pallet, Call, Storage} = 61,856		Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,857		NftPayment: pallet_nft_transaction_payment::{Pallet, Call, Storage} = 63,858		Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage } = 64,859		// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,860		Common: pallet_common::{Pallet, Storage, Event<T>} = 66,861		Fungible: pallet_fungible::{Pallet, Storage} = 67,862		Refungible: pallet_refungible::{Pallet, Storage} = 68,863		Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,864865		// Frontier866		EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,867		Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,868869		EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,870		EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,871		EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,872		EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,873	}874);875876pub struct TransactionConverter;877878impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {879	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {880		UncheckedExtrinsic::new_unsigned(881			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),882		)883	}884}885886impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {887	fn convert_transaction(888		&self,889		transaction: pallet_ethereum::Transaction,890	) -> opaque::UncheckedExtrinsic {891		let extrinsic = UncheckedExtrinsic::new_unsigned(892			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),893		);894		let encoded = extrinsic.encode();895		opaque::UncheckedExtrinsic::decode(&mut &encoded[..])896			.expect("Encoded extrinsic is always valid")897	}898}899900/// The address format for describing accounts.901pub type Address = sp_runtime::MultiAddress<AccountId, ()>;902/// Block header type as expected by this runtime.903pub type Header = generic::Header<BlockNumber, BlakeTwo256>;904/// Block type as expected by this runtime.905pub type Block = generic::Block<Header, UncheckedExtrinsic>;906/// A Block signed with a Justification907pub type SignedBlock = generic::SignedBlock<Block>;908/// BlockId type as expected by this runtime.909pub type BlockId = generic::BlockId<Block>;910/// The SignedExtension to the basic transaction logic.911pub type SignedExtra = (912	system::CheckSpecVersion<Runtime>,913	// system::CheckTxVersion<Runtime>,914	system::CheckGenesis<Runtime>,915	system::CheckEra<Runtime>,916	system::CheckNonce<Runtime>,917	system::CheckWeight<Runtime>,918	pallet_nft_charge_transaction::ChargeTransactionPayment<Runtime>,919	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,920);921/// Unchecked extrinsic type as expected by this runtime.922pub type UncheckedExtrinsic =923	fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;924/// Extrinsic type that has already been checked.925pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;926/// Executive: handles dispatch to the various modules.927pub type Executive = frame_executive::Executive<928	Runtime,929	Block,930	frame_system::ChainContext<Runtime>,931	Runtime,932	AllPallets,933>;934935impl_opaque_keys! {936	pub struct SessionKeys {937		pub aura: Aura,938	}939}940941impl fp_self_contained::SelfContainedCall for Call {942	type SignedInfo = H160;943944	fn is_self_contained(&self) -> bool {945		match self {946			Call::Ethereum(call) => call.is_self_contained(),947			_ => false,948		}949	}950951	fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {952		match self {953			Call::Ethereum(call) => call.check_self_contained(),954			_ => None,955		}956	}957958	fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {959		match self {960			Call::Ethereum(call) => call.validate_self_contained(info),961			_ => None,962		}963	}964965	fn pre_dispatch_self_contained(966		&self,967		info: &Self::SignedInfo,968	) -> Option<Result<(), TransactionValidityError>> {969		match self {970			Call::Ethereum(call) => call.pre_dispatch_self_contained(info),971			_ => None,972		}973	}974975	fn apply_self_contained(976		self,977		info: Self::SignedInfo,978	) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {979		match self {980			call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(981				Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),982			)),983			_ => None,984		}985	}986}987988macro_rules! dispatch_nft_runtime {989	($collection:ident.$method:ident($($name:ident),*)) => {{990		use pallet_nft::dispatch::Dispatched;991992		let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::new($collection).unwrap());993		let dispatch = collection.as_dyn();994995		dispatch.$method($($name),*)996	}};997}998impl_runtime_apis! {999	impl up_rpc::NftApi<Block, CrossAccountId, AccountId>1000		for Runtime1001	{1002		fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId> {1003			dispatch_nft_runtime!(collection.account_tokens(account))1004		}1005		fn token_exists(collection: CollectionId, token: TokenId) -> bool {1006			dispatch_nft_runtime!(collection.token_exists(token))1007		}10081009		fn token_owner(collection: CollectionId, token: TokenId) -> CrossAccountId {1010			dispatch_nft_runtime!(collection.token_owner(token))1011		}1012		fn const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {1013			dispatch_nft_runtime!(collection.const_metadata(token))1014		}1015		fn variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {1016			dispatch_nft_runtime!(collection.variable_metadata(token))1017		}10181019		fn collection_tokens(collection: CollectionId) -> u32 {1020			dispatch_nft_runtime!(collection.collection_tokens())1021		}1022		fn account_balance(collection: CollectionId, account: CrossAccountId) -> u32 {1023			dispatch_nft_runtime!(collection.account_balance(account))1024		}1025		fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> u128 {1026			dispatch_nft_runtime!(collection.balance(account, token))1027		}1028		fn allowance(1029			collection: CollectionId,1030			sender: CrossAccountId,1031			spender: CrossAccountId,1032			token: TokenId,1033		) -> u128 {1034			dispatch_nft_runtime!(collection.allowance(sender, spender, token))1035		}10361037		fn eth_contract_code(account: H160) -> Option<Vec<u8>> {1038			<pallet_nft::NftErcSupport<Runtime>>::get_code(&account)1039				.or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account))1040				.or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))1041		}1042		fn adminlist(collection: CollectionId) -> Vec<CrossAccountId> {1043			<pallet_nft::Pallet<Runtime>>::adminlist(collection)1044		}1045		fn allowlist(collection: CollectionId) -> Vec<CrossAccountId> {1046			<pallet_nft::Pallet<Runtime>>::allowlist(collection)1047		}1048		fn last_token_id(collection: CollectionId) -> TokenId {1049			dispatch_nft_runtime!(collection.last_token_id())1050		}1051	}10521053	impl sp_api::Core<Block> for Runtime {1054		fn version() -> RuntimeVersion {1055			VERSION1056		}10571058		fn execute_block(block: Block) {1059			Executive::execute_block(block)1060		}10611062		fn initialize_block(header: &<Block as BlockT>::Header) {1063			Executive::initialize_block(header)1064		}1065	}10661067	impl sp_api::Metadata<Block> for Runtime {1068		fn metadata() -> OpaqueMetadata {1069			OpaqueMetadata::new(Runtime::metadata().into())1070		}1071	}10721073	impl sp_block_builder::BlockBuilder<Block> for Runtime {1074		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {1075			Executive::apply_extrinsic(extrinsic)1076		}10771078		fn finalize_block() -> <Block as BlockT>::Header {1079			Executive::finalize_block()1080		}10811082		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1083			data.create_extrinsics()1084		}10851086		fn check_inherents(1087			block: Block,1088			data: sp_inherents::InherentData,1089		) -> sp_inherents::CheckInherentsResult {1090			data.check_extrinsics(&block)1091		}10921093		// fn random_seed() -> <Block as BlockT>::Hash {1094		//     RandomnessCollectiveFlip::random_seed().01095		// }1096	}10971098	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1099		fn validate_transaction(1100			source: TransactionSource,1101			tx: <Block as BlockT>::Extrinsic,1102			hash: <Block as BlockT>::Hash,1103		) -> TransactionValidity {1104			Executive::validate_transaction(source, tx, hash)1105		}1106	}11071108	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1109		fn offchain_worker(header: &<Block as BlockT>::Header) {1110			Executive::offchain_worker(header)1111		}1112	}11131114	impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1115		fn chain_id() -> u64 {1116			<Runtime as pallet_evm::Config>::ChainId::get()1117		}11181119		fn account_basic(address: H160) -> EVMAccount {1120			EVM::account_basic(&address)1121		}11221123		fn gas_price() -> U256 {1124			<Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1125		}11261127		fn account_code_at(address: H160) -> Vec<u8> {1128			EVM::account_codes(address)1129		}11301131		fn author() -> H160 {1132			<pallet_evm::Pallet<Runtime>>::find_author()1133		}11341135		fn storage_at(address: H160, index: U256) -> H256 {1136			let mut tmp = [0u8; 32];1137			index.to_big_endian(&mut tmp);1138			EVM::account_storages(address, H256::from_slice(&tmp[..]))1139		}11401141		fn call(1142			from: H160,1143			to: H160,1144			data: Vec<u8>,1145			value: U256,1146			gas_limit: U256,1147			gas_price: Option<U256>,1148			nonce: Option<U256>,1149			estimate: bool,1150		) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1151			let config = if estimate {1152				let mut config = <Runtime as pallet_evm::Config>::config().clone();1153				config.estimate = true;1154				Some(config)1155			} else {1156				None1157			};11581159			<Runtime as pallet_evm::Config>::Runner::call(1160				from,1161				to,1162				data,1163				value,1164				gas_limit.low_u64(),1165				gas_price,1166				nonce,1167				config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1168			).map_err(|err| err.into())1169		}11701171		fn create(1172			from: H160,1173			data: Vec<u8>,1174			value: U256,1175			gas_limit: U256,1176			gas_price: Option<U256>,1177			nonce: Option<U256>,1178			estimate: bool,1179		) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1180			let config = if estimate {1181				let mut config = <Runtime as pallet_evm::Config>::config().clone();1182				config.estimate = true;1183				Some(config)1184			} else {1185				None1186			};11871188			<Runtime as pallet_evm::Config>::Runner::create(1189				from,1190				data,1191				value,1192				gas_limit.low_u64(),1193				gas_price,1194				nonce,1195				config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1196			).map_err(|err| err.into())1197		}11981199		fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1200			Ethereum::current_transaction_statuses()1201		}12021203		fn current_block() -> Option<pallet_ethereum::Block> {1204			Ethereum::current_block()1205		}12061207		fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1208			Ethereum::current_receipts()1209		}12101211		fn current_all() -> (1212			Option<pallet_ethereum::Block>,1213			Option<Vec<pallet_ethereum::Receipt>>,1214			Option<Vec<TransactionStatus>>1215		) {1216			(1217				Ethereum::current_block(),1218				Ethereum::current_receipts(),1219				Ethereum::current_transaction_statuses()1220			)1221		}12221223		fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1224			xts.into_iter().filter_map(|xt| match xt.0.function {1225				Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1226				_ => None1227			}).collect()1228		}1229	}12301231	impl sp_session::SessionKeys<Block> for Runtime {1232		fn decode_session_keys(1233			encoded: Vec<u8>,1234		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1235			SessionKeys::decode_into_raw_public_keys(&encoded)1236		}12371238		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1239			SessionKeys::generate(seed)1240		}1241	}12421243	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1244		fn slot_duration() -> sp_consensus_aura::SlotDuration {1245			sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1246		}12471248		fn authorities() -> Vec<AuraId> {1249			Aura::authorities().to_vec()1250		}1251	}12521253	impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1254		fn collect_collation_info() -> cumulus_primitives_core::CollationInfo {1255			ParachainSystem::collect_collation_info()1256		}1257	}12581259	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1260		fn account_nonce(account: AccountId) -> Index {1261			System::account_nonce(account)1262		}1263	}12641265	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1266		fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1267			TransactionPayment::query_info(uxt, len)1268		}1269		fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1270			TransactionPayment::query_fee_details(uxt, len)1271		}1272	}12731274	/*1275	impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1276		for Runtime1277	{1278		fn call(1279			origin: AccountId,1280			dest: AccountId,1281			value: Balance,1282			gas_limit: u64,1283			input_data: Vec<u8>,1284		) -> pallet_contracts_primitives::ContractExecResult {1285			Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1286		}12871288		fn instantiate(1289			origin: AccountId,1290			endowment: Balance,1291			gas_limit: u64,1292			code: pallet_contracts_primitives::Code<Hash>,1293			data: Vec<u8>,1294			salt: Vec<u8>,1295		) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1296		{1297			Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1298		}12991300		fn get_storage(1301			address: AccountId,1302			key: [u8; 32],1303		) -> pallet_contracts_primitives::GetStorageResult {1304			Contracts::get_storage(address, key)1305		}13061307		fn rent_projection(1308			address: AccountId,1309		) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1310			Contracts::rent_projection(address)1311		}1312	}1313	*/13141315	#[cfg(feature = "runtime-benchmarks")]1316	impl frame_benchmarking::Benchmark<Block> for Runtime {1317		fn benchmark_metadata(extra: bool) -> (1318			Vec<frame_benchmarking::BenchmarkList>,1319			Vec<frame_support::traits::StorageInfo>,1320		) {1321			use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};1322			use frame_support::traits::StorageInfoTrait;13231324			let mut list = Vec::<BenchmarkList>::new();13251326			list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);1327			list_benchmark!(list, extra, pallet_nft, Nft);1328			list_benchmark!(list, extra, pallet_inflation, Inflation);1329			list_benchmark!(list, extra, pallet_fungible, Fungible);1330			list_benchmark!(list, extra, pallet_refungible, Refungible);1331			list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);13321333			let storage_info = AllPalletsWithSystem::storage_info();13341335			return (list, storage_info)1336		}13371338		fn dispatch_benchmark(1339			config: frame_benchmarking::BenchmarkConfig1340		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1341			use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};13421343			let allowlist: Vec<TrackedStorageKey> = vec![1344				// Block Number1345				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),1346				// Total Issuance1347				hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1348				// Execution Phase1349				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1350				// Event Count1351				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1352				// System Events1353				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1354			];13551356			let mut batches = Vec::<BenchmarkBatch>::new();1357			let params = (&config, &allowlist);13581359			add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1360			add_benchmark!(params, batches, pallet_nft, Nft);1361			add_benchmark!(params, batches, pallet_inflation, Inflation);1362			add_benchmark!(params, batches, pallet_fungible, Fungible);1363			add_benchmark!(params, batches, pallet_refungible, Refungible);1364			add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);13651366			if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1367			Ok(batches)1368		}1369	}1370}13711372struct CheckInherents;13731374impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1375	fn check_inherents(1376		block: &Block,1377		relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1378	) -> sp_inherents::CheckInherentsResult {1379		let relay_chain_slot = relay_state_proof1380			.read_slot()1381			.expect("Could not read the relay chain slot from the proof");13821383		let inherent_data =1384			cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1385				relay_chain_slot,1386				sp_std::time::Duration::from_secs(6),1387			)1388			.create_inherent_data()1389			.expect("Could not create the timestamp inherent data");13901391		inherent_data.check_extrinsics(block)1392	}1393}13941395cumulus_pallet_parachain_system::register_validate_block!(1396	Runtime = Runtime,1397	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1398	CheckInherents = CheckInherents,1399);
after · runtime/src/lib.rs
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "1024"]11#![allow(clippy::from_over_into, clippy::identity_op)]12#![allow(clippy::fn_to_numeric_cast_with_truncation)]13// Make the WASM binary available.14#[cfg(feature = "std")]15include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1617use sp_api::impl_runtime_apis;18use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};19// #[cfg(any(feature = "std", test))]20// pub use sp_runtime::BuildStorage;2122use sp_runtime::{23	Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,24	traits::{25		AccountIdLookup, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify,26		AccountIdConversion,27	},28	transaction_validity::{TransactionSource, TransactionValidity},29	ApplyExtrinsicResult, MultiSignature,30};3132use sp_std::prelude::*;3334#[cfg(feature = "std")]35use sp_version::NativeVersion;36use sp_version::RuntimeVersion;37pub use pallet_transaction_payment::{38	Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,39};40// A few exports that help ease life for downstream crates.41pub use pallet_balances::Call as BalancesCall;42pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};43pub use frame_support::{44	construct_runtime, match_type,45	dispatch::DispatchResult,46	PalletId, parameter_types, StorageValue, ConsensusEngineId,47	traits::{48		Everything, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem,49		LockIdentifier, OnUnbalanced, Randomness, FindAuthor,50	},51	weights::{52		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},53		DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,54		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,55	},56};57use nft_data_structs::*;58// use pallet_contracts::weights::WeightInfo;59// #[cfg(any(feature = "std", test))]60use frame_system::{61	self as system, EnsureRoot, EnsureSigned,62	limits::{BlockWeights, BlockLength},63};64use sp_arithmetic::{65	traits::{BaseArithmetic, Unsigned},66};67use smallvec::smallvec;68use codec::{Encode, Decode};69use pallet_evm::{Account as EVMAccount, FeeCalculator, OnMethodCall};70use fp_rpc::TransactionStatus;71use sp_core::crypto::Public;72use sp_runtime::{73	traits::{Dispatchable, PostDispatchInfoOf},74	transaction_validity::TransactionValidityError,75};7677// pub use pallet_timestamp::Call as TimestampCall;78pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;7980// Polkadot imports81use pallet_xcm::XcmPassthrough;82use polkadot_parachain::primitives::Sibling;83use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};84use xcm_builder::{85	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,86	EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset,87	ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,88	SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,89	SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,90};91use xcm_executor::{Config, XcmExecutor};9293// mod chain_extension;94// use crate::chain_extension::{NFTExtension, Imbalance};9596/// An index to a block.97pub type BlockNumber = u32;9899/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.100pub type Signature = MultiSignature;101102/// Some way of identifying an account on the chain. We intentionally make it equivalent103/// to the public key of our transaction signing scheme.104pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;105106pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;107108/// The type for looking up accounts. We don't expect more than 4 billion of them, but you109/// never know...110pub type AccountIndex = u32;111112/// Balance of an account.113pub type Balance = u128;114115/// Index of a transaction in the chain.116pub type Index = u32;117118/// A hash of some data used by the chain.119pub type Hash = sp_core::H256;120121/// Digest item type.122pub type DigestItem = generic::DigestItem<Hash>;123124/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know125/// the specifics of the runtime. They can then be made to be agnostic over specific formats126/// of data like extrinsics, allowing for them to continue syncing the network through upgrades127/// to even the core data structures.128pub mod opaque {129	use super::*;130131	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;132133	/// Opaque block type.134	pub type Block = generic::Block<Header, UncheckedExtrinsic>;135136	pub type SessionHandlers = ();137138	impl_opaque_keys! {139		pub struct SessionKeys {140			pub aura: Aura,141		}142	}143}144145/// This runtime version.146pub const VERSION: RuntimeVersion = RuntimeVersion {147	spec_name: create_runtime_str!("opal"),148	impl_name: create_runtime_str!("opal"),149	authoring_version: 1,150	spec_version: 912202,151	impl_version: 1,152	apis: RUNTIME_API_VERSIONS,153	transaction_version: 1,154};155156pub const MILLISECS_PER_BLOCK: u64 = 12000;157158pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;159160// These time units are defined in number of blocks.161pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);162pub const HOURS: BlockNumber = MINUTES * 60;163pub const DAYS: BlockNumber = HOURS * 24;164165parameter_types! {166	pub const DefaultSponsoringRateLimit: BlockNumber = 1 * DAYS;167}168169#[derive(codec::Encode, codec::Decode)]170pub enum XCMPMessage<XAccountId, XBalance> {171	/// Transfer tokens to the given account from the Parachain account.172	TransferToken(XAccountId, XBalance),173}174175/// The version information used to identify this runtime when compiled natively.176#[cfg(feature = "std")]177pub fn native_version() -> NativeVersion {178	NativeVersion {179		runtime_version: VERSION,180		can_author_with: Default::default(),181	}182}183184type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;185186pub struct DealWithFees;187impl OnUnbalanced<NegativeImbalance> for DealWithFees {188	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {189		if let Some(fees) = fees_then_tips.next() {190			// for fees, 100% to treasury191			let mut split = fees.ration(100, 0);192			if let Some(tips) = fees_then_tips.next() {193				// for tips, if any, 100% to treasury194				tips.ration_merge_into(100, 0, &mut split);195			}196			Treasury::on_unbalanced(split.0);197			// Author::on_unbalanced(split.1);198		}199	}200}201202/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.203/// This is used to limit the maximal weight of a single extrinsic.204const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);205/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used206/// by  Operational  extrinsics.207const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);208/// We allow for 2 seconds of compute with a 6 second average block time.209const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2;210211parameter_types! {212	pub const BlockHashCount: BlockNumber = 2400;213	pub RuntimeBlockLength: BlockLength =214		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);215	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);216	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;217	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()218		.base_block(BlockExecutionWeight::get())219		.for_class(DispatchClass::all(), |weights| {220			weights.base_extrinsic = ExtrinsicBaseWeight::get();221		})222		.for_class(DispatchClass::Normal, |weights| {223			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);224		})225		.for_class(DispatchClass::Operational, |weights| {226			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);227			// Operational transactions have some extra reserved space, so that they228			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.229			weights.reserved = Some(230				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT231			);232		})233		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)234		.build_or_panic();235	pub const Version: RuntimeVersion = VERSION;236	pub const SS58Prefix: u8 = 42;237}238239parameter_types! {240	pub const ChainId: u64 = 8888;241}242243pub struct FixedFee;244impl FeeCalculator for FixedFee {245	fn min_gas_price() -> U256 {246		1.into()247	}248}249250impl pallet_evm::Config for Runtime {251	type BlockGasLimit = BlockGasLimit;252	type FeeCalculator = FixedFee;253	type GasWeightMapping = ();254	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;255	type CallOrigin = EnsureAddressTruncated;256	type WithdrawOrigin = EnsureAddressTruncated;257	type AddressMapping = HashedAddressMapping<Self::Hashing>;258	type Precompiles = ();259	type Currency = Balances;260	type Event = Event;261	type OnMethodCall = (262		pallet_evm_migration::OnMethodCall<Self>,263		pallet_nft::NftErcSupport<Self>,264		pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,265	);266	type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;267	type ChainId = ChainId;268	type Runner = pallet_evm::runner::stack::Runner<Self>;269	type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;270	type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;271	type FindAuthor = EthereumFindAuthor<Aura>;272}273274impl pallet_evm_migration::Config for Runtime {275	type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;276}277278pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);279impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {280	fn find_author<'a, I>(digests: I) -> Option<H160>281	where282		I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,283	{284		if let Some(author_index) = F::find_author(digests) {285			let authority_id = Aura::authorities()[author_index as usize].clone();286			return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));287		}288		None289	}290}291292parameter_types! {293	pub BlockGasLimit: U256 = U256::from(u32::max_value());294}295296impl pallet_ethereum::Config for Runtime {297	type Event = Event;298	type StateRoot = pallet_ethereum::IntermediateStateRoot;299	type EvmSubmitLog = pallet_evm::Pallet<Self>;300}301302impl pallet_randomness_collective_flip::Config for Runtime {}303304impl system::Config for Runtime {305	/// The data to be stored in an account.306	type AccountData = pallet_balances::AccountData<Balance>;307	/// The identifier used to distinguish between accounts.308	type AccountId = AccountId;309	/// The basic call filter to use in dispatchable.310	type BaseCallFilter = Everything;311	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).312	type BlockHashCount = BlockHashCount;313	/// The maximum length of a block (in bytes).314	type BlockLength = RuntimeBlockLength;315	/// The index type for blocks.316	type BlockNumber = BlockNumber;317	/// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.318	type BlockWeights = RuntimeBlockWeights;319	/// The aggregated dispatch type that is available for extrinsics.320	type Call = Call;321	/// The weight of database operations that the runtime can invoke.322	type DbWeight = RocksDbWeight;323	/// The ubiquitous event type.324	type Event = Event;325	/// The type for hashing blocks and tries.326	type Hash = Hash;327	/// The hashing algorithm used.328	type Hashing = BlakeTwo256;329	/// The header type.330	type Header = generic::Header<BlockNumber, BlakeTwo256>;331	/// The index type for storing how many extrinsics an account has signed.332	type Index = Index;333	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.334	type Lookup = AccountIdLookup<AccountId, ()>;335	/// What to do if an account is fully reaped from the system.336	type OnKilledAccount = ();337	/// What to do if a new account is created.338	type OnNewAccount = ();339	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;340	/// The ubiquitous origin type.341	type Origin = Origin;342	/// This type is being generated by `construct_runtime!`.343	type PalletInfo = PalletInfo;344	/// This is used as an identifier of the chain. 42 is the generic substrate prefix.345	type SS58Prefix = SS58Prefix;346	/// Weight information for the extrinsics of this pallet.347	type SystemWeightInfo = system::weights::SubstrateWeight<Self>;348	/// Version of the runtime.349	type Version = Version;350}351352parameter_types! {353	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;354}355356impl pallet_timestamp::Config for Runtime {357	/// A timestamp: milliseconds since the unix epoch.358	type Moment = u64;359	type OnTimestampSet = ();360	type MinimumPeriod = MinimumPeriod;361	type WeightInfo = ();362}363364parameter_types! {365	// pub const ExistentialDeposit: u128 = 500;366	pub const ExistentialDeposit: u128 = 0;367	pub const MaxLocks: u32 = 50;368}369370impl pallet_balances::Config for Runtime {371	type MaxLocks = MaxLocks;372	type MaxReserves = ();373	type ReserveIdentifier = [u8; 8];374	/// The type for recording an account's balance.375	type Balance = Balance;376	/// The ubiquitous event type.377	type Event = Event;378	type DustRemoval = Treasury;379	type ExistentialDeposit = ExistentialDeposit;380	type AccountStore = System;381	type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;382}383384pub const MICROUNIQUE: Balance = 1_000_000_000;385pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;386pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;387pub const UNIQUE: Balance = 100 * CENTIUNIQUE;388389pub const fn deposit(items: u32, bytes: u32) -> Balance {390	items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE391}392393/*394parameter_types! {395	pub TombstoneDeposit: Balance = deposit(396		1,397		sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,398	);399	pub DepositPerContract: Balance = TombstoneDeposit::get();400	pub const DepositPerStorageByte: Balance = deposit(0, 1);401	pub const DepositPerStorageItem: Balance = deposit(1, 0);402	pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);403	pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;404	pub const SignedClaimHandicap: u32 = 2;405	pub const MaxDepth: u32 = 32;406	pub const MaxValueSize: u32 = 16 * 1024;407	pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb408	// The lazy deletion runs inside on_initialize.409	pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *410		RuntimeBlockWeights::get().max_block;411	// The weight needed for decoding the queue should be less or equal than a fifth412	// of the overall weight dedicated to the lazy deletion.413	pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (414			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -415			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)416		)) / 5) as u32;417	pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();418}419420impl pallet_contracts::Config for Runtime {421	type Time = Timestamp;422	type Randomness = RandomnessCollectiveFlip;423	type Currency = Balances;424	type Event = Event;425	type RentPayment = ();426	type SignedClaimHandicap = SignedClaimHandicap;427	type TombstoneDeposit = TombstoneDeposit;428	type DepositPerContract = DepositPerContract;429	type DepositPerStorageByte = DepositPerStorageByte;430	type DepositPerStorageItem = DepositPerStorageItem;431	type RentFraction = RentFraction;432	type SurchargeReward = SurchargeReward;433	type WeightPrice = pallet_transaction_payment::Pallet<Self>;434	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;435	type ChainExtension = NFTExtension;436	type DeletionQueueDepth = DeletionQueueDepth;437	type DeletionWeightLimit = DeletionWeightLimit;438	type Schedule = Schedule;439	type CallStack = [pallet_contracts::Frame<Self>; 31];440}441*/442443parameter_types! {444	pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer445	/// This value increases the priority of `Operational` transactions by adding446	/// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.447	pub const OperationalFeeMultiplier: u8 = 5;448}449450/// Linear implementor of `WeightToFeePolynomial`451pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);452453impl<T> WeightToFeePolynomial for LinearFee<T>454where455	T: BaseArithmetic + From<u32> + Copy + Unsigned,456{457	type Balance = T;458459	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {460		smallvec!(WeightToFeeCoefficient {461			coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer462			coeff_frac: Perbill::zero(),463			negative: false,464			degree: 1,465		})466	}467}468469impl pallet_transaction_payment::Config for Runtime {470	type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;471	type TransactionByteFee = TransactionByteFee;472	type OperationalFeeMultiplier = OperationalFeeMultiplier;473	type WeightToFee = LinearFee<Balance>;474	type FeeMultiplierUpdate = ();475}476477parameter_types! {478	pub const ProposalBond: Permill = Permill::from_percent(5);479	pub const ProposalBondMinimum: Balance = 1 * UNIQUE;480	pub const SpendPeriod: BlockNumber = 5 * MINUTES;481	pub const Burn: Permill = Permill::from_percent(0);482	pub const TipCountdown: BlockNumber = 1 * DAYS;483	pub const TipFindersFee: Percent = Percent::from_percent(20);484	pub const TipReportDepositBase: Balance = 1 * UNIQUE;485	pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;486	pub const BountyDepositBase: Balance = 1 * UNIQUE;487	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;488	pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");489	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;490	pub const MaximumReasonLength: u32 = 16384;491	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);492	pub const BountyValueMinimum: Balance = 5 * UNIQUE;493	pub const MaxApprovals: u32 = 100;494}495496impl pallet_treasury::Config for Runtime {497	type PalletId = TreasuryModuleId;498	type Currency = Balances;499	type ApproveOrigin = EnsureRoot<AccountId>;500	type RejectOrigin = EnsureRoot<AccountId>;501	type Event = Event;502	type OnSlash = ();503	type ProposalBond = ProposalBond;504	type ProposalBondMinimum = ProposalBondMinimum;505	type SpendPeriod = SpendPeriod;506	type Burn = Burn;507	type BurnDestination = ();508	type SpendFunds = ();509	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;510	type MaxApprovals = MaxApprovals;511}512513impl pallet_sudo::Config for Runtime {514	type Event = Event;515	type Call = Call;516}517518parameter_types! {519	pub const MinVestedTransfer: Balance = 10 * UNIQUE;520}521522impl pallet_vesting::Config for Runtime {523	type Event = Event;524	type Currency = Balances;525	type BlockNumberToBalance = ConvertInto;526	type MinVestedTransfer = MinVestedTransfer;527	type WeightInfo = ();528	const MAX_VESTING_SCHEDULES: u32 = 28;529}530531parameter_types! {532	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;533	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;534}535536impl cumulus_pallet_parachain_system::Config for Runtime {537	type Event = Event;538	type OnValidationData = ();539	type SelfParaId = parachain_info::Pallet<Self>;540	// type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<541	// 	MaxDownwardMessageWeight,542	// 	XcmExecutor<XcmConfig>,543	// 	Call,544	// >;545	type OutboundXcmpMessageSource = XcmpQueue;546	type DmpMessageHandler = DmpQueue;547	type ReservedDmpWeight = ReservedDmpWeight;548	type ReservedXcmpWeight = ReservedXcmpWeight;549	type XcmpMessageHandler = XcmpQueue;550}551552impl parachain_info::Config for Runtime {}553554impl cumulus_pallet_aura_ext::Config for Runtime {}555556parameter_types! {557	pub const RelayLocation: MultiLocation = MultiLocation::parent();558	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;559	pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();560	pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();561}562563/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used564/// when determining ownership of accounts for asset transacting and when attempting to use XCM565/// `Transact` in order to determine the dispatch Origin.566pub type LocationToAccountId = (567	// The parent (Relay-chain) origin converts to the default `AccountId`.568	ParentIsDefault<AccountId>,569	// Sibling parachain origins convert to AccountId via the `ParaId::into`.570	SiblingParachainConvertsVia<Sibling, AccountId>,571	// Straight up local `AccountId32` origins just alias directly to `AccountId`.572	AccountId32Aliases<RelayNetwork, AccountId>,573);574575/// Means for transacting assets on this chain.576pub type LocalAssetTransactor = CurrencyAdapter<577	// Use this currency:578	Balances,579	// Use this currency when it is a fungible asset matching the given location or name:580	IsConcrete<RelayLocation>,581	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:582	LocationToAccountId,583	// Our chain's account ID type (we can't get away without mentioning it explicitly):584	AccountId,585	// We don't track any teleports.586	(),587>;588589/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,590/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can591/// biases the kind of local `Origin` it will become.592pub type XcmOriginToTransactDispatchOrigin = (593	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location594	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for595	// foreign chains who want to have a local sovereign account on this chain which they control.596	SovereignSignedViaLocation<LocationToAccountId, Origin>,597	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when598	// recognised.599	RelayChainAsNative<RelayOrigin, Origin>,600	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when601	// recognised.602	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,603	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a604	// transaction from the Root origin.605	ParentAsSuperuser<Origin>,606	// Native signed account converter; this just converts an `AccountId32` origin into a normal607	// `Origin::Signed` origin of the same 32-byte value.608	SignedAccountId32AsNative<RelayNetwork, Origin>,609	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.610	XcmPassthrough<Origin>,611);612613parameter_types! {614	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.615	pub UnitWeightCost: Weight = 1_000_000;616	// 1200 UNIQUEs buy 1 second of weight.617	pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);618	pub const MaxInstructions: u32 = 100;619	pub const MaxAuthorities: u32 = 100_000;620}621622match_type! {623	pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {624		MultiLocation { parents: 1, interior: Here } |625		MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }626	};627}628629pub type Barrier = (630	TakeWeightCredit,631	AllowTopLevelPaidExecutionFrom<Everything>,632	AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,633	// ^^^ Parent & its unit plurality gets free execution634);635636pub struct XcmConfig;637impl Config for XcmConfig {638	type Call = Call;639	type XcmSender = XcmRouter;640	// How to withdraw and deposit an asset.641	type AssetTransactor = LocalAssetTransactor;642	type OriginConverter = XcmOriginToTransactDispatchOrigin;643	type IsReserve = NativeAsset;644	type IsTeleporter = (); // Teleportation is disabled645	type LocationInverter = LocationInverter<Ancestry>;646	type Barrier = Barrier;647	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;648	type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;649	type ResponseHandler = (); // Don't handle responses for now.650	type SubscriptionService = PolkadotXcm;651652	type AssetTrap = PolkadotXcm;653	type AssetClaims = PolkadotXcm;654}655656// parameter_types! {657// 	pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;658// }659660/// No local origins on this chain are allowed to dispatch XCM sends/executions.661pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);662663/// The means for routing XCM messages which are not for local execution into the right message664/// queues.665pub type XcmRouter = (666	// Two routers - use UMP to communicate with the relay chain:667	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,668	// ..and XCMP to communicate with the sibling chains.669	XcmpQueue,670);671672impl pallet_evm_coder_substrate::Config for Runtime {673	type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;674}675676impl pallet_xcm::Config for Runtime {677	type Event = Event;678	type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;679	type XcmRouter = XcmRouter;680	type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;681	type XcmExecuteFilter = Everything;682	type XcmExecutor = XcmExecutor<XcmConfig>;683	type XcmTeleportFilter = Everything;684	type XcmReserveTransferFilter = Everything;685	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;686	type LocationInverter = LocationInverter<Ancestry>;687	type Origin = Origin;688	type Call = Call;689	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;690	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;691}692693impl cumulus_pallet_xcm::Config for Runtime {694	type Event = Event;695	type XcmExecutor = XcmExecutor<XcmConfig>;696}697698impl cumulus_pallet_xcmp_queue::Config for Runtime {699	type Event = Event;700	type XcmExecutor = XcmExecutor<XcmConfig>;701	type ChannelInfo = ParachainSystem;702	type VersionWrapper = ();703}704705impl cumulus_pallet_dmp_queue::Config for Runtime {706	type Event = Event;707	type XcmExecutor = XcmExecutor<XcmConfig>;708	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;709}710711impl pallet_aura::Config for Runtime {712	type AuthorityId = AuraId;713	type DisabledValidators = ();714	type MaxAuthorities = MaxAuthorities;715}716717parameter_types! {718	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();719	pub const CollectionCreationPrice: Balance = 100 * UNIQUE;720}721722impl pallet_common::Config for Runtime {723	type Event = Event;724	type EvmBackwardsAddressMapping = pallet_common::account::MapBackwardsAddressTruncated;725	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;726	type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;727728	type Currency = Balances;729	type CollectionCreationPrice = CollectionCreationPrice;730	type TreasuryAccountId = TreasuryAccountId;731}732733impl pallet_fungible::Config for Runtime {734	type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;735}736impl pallet_refungible::Config for Runtime {737	type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;738}739impl pallet_nonfungible::Config for Runtime {740	type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;741}742743/// Used for the pallet nft in `./nft.rs`744impl pallet_nft::Config for Runtime {745	type WeightInfo = pallet_nft::weights::SubstrateWeight<Self>;746}747748parameter_types! {749	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied750}751752/// Used for the pallet inflation753impl pallet_inflation::Config for Runtime {754	type Currency = Balances;755	type TreasuryAccountId = TreasuryAccountId;756	type InflationBlockInterval = InflationBlockInterval;757}758759parameter_types! {760	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *761		RuntimeBlockWeights::get().max_block;762	pub const MaxScheduledPerBlock: u32 = 50;763}764765pub struct Sponsoring;766impl SponsoringResolve<AccountId, Call> for Sponsoring {767	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>768	where769		Call: Dispatchable<Info = DispatchInfo>,770		AccountId: AsRef<[u8]>,771	{772		pallet_nft_transaction_payment::Module::<Runtime>::withdraw_type(who, call)773	}774}775776type SponsorshipHandler = (777	pallet_nft::NftSponsorshipHandler<Runtime>,778	//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,779);780781impl pallet_unq_scheduler::Config for Runtime {782	type Event = Event;783	type Origin = Origin;784	type PalletsOrigin = OriginCaller;785	type Call = Call;786	type MaximumWeight = MaximumSchedulerWeight;787	type ScheduleOrigin = EnsureSigned<AccountId>;788	type MaxScheduledPerBlock = MaxScheduledPerBlock;789	type SponsorshipHandler = SponsorshipHandler;790	type WeightInfo = ();791}792793impl pallet_nft_transaction_payment::Config for Runtime {794	type SponsorshipHandler = SponsorshipHandler;795}796797impl pallet_evm_transaction_payment::Config for Runtime {798	type SponsorshipHandler = (799		pallet_nft::NftEthSponsorshipHandler<Self>,800		pallet_evm_contract_helpers::HelpersContractSponsoring<Self>,801	);802	type Currency = Balances;803}804805impl pallet_nft_charge_transaction::Config for Runtime {806	type SponsorshipHandler = pallet_nft::NftSponsorshipHandler<Runtime>;807}808809// impl pallet_contract_helpers::Config for Runtime {810//	 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;811// }812813parameter_types! {814	// 0x842899ECF380553E8a4de75bF534cdf6fBF64049815	pub const HelpersContractAddress: H160 = H160([816		0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,817	]);818}819820impl pallet_evm_contract_helpers::Config for Runtime {821	type ContractAddress = HelpersContractAddress;822	type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;823}824825construct_runtime!(826	pub enum Runtime where827		Block = Block,828		NodeBlock = opaque::Block,829		UncheckedExtrinsic = UncheckedExtrinsic830	{831		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,832		ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,833834		Aura: pallet_aura::{Pallet, Config<T>} = 22,835		AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,836837		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,838		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,839		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,840		TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,841		Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,842		Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,843		System: system::{Pallet, Call, Storage, Config, Event<T>} = 36,844		Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,845		// Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,846847		// XCM helpers.848		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,849		PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,850		CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,851		DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,852853		// Unique Pallets854		Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,855		Nft: pallet_nft::{Pallet, Call, Storage} = 61,856		Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,857		NftPayment: pallet_nft_transaction_payment::{Pallet, Call, Storage} = 63,858		Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage } = 64,859		// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,860		Common: pallet_common::{Pallet, Storage, Event<T>} = 66,861		Fungible: pallet_fungible::{Pallet, Storage} = 67,862		Refungible: pallet_refungible::{Pallet, Storage} = 68,863		Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,864865		// Frontier866		EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,867		Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,868869		EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,870		EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,871		EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,872		EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,873	}874);875876pub struct TransactionConverter;877878impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {879	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {880		UncheckedExtrinsic::new_unsigned(881			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),882		)883	}884}885886impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {887	fn convert_transaction(888		&self,889		transaction: pallet_ethereum::Transaction,890	) -> opaque::UncheckedExtrinsic {891		let extrinsic = UncheckedExtrinsic::new_unsigned(892			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),893		);894		let encoded = extrinsic.encode();895		opaque::UncheckedExtrinsic::decode(&mut &encoded[..])896			.expect("Encoded extrinsic is always valid")897	}898}899900/// The address format for describing accounts.901pub type Address = sp_runtime::MultiAddress<AccountId, ()>;902/// Block header type as expected by this runtime.903pub type Header = generic::Header<BlockNumber, BlakeTwo256>;904/// Block type as expected by this runtime.905pub type Block = generic::Block<Header, UncheckedExtrinsic>;906/// A Block signed with a Justification907pub type SignedBlock = generic::SignedBlock<Block>;908/// BlockId type as expected by this runtime.909pub type BlockId = generic::BlockId<Block>;910/// The SignedExtension to the basic transaction logic.911pub type SignedExtra = (912	system::CheckSpecVersion<Runtime>,913	// system::CheckTxVersion<Runtime>,914	system::CheckGenesis<Runtime>,915	system::CheckEra<Runtime>,916	system::CheckNonce<Runtime>,917	system::CheckWeight<Runtime>,918	pallet_nft_charge_transaction::ChargeTransactionPayment<Runtime>,919	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,920);921/// Unchecked extrinsic type as expected by this runtime.922pub type UncheckedExtrinsic =923	fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;924/// Extrinsic type that has already been checked.925pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;926/// Executive: handles dispatch to the various modules.927pub type Executive = frame_executive::Executive<928	Runtime,929	Block,930	frame_system::ChainContext<Runtime>,931	Runtime,932	AllPallets,933>;934935impl_opaque_keys! {936	pub struct SessionKeys {937		pub aura: Aura,938	}939}940941impl fp_self_contained::SelfContainedCall for Call {942	type SignedInfo = H160;943944	fn is_self_contained(&self) -> bool {945		match self {946			Call::Ethereum(call) => call.is_self_contained(),947			_ => false,948		}949	}950951	fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {952		match self {953			Call::Ethereum(call) => call.check_self_contained(),954			_ => None,955		}956	}957958	fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {959		match self {960			Call::Ethereum(call) => call.validate_self_contained(info),961			_ => None,962		}963	}964965	fn pre_dispatch_self_contained(966		&self,967		info: &Self::SignedInfo,968	) -> Option<Result<(), TransactionValidityError>> {969		match self {970			Call::Ethereum(call) => call.pre_dispatch_self_contained(info),971			_ => None,972		}973	}974975	fn apply_self_contained(976		self,977		info: Self::SignedInfo,978	) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {979		match self {980			call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(981				Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),982			)),983			_ => None,984		}985	}986}987988macro_rules! dispatch_nft_runtime {989	($collection:ident.$method:ident($($name:ident),*)) => {{990		use pallet_nft::dispatch::Dispatched;991992		let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::new($collection).unwrap());993		let dispatch = collection.as_dyn();994995		dispatch.$method($($name),*)996	}};997}998impl_runtime_apis! {999	impl up_rpc::NftApi<Block, CrossAccountId, AccountId>1000		for Runtime1001	{1002		fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId> {1003			dispatch_nft_runtime!(collection.account_tokens(account))1004		}1005		fn token_exists(collection: CollectionId, token: TokenId) -> bool {1006			dispatch_nft_runtime!(collection.token_exists(token))1007		}10081009		fn token_owner(collection: CollectionId, token: TokenId) -> CrossAccountId {1010			dispatch_nft_runtime!(collection.token_owner(token))1011		}1012		fn const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {1013			dispatch_nft_runtime!(collection.const_metadata(token))1014		}1015		fn variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {1016			dispatch_nft_runtime!(collection.variable_metadata(token))1017		}10181019		fn collection_tokens(collection: CollectionId) -> u32 {1020			dispatch_nft_runtime!(collection.collection_tokens())1021		}1022		fn account_balance(collection: CollectionId, account: CrossAccountId) -> u32 {1023			dispatch_nft_runtime!(collection.account_balance(account))1024		}1025		fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> u128 {1026			dispatch_nft_runtime!(collection.balance(account, token))1027		}1028		fn allowance(1029			collection: CollectionId,1030			sender: CrossAccountId,1031			spender: CrossAccountId,1032			token: TokenId,1033		) -> u128 {1034			dispatch_nft_runtime!(collection.allowance(sender, spender, token))1035		}10361037		fn eth_contract_code(account: H160) -> Option<Vec<u8>> {1038			<pallet_nft::NftErcSupport<Runtime>>::get_code(&account)1039				.or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account))1040				.or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))1041		}1042		fn adminlist(collection: CollectionId) -> Vec<CrossAccountId> {1043			<pallet_common::Pallet<Runtime>>::adminlist(collection)1044		}1045		fn allowlist(collection: CollectionId) -> Vec<CrossAccountId> {1046			<pallet_common::Pallet<Runtime>>::allowlist(collection)1047		}1048		fn allowed(collection: CollectionId, user: CrossAccountId) -> bool {1049			<pallet_common::Pallet<Runtime>>::allowed(collection, user)1050		}1051		fn last_token_id(collection: CollectionId) -> TokenId {1052			dispatch_nft_runtime!(collection.last_token_id())1053		}1054		fn collection_by_id(collection: CollectionId) -> Option<Collection<AccountId>> {1055			<pallet_common::CollectionById<Runtime>>::get(collection)1056		}1057		fn collection_stats() -> CollectionStats {1058			<pallet_common::Pallet<Runtime>>::collection_stats()1059		}1060	}10611062	impl sp_api::Core<Block> for Runtime {1063		fn version() -> RuntimeVersion {1064			VERSION1065		}10661067		fn execute_block(block: Block) {1068			Executive::execute_block(block)1069		}10701071		fn initialize_block(header: &<Block as BlockT>::Header) {1072			Executive::initialize_block(header)1073		}1074	}10751076	impl sp_api::Metadata<Block> for Runtime {1077		fn metadata() -> OpaqueMetadata {1078			OpaqueMetadata::new(Runtime::metadata().into())1079		}1080	}10811082	impl sp_block_builder::BlockBuilder<Block> for Runtime {1083		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {1084			Executive::apply_extrinsic(extrinsic)1085		}10861087		fn finalize_block() -> <Block as BlockT>::Header {1088			Executive::finalize_block()1089		}10901091		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1092			data.create_extrinsics()1093		}10941095		fn check_inherents(1096			block: Block,1097			data: sp_inherents::InherentData,1098		) -> sp_inherents::CheckInherentsResult {1099			data.check_extrinsics(&block)1100		}11011102		// fn random_seed() -> <Block as BlockT>::Hash {1103		//     RandomnessCollectiveFlip::random_seed().01104		// }1105	}11061107	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1108		fn validate_transaction(1109			source: TransactionSource,1110			tx: <Block as BlockT>::Extrinsic,1111			hash: <Block as BlockT>::Hash,1112		) -> TransactionValidity {1113			Executive::validate_transaction(source, tx, hash)1114		}1115	}11161117	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1118		fn offchain_worker(header: &<Block as BlockT>::Header) {1119			Executive::offchain_worker(header)1120		}1121	}11221123	impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1124		fn chain_id() -> u64 {1125			<Runtime as pallet_evm::Config>::ChainId::get()1126		}11271128		fn account_basic(address: H160) -> EVMAccount {1129			EVM::account_basic(&address)1130		}11311132		fn gas_price() -> U256 {1133			<Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1134		}11351136		fn account_code_at(address: H160) -> Vec<u8> {1137			EVM::account_codes(address)1138		}11391140		fn author() -> H160 {1141			<pallet_evm::Pallet<Runtime>>::find_author()1142		}11431144		fn storage_at(address: H160, index: U256) -> H256 {1145			let mut tmp = [0u8; 32];1146			index.to_big_endian(&mut tmp);1147			EVM::account_storages(address, H256::from_slice(&tmp[..]))1148		}11491150		fn call(1151			from: H160,1152			to: H160,1153			data: Vec<u8>,1154			value: U256,1155			gas_limit: U256,1156			gas_price: Option<U256>,1157			nonce: Option<U256>,1158			estimate: bool,1159		) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1160			let config = if estimate {1161				let mut config = <Runtime as pallet_evm::Config>::config().clone();1162				config.estimate = true;1163				Some(config)1164			} else {1165				None1166			};11671168			<Runtime as pallet_evm::Config>::Runner::call(1169				from,1170				to,1171				data,1172				value,1173				gas_limit.low_u64(),1174				gas_price,1175				nonce,1176				config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1177			).map_err(|err| err.into())1178		}11791180		fn create(1181			from: H160,1182			data: Vec<u8>,1183			value: U256,1184			gas_limit: U256,1185			gas_price: Option<U256>,1186			nonce: Option<U256>,1187			estimate: bool,1188		) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1189			let config = if estimate {1190				let mut config = <Runtime as pallet_evm::Config>::config().clone();1191				config.estimate = true;1192				Some(config)1193			} else {1194				None1195			};11961197			<Runtime as pallet_evm::Config>::Runner::create(1198				from,1199				data,1200				value,1201				gas_limit.low_u64(),1202				gas_price,1203				nonce,1204				config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1205			).map_err(|err| err.into())1206		}12071208		fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1209			Ethereum::current_transaction_statuses()1210		}12111212		fn current_block() -> Option<pallet_ethereum::Block> {1213			Ethereum::current_block()1214		}12151216		fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1217			Ethereum::current_receipts()1218		}12191220		fn current_all() -> (1221			Option<pallet_ethereum::Block>,1222			Option<Vec<pallet_ethereum::Receipt>>,1223			Option<Vec<TransactionStatus>>1224		) {1225			(1226				Ethereum::current_block(),1227				Ethereum::current_receipts(),1228				Ethereum::current_transaction_statuses()1229			)1230		}12311232		fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1233			xts.into_iter().filter_map(|xt| match xt.0.function {1234				Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1235				_ => None1236			}).collect()1237		}1238	}12391240	impl sp_session::SessionKeys<Block> for Runtime {1241		fn decode_session_keys(1242			encoded: Vec<u8>,1243		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1244			SessionKeys::decode_into_raw_public_keys(&encoded)1245		}12461247		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1248			SessionKeys::generate(seed)1249		}1250	}12511252	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1253		fn slot_duration() -> sp_consensus_aura::SlotDuration {1254			sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1255		}12561257		fn authorities() -> Vec<AuraId> {1258			Aura::authorities().to_vec()1259		}1260	}12611262	impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1263		fn collect_collation_info() -> cumulus_primitives_core::CollationInfo {1264			ParachainSystem::collect_collation_info()1265		}1266	}12671268	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1269		fn account_nonce(account: AccountId) -> Index {1270			System::account_nonce(account)1271		}1272	}12731274	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1275		fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1276			TransactionPayment::query_info(uxt, len)1277		}1278		fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1279			TransactionPayment::query_fee_details(uxt, len)1280		}1281	}12821283	/*1284	impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1285		for Runtime1286	{1287		fn call(1288			origin: AccountId,1289			dest: AccountId,1290			value: Balance,1291			gas_limit: u64,1292			input_data: Vec<u8>,1293		) -> pallet_contracts_primitives::ContractExecResult {1294			Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1295		}12961297		fn instantiate(1298			origin: AccountId,1299			endowment: Balance,1300			gas_limit: u64,1301			code: pallet_contracts_primitives::Code<Hash>,1302			data: Vec<u8>,1303			salt: Vec<u8>,1304		) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1305		{1306			Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1307		}13081309		fn get_storage(1310			address: AccountId,1311			key: [u8; 32],1312		) -> pallet_contracts_primitives::GetStorageResult {1313			Contracts::get_storage(address, key)1314		}13151316		fn rent_projection(1317			address: AccountId,1318		) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1319			Contracts::rent_projection(address)1320		}1321	}1322	*/13231324	#[cfg(feature = "runtime-benchmarks")]1325	impl frame_benchmarking::Benchmark<Block> for Runtime {1326		fn benchmark_metadata(extra: bool) -> (1327			Vec<frame_benchmarking::BenchmarkList>,1328			Vec<frame_support::traits::StorageInfo>,1329		) {1330			use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};1331			use frame_support::traits::StorageInfoTrait;13321333			let mut list = Vec::<BenchmarkList>::new();13341335			list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);1336			list_benchmark!(list, extra, pallet_nft, Nft);1337			list_benchmark!(list, extra, pallet_inflation, Inflation);1338			list_benchmark!(list, extra, pallet_fungible, Fungible);1339			list_benchmark!(list, extra, pallet_refungible, Refungible);1340			list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);13411342			let storage_info = AllPalletsWithSystem::storage_info();13431344			return (list, storage_info)1345		}13461347		fn dispatch_benchmark(1348			config: frame_benchmarking::BenchmarkConfig1349		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1350			use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};13511352			let allowlist: Vec<TrackedStorageKey> = vec![1353				// Block Number1354				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),1355				// Total Issuance1356				hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1357				// Execution Phase1358				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1359				// Event Count1360				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1361				// System Events1362				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1363			];13641365			let mut batches = Vec::<BenchmarkBatch>::new();1366			let params = (&config, &allowlist);13671368			add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1369			add_benchmark!(params, batches, pallet_nft, Nft);1370			add_benchmark!(params, batches, pallet_inflation, Inflation);1371			add_benchmark!(params, batches, pallet_fungible, Fungible);1372			add_benchmark!(params, batches, pallet_refungible, Refungible);1373			add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);13741375			if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1376			Ok(batches)1377		}1378	}1379}13801381struct CheckInherents;13821383impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1384	fn check_inherents(1385		block: &Block,1386		relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1387	) -> sp_inherents::CheckInherentsResult {1388		let relay_chain_slot = relay_state_proof1389			.read_slot()1390			.expect("Could not read the relay chain slot from the proof");13911392		let inherent_data =1393			cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1394				relay_chain_slot,1395				sp_std::time::Duration::from_secs(6),1396			)1397			.create_inherent_data()1398			.expect("Could not create the timestamp inherent data");13991400		inherent_data.check_extrinsics(block)1401	}1402}14031404cumulus_pallet_parachain_system::register_validate_block!(1405	Runtime = Runtime,1406	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1407	CheckInherents = CheckInherents,1408);
modifiedtests/src/addCollectionAdmin.test.tsdiffbeforeafterboth
--- a/tests/src/addCollectionAdmin.test.ts
+++ b/tests/src/addCollectionAdmin.test.ts
@@ -8,7 +8,7 @@
 import chaiAsPromised from 'chai-as-promised';
 import privateKey from './substrate/privateKey';
 import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {addCollectionAdminExpectSuccess, createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId} from './util/helpers';
+import {addCollectionAdminExpectSuccess, createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId, queryCollectionExpectSuccess} from './util/helpers';
 
 chai.use(chaiAsPromised);
 const expect = chai.expect;
@@ -20,7 +20,7 @@
       const alice = privateKey('//Alice');
       const bob = privateKey('//Bob');
 
-      const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.owner.toString()).to.be.equal(alice.address);
 
       const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
@@ -38,7 +38,7 @@
       const bob = privateKey('//Bob');
       const charlie = privateKey('//CHARLIE');
 
-      const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.owner.toString()).to.be.equal(alice.address);
 
       const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
modifiedtests/src/addToAllowList.test.tsdiffbeforeafterboth
--- a/tests/src/addToAllowList.test.ts
+++ b/tests/src/addToAllowList.test.ts
@@ -18,6 +18,7 @@
   normalizeAccountId,
   addCollectionAdminExpectSuccess,
   addToAllowListExpectFail,
+  getCreatedCollectionCount,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
@@ -55,7 +56,7 @@
   it('Allow list an address in the collection that does not exist', async () => {
     await usingApi(async (api) => {
       // tslint:disable-next-line: no-bitwise
-      const collectionId = ((await api.query.common.createdCollectionCount()).toNumber()) + 1;
+      const collectionId = await getCreatedCollectionCount(api) + 1;
       const bob = privateKey('//Bob');
 
       const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(bob.address));
modifiedtests/src/approve.test.tsdiffbeforeafterboth
--- a/tests/src/approve.test.ts
+++ b/tests/src/approve.test.ts
@@ -18,6 +18,7 @@
   transferExpectSuccess,
   addCollectionAdminExpectSuccess,
   adminApproveFromExpectSuccess,
+  getCreatedCollectionCount,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
@@ -94,13 +95,13 @@
   it('Approve for a collection that does not exist', async () => {
     await usingApi(async (api: ApiPromise) => {
       // nft
-      const nftCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+      const nftCollectionCount = await getCreatedCollectionCount(api);
       await approveExpectFail(nftCollectionCount + 1, 1, alice, bob);
       // fungible
-      const fungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+      const fungibleCollectionCount = await getCreatedCollectionCount(api);
       await approveExpectFail(fungibleCollectionCount + 1, 0, alice, bob);
       // reFungible
-      const reFungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+      const reFungibleCollectionCount = await getCreatedCollectionCount(api);
       await approveExpectFail(reFungibleCollectionCount + 1, 1, alice, bob);
     });
   });
modifiedtests/src/change-collection-owner.test.tsdiffbeforeafterboth
--- a/tests/src/change-collection-owner.test.ts
+++ b/tests/src/change-collection-owner.test.ts
@@ -22,6 +22,7 @@
   setMintPermissionExpectFailure,
   destroyCollectionExpectFailure,
   setPublicAccessModeExpectSuccess,
+  queryCollectionExpectSuccess,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
@@ -34,13 +35,13 @@
       const alice = privateKey('//Alice');
       const bob = privateKey('//Bob');
 
-      const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collection =await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.owner.toString()).to.be.deep.eq(alice.address);
 
       const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
       await submitTransactionAsync(alice, changeOwnerTx);
 
-      const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
       expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);
     });
   });
@@ -53,7 +54,7 @@
       const alice = privateKey('//Alice');
       const bob = privateKey('//Bob');
 
-      const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.owner.toString()).to.be.deep.eq(alice.address);
 
       const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
@@ -62,7 +63,7 @@
       const badChangeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, alice.address);
       await expect(submitTransactionExpectFailAsync(alice, badChangeOwnerTx)).to.be.rejected;
 
-      const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
       expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);
     });
   });
@@ -74,13 +75,13 @@
       const bob = privateKey('//Bob');
       const charlie = privateKey('//Charlie');
 
-      const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.owner.toString()).to.be.deep.eq(alice.address);
 
       const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
       await submitTransactionAsync(alice, changeOwnerTx);
 
-      const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
       expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);
 
       // After changing the owner of the collection, all privileged methods are available to the new owner
@@ -118,20 +119,20 @@
       const bob = privateKey('//Bob');
       const charlie = privateKey('//Charlie');
 
-      const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.owner.toString()).to.be.deep.eq(alice.address);
 
       const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
       await submitTransactionAsync(alice, changeOwnerTx);
 
-      const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
       expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);
 
       const changeOwnerTx2 = api.tx.nft.changeCollectionOwner(collectionId, charlie.address);
       await submitTransactionAsync(bob, changeOwnerTx2);
 
       // ownership lost
-      const collectionAfterOwnerChange2 = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collectionAfterOwnerChange2 = await queryCollectionExpectSuccess(api, collectionId);
       expect(collectionAfterOwnerChange2.owner.toString()).to.be.deep.eq(charlie.address);
     });
   });
@@ -147,7 +148,7 @@
       const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
       await expect(submitTransactionExpectFailAsync(bob, changeOwnerTx)).to.be.rejected;
 
-      const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
       expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(alice.address);
 
       // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
@@ -166,7 +167,7 @@
       const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
       await expect(submitTransactionExpectFailAsync(bob, changeOwnerTx)).to.be.rejected;
 
-      const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
       expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(alice.address);
 
       // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
@@ -195,7 +196,7 @@
       const bob = privateKey('//Bob');
       const charlie = privateKey('//Charlie');
 
-      const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.owner.toString()).to.be.deep.eq(alice.address);
 
       const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
@@ -204,7 +205,7 @@
       const badChangeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, alice.address);
       await expect(submitTransactionExpectFailAsync(alice, badChangeOwnerTx)).to.be.rejected;
 
-      const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
       expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);
 
       await setCollectionSponsorExpectFailure(collectionId, charlie.address, '//Alice');
modifiedtests/src/confirmSponsorship.test.tsdiffbeforeafterboth
--- a/tests/src/confirmSponsorship.test.ts
+++ b/tests/src/confirmSponsorship.test.ts
@@ -20,6 +20,7 @@
   addToAllowListExpectSuccess,
   normalizeAccountId,
   addCollectionAdminExpectSuccess,
+  getCreatedCollectionCount,
 } from './util/helpers';
 import {Keyring} from '@polkadot/api';
 import {IKeyringPair} from '@polkadot/types/types';
@@ -335,7 +336,7 @@
     // Find the collection that never existed
     let collectionId = 0;
     await usingApi(async (api) => {
-      collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+      collectionId = await getCreatedCollectionCount(api) + 1;
     });
 
     await confirmSponsorshipExpectFailure(collectionId, '//Bob');
modifiedtests/src/contracts.test.tsdiffbeforeafterboth
--- a/tests/src/contracts.test.ts
+++ b/tests/src/contracts.test.ts
@@ -228,7 +228,7 @@
       const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, contract.address);
       await submitTransactionAsync(alice, changeAdminTx);
 
-      expect(await isAllowlisted(collectionId, bob.address)).to.be.false;
+      expect(await isAllowlisted(api, collectionId, bob.address)).to.be.false;
 
       {
         const transferTx = contract.tx.toggleAllowList(value, gasLimit, collectionId, bob.address, true);
@@ -236,7 +236,7 @@
         const result = getGenericResult(events);
         expect(result.success).to.be.true;
 
-        expect(await isAllowlisted(collectionId, bob.address)).to.be.true;
+        expect(await isAllowlisted(api, collectionId, bob.address)).to.be.true;
       }
       {
         const transferTx = contract.tx.toggleAllowList(value, gasLimit, collectionId, bob.address, false);
@@ -244,7 +244,7 @@
         const result = getGenericResult(events);
         expect(result.success).to.be.true;
 
-        expect(await isAllowlisted(collectionId, bob.address)).to.be.false;
+        expect(await isAllowlisted(api, collectionId, bob.address)).to.be.false;
       }
     });
   });
modifiedtests/src/createMultipleItems.test.tsdiffbeforeafterboth
--- a/tests/src/createMultipleItems.test.ts
+++ b/tests/src/createMultipleItems.test.ts
@@ -20,6 +20,7 @@
   getLastTokenId,
   getVariableMetadata,
   getConstMetadata,
+  getCreatedCollectionCount,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
@@ -273,7 +274,7 @@
 
   it('Create token in not existing collection', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+      const collectionId = await getCreatedCollectionCount(api) + 1;
       const createMultipleItemsTx = api.tx.nft
         .createMultipleItems(collectionId, normalizeAccountId(alice.address), ['NFT', 'NFT', 'NFT']);
       await expect(submitTransactionExpectFailAsync(alice, createMultipleItemsTx)).to.be.rejected;
modifiedtests/src/destroyCollection.test.tsdiffbeforeafterboth
--- a/tests/src/destroyCollection.test.ts
+++ b/tests/src/destroyCollection.test.ts
@@ -13,6 +13,7 @@
   destroyCollectionExpectFailure,
   setCollectionLimitsExpectSuccess,
   addCollectionAdminExpectSuccess,
+  getCreatedCollectionCount,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
@@ -46,7 +47,7 @@
   it('(!negative test!) Destroy a collection that never existed', async () => {
     await usingApi(async (api) => {
       // Find the collection that never existed
-      const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+      const collectionId = await getCreatedCollectionCount(api) + 1;
       await destroyCollectionExpectFailure(collectionId);
     });
   });
modifiedtests/src/interfaces/augment-api-rpc.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-rpc.ts
+++ b/tests/src/interfaces/augment-api-rpc.ts
@@ -1,7 +1,7 @@
 // Auto-generated via `yarn polkadot-types-from-chain`, do not edit
 /* eslint-disable */
 
-import type { NftDataStructsCollectionId, NftDataStructsTokenId, PalletCommonAccountBasicCrossAccountIdRepr } from './nft';
+import type { NftDataStructsCollection, NftDataStructsCollectionId, NftDataStructsCollectionStats, NftDataStructsTokenId, PalletCommonAccountBasicCrossAccountIdRepr } from './nft';
 import type { Bytes, HashMap, Json, Metadata, Null, Option, StorageKey, Text, U256, U64, Vec, bool, u128, u32, u64 } from '@polkadot/types';
 import type { ExtrinsicOrHash, ExtrinsicStatus } from '@polkadot/types/interfaces/author';
 import type { EpochAuthorship } from '@polkadot/types/interfaces/babe';
@@ -373,6 +373,10 @@
        **/
       allowance: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, sender: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, spender: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, tokenId: NftDataStructsTokenId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;
       /**
+       * Check if user is allowed to use collection
+       **/
+      allowed: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, account: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<bool>>;
+      /**
        * Get allowlist
        **/
       allowlist: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Vec<PalletCommonAccountBasicCrossAccountIdRepr>>>;
@@ -381,6 +385,14 @@
        **/
       balance: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, account: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, tokenId: NftDataStructsTokenId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;
       /**
+       * Get collection by specified id
+       **/
+      collectionById: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Option<NftDataStructsCollection>>>;
+      /**
+       * Get collection stats
+       **/
+      collectionStats: AugmentedRpc<(at?: Hash | string | Uint8Array) => Observable<NftDataStructsCollectionStats>>;
+      /**
        * Get tokens contained in collection
        **/
       collectionTokens: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Vec<NftDataStructsTokenId>>>;
modifiedtests/src/interfaces/augment-types.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-types.ts
+++ b/tests/src/interfaces/augment-types.ts
@@ -2,7 +2,7 @@
 /* eslint-disable */
 
 import type { EthereumBlock, EthereumLog, EthereumReceipt, EthereumTransactionLegacyTransaction, EvmCoreErrorExitReason, FpRpcTransactionStatus } from './ethereum';
-import type { NftDataStructsAccessMode, NftDataStructsCollection, NftDataStructsCollectionId, NftDataStructsCollectionLimits, NftDataStructsCollectionMode, NftDataStructsCreateItemData, NftDataStructsMetaUpdatePermission, NftDataStructsSchemaVersion, NftDataStructsSponsorshipState, NftDataStructsTokenId, PalletCommonAccountBasicCrossAccountIdRepr, PalletNonfungibleItemData, PalletRefungibleItemData, PalletUnqSchedulerCallSpec, PalletUnqSchedulerReleases, PalletUnqSchedulerScheduledV2 } from './nft';
+import type { NftDataStructsAccessMode, NftDataStructsCollection, NftDataStructsCollectionId, NftDataStructsCollectionLimits, NftDataStructsCollectionMode, NftDataStructsCollectionStats, NftDataStructsCreateItemData, NftDataStructsMetaUpdatePermission, NftDataStructsSchemaVersion, NftDataStructsSponsorshipState, NftDataStructsTokenId, PalletCommonAccountBasicCrossAccountIdRepr, PalletNonfungibleItemData, PalletRefungibleItemData, PalletUnqSchedulerCallSpec, PalletUnqSchedulerReleases, PalletUnqSchedulerScheduledV2 } from './nft';
 import type { CumulusPalletDmpQueueConfigData, CumulusPalletDmpQueuePageIndexData, CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot, CumulusPalletXcmpQueueInboundStatus, CumulusPalletXcmpQueueOutboundStatus, CumulusPalletXcmpQueueQueueConfigData, CumulusPrimitivesParachainInherentParachainInherentData, PolkadotParachainPrimitivesXcmpMessageFormat, PolkadotPrimitivesV1AbridgedHostConfiguration, PolkadotPrimitivesV1PersistedValidationData } from './polkadot';
 import type { BitVec, Bool, Bytes, Data, I128, I16, I256, I32, I64, I8, Json, Null, Raw, StorageKey, Text, Type, U128, U16, U256, U32, U64, U8, USize, bool, i128, i16, i256, i32, i64, i8, u128, u16, u256, u32, u64, u8, usize } from '@polkadot/types';
 import type { AssetApproval, AssetApprovalKey, AssetBalance, AssetDestroyWitness, AssetDetails, AssetMetadata, TAssetBalance, TAssetDepositBalance } from '@polkadot/types/interfaces/assets';
@@ -627,6 +627,7 @@
     NftDataStructsCollectionId: NftDataStructsCollectionId;
     NftDataStructsCollectionLimits: NftDataStructsCollectionLimits;
     NftDataStructsCollectionMode: NftDataStructsCollectionMode;
+    NftDataStructsCollectionStats: NftDataStructsCollectionStats;
     NftDataStructsCreateItemData: NftDataStructsCreateItemData;
     NftDataStructsMetaUpdatePermission: NftDataStructsMetaUpdatePermission;
     NftDataStructsSchemaVersion: NftDataStructsSchemaVersion;
modifiedtests/src/interfaces/nft/definitions.tsdiffbeforeafterboth
--- a/tests/src/interfaces/nft/definitions.ts
+++ b/tests/src/interfaces/nft/definitions.ts
@@ -40,6 +40,9 @@
     constMetadata: fun('Get token constant metadata', [collectionParam, tokenParam], 'Vec<u8>'),
     variableMetadata: fun('Get token variable metadata', [collectionParam, tokenParam], 'Vec<u8>'),
     tokenExists: fun('Check if token exists', [collectionParam, tokenParam], 'bool'),
+    collectionById: fun('Get collection by specified id', [collectionParam], 'Option<NftDataStructsCollection>'),
+    collectionStats: fun('Get collection stats', [], 'NftDataStructsCollectionStats'),
+    allowed: fun('Check if user is allowed to use collection', [collectionParam, crossAccountParam()], 'bool'),
   },
   types: {
     PalletCommonAccountBasicCrossAccountIdRepr: {
@@ -64,6 +67,11 @@
       constOnChainSchema: 'Vec<u8>',
       metaUpdatePermission: 'NftDataStructsMetaUpdatePermission',
     },
+    NftDataStructsCollectionStats: {
+      created: 'u32',
+      destroyed: 'u32',
+      alive: 'u32',
+    },
     NftDataStructsCollectionId: 'u32',
     NftDataStructsTokenId: 'u32',
     PalletNonfungibleItemData: mkDummy('NftItemData'),
modifiedtests/src/interfaces/nft/types.tsdiffbeforeafterboth
--- a/tests/src/interfaces/nft/types.ts
+++ b/tests/src/interfaces/nft/types.ts
@@ -48,6 +48,13 @@
   readonly dummyCollectionMode: u32;
 }
 
+/** @name NftDataStructsCollectionStats */
+export interface NftDataStructsCollectionStats extends Struct {
+  readonly created: u32;
+  readonly destroyed: u32;
+  readonly alive: u32;
+}
+
 /** @name NftDataStructsCreateItemData */
 export interface NftDataStructsCreateItemData extends Struct {
   readonly dummyCreateItemData: u32;
modifiedtests/src/removeCollectionAdmin.test.tsdiffbeforeafterboth
--- a/tests/src/removeCollectionAdmin.test.ts
+++ b/tests/src/removeCollectionAdmin.test.ts
@@ -8,7 +8,7 @@
 import chaiAsPromised from 'chai-as-promised';
 import privateKey from './substrate/privateKey';
 import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId} from './util/helpers';
+import {createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId, queryCollectionExpectSuccess} from './util/helpers';
 
 chai.use(chaiAsPromised);
 const expect = chai.expect;
@@ -19,7 +19,7 @@
       const collectionId = await createCollectionExpectSuccess();
       const alice = privateKey('//Alice');
       const bob = privateKey('//Bob');
-      const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.owner.toString()).to.be.deep.eq(alice.address);
       // first - add collection admin Bob
       const addAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
@@ -43,7 +43,7 @@
       const alice = privateKey('//Alice');
       const bob = privateKey('//Bob');
       const charlie = privateKey('//Charlie');
-      const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.owner.toString()).to.be.eq(alice.address);
       // first - add collection admin Bob
       const addAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
modifiedtests/src/removeCollectionSponsor.test.tsdiffbeforeafterboth
--- a/tests/src/removeCollectionSponsor.test.ts
+++ b/tests/src/removeCollectionSponsor.test.ts
@@ -18,6 +18,7 @@
   removeCollectionSponsorExpectFailure,
   normalizeAccountId,
   addCollectionAdminExpectSuccess,
+  getCreatedCollectionCount,
 } from './util/helpers';
 import {Keyring} from '@polkadot/api';
 import {IKeyringPair} from '@polkadot/types/types';
@@ -98,7 +99,7 @@
     // Find the collection that never existed
     let collectionId = 0;
     await usingApi(async (api) => {
-      collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+      collectionId = await getCreatedCollectionCount(api) + 1;
     });
 
     await removeCollectionSponsorExpectFailure(collectionId);
modifiedtests/src/removeFromAllowList.test.tsdiffbeforeafterboth
--- a/tests/src/removeFromAllowList.test.ts
+++ b/tests/src/removeFromAllowList.test.ts
@@ -37,13 +37,13 @@
   });
 
   it('ensure bob is not in allowlist after removal', async () => {
-    await usingApi(async () => {
+    await usingApi(async api => {
       const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
       await enableAllowListExpectSuccess(alice, collectionId);
       await addToAllowListExpectSuccess(alice, collectionId, bob.address);
 
       await removeFromAllowListExpectSuccess(alice, collectionId, normalizeAccountId(bob.address));
-      expect(await isAllowlisted(collectionId, bob.address)).to.be.false;
+      expect(await isAllowlisted(api, collectionId, bob.address)).to.be.false;
     });
   });
 
@@ -104,13 +104,13 @@
   });
 
   it('ensure address is not in allowlist after removal', async () => {
-    await usingApi(async () => {
+    await usingApi(async api => {
       const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
       await enableAllowListExpectSuccess(alice, collectionId);
       await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
       await addToAllowListExpectSuccess(alice, collectionId, charlie.address);
       await removeFromAllowListExpectSuccess(bob, collectionId, normalizeAccountId(charlie.address));
-      expect(await isAllowlisted(collectionId, charlie.address)).to.be.false;
+      expect(await isAllowlisted(api, collectionId, charlie.address)).to.be.false;
     });
   });
 
modifiedtests/src/setCollectionSponsor.test.tsdiffbeforeafterboth
--- a/tests/src/setCollectionSponsor.test.ts
+++ b/tests/src/setCollectionSponsor.test.ts
@@ -11,6 +11,7 @@
   destroyCollectionExpectSuccess,
   setCollectionSponsorExpectFailure,
   addCollectionAdminExpectSuccess,
+  getCreatedCollectionCount,
 } from './util/helpers';
 import {Keyring} from '@polkadot/api';
 import {IKeyringPair} from '@polkadot/types/types';
@@ -77,7 +78,7 @@
     // Find the collection that never existed
     let collectionId = 0;
     await usingApi(async (api) => {
-      collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+      collectionId = await getCreatedCollectionCount(api) + 1;
     });
 
     await setCollectionSponsorExpectFailure(collectionId, bob.address);
modifiedtests/src/setConstOnChainSchema.test.tsdiffbeforeafterboth
--- a/tests/src/setConstOnChainSchema.test.ts
+++ b/tests/src/setConstOnChainSchema.test.ts
@@ -12,6 +12,8 @@
   createCollectionExpectSuccess,
   destroyCollectionExpectSuccess,
   addCollectionAdminExpectSuccess,
+  queryCollectionExpectSuccess,
+  getCreatedCollectionCount,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
@@ -37,7 +39,7 @@
   it('Run extrinsic with parameters of the collection id, set the scheme', async () => {
     await usingApi(async (api) => {
       const collectionId = await createCollectionExpectSuccess();
-      const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.owner.toString()).to.be.eq(alice.address);
       const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);
       await submitTransactionAsync(alice, setShema);
@@ -47,7 +49,7 @@
   it('Collection admin can set the scheme', async () => {
     await usingApi(async (api) => {
       const collectionId = await createCollectionExpectSuccess();
-      const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.owner.toString()).to.be.eq(alice.address);
       await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
       const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);
@@ -60,7 +62,7 @@
       const collectionId = await createCollectionExpectSuccess();
       const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);
       await submitTransactionAsync(alice, setShema);
-      const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.constOnChainSchema.toString()).to.be.eq(shema);
     });
   });
@@ -71,7 +73,7 @@
   it('Set a non-existent collection', async () => {
     await usingApi(async (api) => {
       // tslint:disable-next-line: radix
-      const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+      const collectionId = await getCreatedCollectionCount(api) + 1;
       const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);
       await expect(submitTransactionExpectFailAsync(alice, setShema)).to.be.rejected;
     });
@@ -97,7 +99,7 @@
   it('Execute method not on behalf of the collection owner', async () => {
     await usingApi(async (api) => {
       const collectionId = await createCollectionExpectSuccess();
-      const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.owner.toString()).to.be.eq(alice.address);
       const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);
       await expect(submitTransactionExpectFailAsync(bob, setShema)).to.be.rejected;
modifiedtests/src/setPublicAccessMode.test.tsdiffbeforeafterboth
--- a/tests/src/setPublicAccessMode.test.ts
+++ b/tests/src/setPublicAccessMode.test.ts
@@ -19,6 +19,7 @@
   enableAllowListExpectSuccess,
   normalizeAccountId,
   addCollectionAdminExpectSuccess,
+  getCreatedCollectionCount,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
@@ -60,7 +61,7 @@
   it('Set a non-existent collection', async () => {
     await usingApi(async (api: ApiPromise) => {
       // tslint:disable-next-line: radix
-      const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+      const collectionId = await getCreatedCollectionCount(api) + 1;
       const tx = api.tx.nft.setPublicAccessMode(collectionId, 'AllowList');
       await expect(submitTransactionExpectFailAsync(alice, tx)).to.be.rejected;
     });
modifiedtests/src/setVariableOnChainSchema.test.tsdiffbeforeafterboth
--- a/tests/src/setVariableOnChainSchema.test.ts
+++ b/tests/src/setVariableOnChainSchema.test.ts
@@ -12,6 +12,8 @@
   createCollectionExpectSuccess,
   destroyCollectionExpectSuccess,
   addCollectionAdminExpectSuccess,
+  queryCollectionExpectSuccess,
+  getCreatedCollectionCount,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
@@ -37,7 +39,7 @@
   it('Run extrinsic with parameters of the collection id, set the scheme', async () => {
     await usingApi(async (api) => {
       const collectionId = await createCollectionExpectSuccess();
-      const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.owner.toString()).to.be.eq(alice.address);
       const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
       await submitTransactionAsync(alice, setSchema);
@@ -49,7 +51,7 @@
       const collectionId = await createCollectionExpectSuccess();
       const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
       await submitTransactionAsync(alice, setSchema);
-      const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.variableOnChainSchema.toString()).to.be.eq(schema);
 
     });
@@ -61,7 +63,7 @@
   it('Run extrinsic with parameters of the collection id, set the scheme', async () => {
     await usingApi(async (api) => {
       const collectionId = await createCollectionExpectSuccess();
-      const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.owner.toString()).to.be.eq(alice.address);
       await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
       const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
@@ -75,7 +77,7 @@
       await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
       const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
       await submitTransactionAsync(bob, setSchema);
-      const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.variableOnChainSchema.toString()).to.be.eq(schema);
 
     });
@@ -87,7 +89,7 @@
   it('Set a non-existent collection', async () => {
     await usingApi(async (api) => {
       // tslint:disable-next-line: radix
-      const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+      const collectionId = await getCreatedCollectionCount(api) + 1;
       const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
       await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;
     });
@@ -113,7 +115,7 @@
   it('Execute method not on behalf of the collection owner', async () => {
     await usingApi(async (api) => {
       const collectionId = await createCollectionExpectSuccess();
-      const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+      const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.owner.toString()).to.be.eq(alice.address);
       const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
       await expect(submitTransactionExpectFailAsync(bob, setSchema)).to.be.rejected;
modifiedtests/src/transfer.test.tsdiffbeforeafterboth
--- a/tests/src/transfer.test.ts
+++ b/tests/src/transfer.test.ts
@@ -19,6 +19,7 @@
   transferExpectFailure,
   transferExpectSuccess,
   addCollectionAdminExpectSuccess,
+  getCreatedCollectionCount,
 } from './util/helpers';
 
 let alice: IKeyringPair;
@@ -132,13 +133,13 @@
   it('Transfer with not existed collection_id', async () => {
     await usingApi(async (api) => {
       // nft
-      const nftCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+      const nftCollectionCount = await getCreatedCollectionCount(api);
       await transferExpectFailure(nftCollectionCount + 1, 1, alice, bob, 1);
       // fungible
-      const fungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+      const fungibleCollectionCount = await getCreatedCollectionCount(api);
       await transferExpectFailure(fungibleCollectionCount + 1, 0, alice, bob, 1);
       // reFungible
-      const reFungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+      const reFungibleCollectionCount = await getCreatedCollectionCount(api);
       await transferExpectFailure(reFungibleCollectionCount + 1, 1, alice, bob, 1);
     });
   });
modifiedtests/src/transferFrom.test.tsdiffbeforeafterboth
--- a/tests/src/transferFrom.test.ts
+++ b/tests/src/transferFrom.test.ts
@@ -19,6 +19,7 @@
   transferFromExpectSuccess,
   burnItemExpectSuccess,
   setCollectionLimitsExpectSuccess,
+  getCreatedCollectionCount,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
@@ -109,18 +110,18 @@
   it('transferFrom for a collection that does not exist', async () => {
     await usingApi(async (api: ApiPromise) => {
       // nft
-      const nftCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+      const nftCollectionCount = await getCreatedCollectionCount(api);
       await approveExpectFail(nftCollectionCount + 1, 1, alice, bob);
 
       await transferFromExpectFail(nftCollectionCount + 1, 1, bob, alice, charlie, 1);
 
       // fungible
-      const fungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+      const fungibleCollectionCount = await getCreatedCollectionCount(api);
       await approveExpectFail(fungibleCollectionCount + 1, 0, alice, bob);
 
       await transferFromExpectFail(fungibleCollectionCount + 1, 0, bob, alice, charlie, 1);
       // reFungible
-      const reFungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+      const reFungibleCollectionCount = await getCreatedCollectionCount(api);
       await approveExpectFail(reFungibleCollectionCount + 1, 1, alice, bob);
 
       await transferFromExpectFail(reFungibleCollectionCount + 1, 1, bob, alice, charlie, 1);
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -269,7 +269,7 @@
   let collectionId = 0;
   await usingApi(async (api) => {
     // Get number of collections before the transaction
-    const collectionCountBefore = (await api.query.common.createdCollectionCount()).toNumber();
+    const collectionCountBefore = await getCreatedCollectionCount(api);
 
     // Run the CreateCollection transaction
     const alicePrivateKey = privateKey('//Alice');
@@ -288,10 +288,10 @@
     const result = getCreateCollectionResult(events);
 
     // Get number of collections after the transaction
-    const collectionCountAfter = (await api.query.common.createdCollectionCount()).toNumber();
+    const collectionCountAfter = await getCreatedCollectionCount(api);
 
     // Get the collection
-    const collection = (await api.query.common.collectionById(result.collectionId)).unwrap();
+    const collection = await queryCollectionExpectSuccess(api, result.collectionId);
 
     // What to expect
     // tslint:disable-next-line:no-unused-expression
@@ -325,7 +325,7 @@
 
   await usingApi(async (api) => {
     // Get number of collections before the transaction
-    const collectionCountBefore = (await api.query.common.createdCollectionCount()).toNumber();
+    const collectionCountBefore = await getCreatedCollectionCount(api);
 
     // Run the CreateCollection transaction
     const alicePrivateKey = privateKey('//Alice');
@@ -334,7 +334,7 @@
     const result = getCreateCollectionResult(events);
 
     // Get number of collections after the transaction
-    const collectionCountAfter = (await api.query.common.createdCollectionCount()).toNumber();
+    const collectionCountAfter = await getCreatedCollectionCount(api);
 
     // What to expect
     // tslint:disable-next-line:no-unused-expression
@@ -364,7 +364,7 @@
 }
 
 export async function findNotExistingCollection(api: ApiPromise): Promise<number> {
-  const totalNumber = (await api.query.common.createdCollectionCount()).toNumber();
+  const totalNumber = await getCreatedCollectionCount(api);
   const newCollection: number = totalNumber + 1;
   return newCollection;
 }
@@ -398,7 +398,7 @@
     expect(result).to.be.true;
 
     // What to expect
-    expect((await api.query.common.collectionById(collectionId)).isNone).to.be.true;
+    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;
   });
 }
 
@@ -432,7 +432,7 @@
     const result = getGenericResult(events);
 
     // Get the collection
-    const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+    const collection = await queryCollectionExpectSuccess(api, collectionId);
 
     // What to expect
     expect(result.success).to.be.true;
@@ -452,7 +452,7 @@
     const result = getGenericResult(events);
 
     // Get the collection
-    const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+    const collection = await queryCollectionExpectSuccess(api, collectionId);
 
     // What to expect
     expect(result.success).to.be.true;
@@ -490,7 +490,7 @@
     const result = getGenericResult(events);
 
     // Get the collection
-    const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+    const collection = await queryCollectionExpectSuccess(api, collectionId);
 
     // What to expect
     expect(result.success).to.be.true;
@@ -1057,7 +1057,7 @@
     const result = getGenericResult(events);
 
     // Get the collection
-    const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+    const collection = await queryCollectionExpectSuccess(api, collectionId);
 
     // What to expect
     // tslint:disable-next-line:no-unused-expression
@@ -1105,7 +1105,7 @@
     expect(result.success).to.be.true;
 
     // Get the collection
-    const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+    const collection = await queryCollectionExpectSuccess(api, collectionId);
 
     expect(collection.mintMode.toHuman()).to.be.equal(enabled);
   });
@@ -1137,15 +1137,13 @@
   });
 }
 
-export async function isAllowlisted(collectionId: number, address: string | CrossAccountId) {
-  return await usingApi(async (api) => {
-    return (await api.query.common.allowlist(collectionId, normalizeAccountId(address))).toJSON();
-  });
+export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {
+  return (await api.rpc.nft.allowed(collectionId, normalizeAccountId(address))).toJSON();
 }
 
 export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {
   await usingApi(async (api) => {
-    expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.false;
+    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;
 
     // Run the transaction
     const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));
@@ -1153,14 +1151,14 @@
     const result = getGenericResult(events);
     expect(result.success).to.be.true;
 
-    expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.true;
+    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
   });
 }
 
 export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {
   await usingApi(async (api) => {
 
-    expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.true;
+    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
 
     // Run the transaction
     const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));
@@ -1168,7 +1166,7 @@
     const result = getGenericResult(events);
     expect(result.success).to.be.true;
 
-    expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.true;
+    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
   });
 }
 
@@ -1214,16 +1212,16 @@
 
 export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)
   : Promise<NftDataStructsCollection | null> => {
-  return (await api.query.common.collectionById(collectionId)).unwrapOr(null);
+  return (await api.rpc.nft.collectionById(collectionId)).unwrapOr(null);
 };
 
 export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {
   // set global object - collectionsCount
-  return (await api.query.common.createdCollectionCount()).toNumber();
+  return (await api.rpc.nft.collectionStats()).created.toNumber();
 };
 
 export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<NftDataStructsCollection> {
-  return (await api.query.common.collectionById(collectionId)).unwrap();
+  return (await api.rpc.nft.collectionById(collectionId)).unwrap();
 }
 
 export async function waitNewBlocks(blocksCount = 1): Promise<void> {