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
before · pallets/refungible/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23use frame_support::{ensure, BoundedVec};4use nft_data_structs::{5	AccessMode, CUSTOM_DATA_LIMIT, Collection, CollectionId, CustomDataLimit,6	MAX_REFUNGIBLE_PIECES, TokenId,7};8use pallet_common::{9	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,10};11use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};12use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};13use core::ops::Deref;14use codec::{Encode, Decode};15use scale_info::TypeInfo;1617pub use pallet::*;18#[cfg(feature = "runtime-benchmarks")]19pub mod benchmarking;20pub mod common;21pub mod erc;22pub mod weights;23pub struct CreateItemData<T: Config> {24	pub const_data: BoundedVec<u8, CustomDataLimit>,25	pub variable_data: BoundedVec<u8, CustomDataLimit>,26	pub users: BTreeMap<T::CrossAccountId, u128>,27}28pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2930#[derive(Encode, Decode, Default, TypeInfo)]31pub struct ItemData {32	pub const_data: Vec<u8>,33	pub variable_data: Vec<u8>,34}3536#[frame_support::pallet]37pub mod pallet {38	use super::*;39	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};40	use nft_data_structs::{CollectionId, TokenId};41	use super::weights::WeightInfo;4243	#[pallet::error]44	pub enum Error<T> {45		/// Not Refungible item data used to mint in Refungible collection.46		NotRefungibleDataUsedToMintFungibleCollectionToken,47		/// Maximum refungibility exceeded48		WrongRefungiblePieces,49	}5051	#[pallet::config]52	pub trait Config: frame_system::Config + pallet_common::Config {53		type WeightInfo: WeightInfo;54	}5556	#[pallet::pallet]57	#[pallet::generate_store(pub(super) trait Store)]58	pub struct Pallet<T>(_);5960	#[pallet::storage]61	pub(super) type TokensMinted<T: Config> =62		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;63	#[pallet::storage]64	pub(super) type TokensBurnt<T: Config> =65		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;6667	#[pallet::storage]68	pub(super) type TokenData<T: Config> = StorageNMap<69		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),70		Value = ItemData,71		QueryKind = ValueQuery,72	>;7374	#[pallet::storage]75	pub(super) type TotalSupply<T: Config> = StorageNMap<76		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),77		Value = u128,78		QueryKind = ValueQuery,79	>;8081	/// Used to enumerate tokens owned by account82	#[pallet::storage]83	pub(super) type Owned<T: Config> = StorageNMap<84		Key = (85			Key<Twox64Concat, CollectionId>,86			Key<Blake2_128Concat, T::CrossAccountId>,87			Key<Twox64Concat, TokenId>,88		),89		Value = bool,90		QueryKind = ValueQuery,91	>;9293	#[pallet::storage]94	pub(super) type AccountBalance<T: Config> = StorageNMap<95		Key = (96			Key<Twox64Concat, CollectionId>,97			// Owner98			Key<Blake2_128Concat, T::CrossAccountId>,99		),100		Value = u32,101		QueryKind = ValueQuery,102	>;103104	#[pallet::storage]105	pub(super) type Balance<T: Config> = StorageNMap<106		Key = (107			Key<Twox64Concat, CollectionId>,108			Key<Twox64Concat, TokenId>,109			// Owner110			Key<Blake2_128Concat, T::CrossAccountId>,111		),112		Value = u128,113		QueryKind = ValueQuery,114	>;115116	#[pallet::storage]117	pub(super) type Allowance<T: Config> = StorageNMap<118		Key = (119			Key<Twox64Concat, CollectionId>,120			Key<Twox64Concat, TokenId>,121			// Owner122			Key<Blake2_128, T::CrossAccountId>,123			// Spender124			Key<Blake2_128Concat, T::CrossAccountId>,125		),126		Value = u128,127		QueryKind = ValueQuery,128	>;129}130131pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);132impl<T: Config> RefungibleHandle<T> {133	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {134		Self(inner)135	}136	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {137		self.0138	}139}140impl<T: Config> Deref for RefungibleHandle<T> {141	type Target = pallet_common::CollectionHandle<T>;142143	fn deref(&self) -> &Self::Target {144		&self.0145	}146}147148impl<T: Config> Pallet<T> {149	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {150		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)151	}152	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {153		<TotalSupply<T>>::contains_key((collection.id, token))154	}155}156157// unchecked calls skips any permission checks158impl<T: Config> Pallet<T> {159	pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {160		PalletCommon::init_collection(data)161	}162	pub fn destroy_collection(163		collection: RefungibleHandle<T>,164		sender: &T::CrossAccountId,165	) -> DispatchResult {166		let id = collection.id;167168		// =========169170		PalletCommon::destroy_collection(collection.0, sender)?;171172		<TokensMinted<T>>::remove(id);173		<TokensBurnt<T>>::remove(id);174		<TokenData<T>>::remove_prefix((id,), None);175		<TotalSupply<T>>::remove_prefix((id,), None);176		<Balance<T>>::remove_prefix((id,), None);177		<Allowance<T>>::remove_prefix((id,), None);178		Ok(())179	}180181	pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {182		let burnt = <TokensBurnt<T>>::get(collection.id)183			.checked_add(1)184			.ok_or(ArithmeticError::Overflow)?;185186		<TokensBurnt<T>>::insert(collection.id, burnt);187		<TokenData<T>>::remove((collection.id, token_id));188		<TotalSupply<T>>::remove((collection.id, token_id));189		<Balance<T>>::remove_prefix((collection.id, token_id), None);190		<Allowance<T>>::remove_prefix((collection.id, token_id), None);191		// TODO: ERC721 transfer event192		return Ok(());193	}194195	pub fn burn(196		collection: &RefungibleHandle<T>,197		owner: &T::CrossAccountId,198		token: TokenId,199		amount: u128,200	) -> DispatchResult {201		let total_supply = <TotalSupply<T>>::get((collection.id, token))202			.checked_sub(amount)203			.ok_or(<CommonError<T>>::TokenValueTooLow)?;204205		// This was probally last owner of this token?206		if total_supply == 0 {207			// Ensure user actually owns this amount208			ensure!(209				<Balance<T>>::get((collection.id, token, owner)) == amount,210				<CommonError<T>>::TokenValueTooLow211			);212			let account_balance = <AccountBalance<T>>::get((collection.id, owner))213				.checked_sub(1)214				// Should not occur215				.ok_or(ArithmeticError::Underflow)?;216217			// =========218219			<Owned<T>>::remove((collection.id, owner, token));220			<AccountBalance<T>>::insert((collection.id, owner), account_balance);221			Self::burn_token(collection, token)?;222			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(223				collection.id,224				token,225				owner.clone(),226				amount,227			));228			return Ok(());229		}230231		let balance = <Balance<T>>::get((collection.id, token, owner))232			.checked_sub(amount)233			.ok_or(<CommonError<T>>::TokenValueTooLow)?;234		let account_balance = if balance == 0 {235			<AccountBalance<T>>::get((collection.id, owner))236				.checked_sub(1)237				// Should not occur238				.ok_or(ArithmeticError::Underflow)?239		} else {240			0241		};242243		// =========244245		if balance == 0 {246			<Owned<T>>::remove((collection.id, owner, token));247			<Balance<T>>::remove((collection.id, token, owner));248			<AccountBalance<T>>::insert((collection.id, owner), account_balance);249		} else {250			<Balance<T>>::insert((collection.id, token, owner), balance);251		}252		<TotalSupply<T>>::insert((collection.id, token), total_supply);253		// TODO: ERC20 transfer event254		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(255			collection.id,256			token,257			owner.clone(),258			amount,259		));260		Ok(())261	}262263	pub fn transfer(264		collection: &RefungibleHandle<T>,265		from: &T::CrossAccountId,266		to: &T::CrossAccountId,267		token: TokenId,268		amount: u128,269	) -> DispatchResult {270		ensure!(271			collection.limits.transfers_enabled(),272			<CommonError<T>>::TransferNotAllowed273		);274275		if collection.access == AccessMode::AllowList {276			collection.check_allowlist(from)?;277			collection.check_allowlist(to)?;278		}279		<PalletCommon<T>>::ensure_correct_receiver(to)?;280281		let balance_from = <Balance<T>>::get((collection.id, token, from))282			.checked_sub(amount)283			.ok_or(<CommonError<T>>::TokenValueTooLow)?;284		let mut create_target = false;285		let from_to_differ = from != to;286		let balance_to = if from != to {287			let old_balance = <Balance<T>>::get((collection.id, token, to));288			if old_balance == 0 {289				create_target = true;290			}291			Some(292				old_balance293					.checked_add(amount)294					.ok_or(ArithmeticError::Overflow)?,295			)296		} else {297			None298		};299300		let account_balance_from = if balance_from == 0 {301			Some(302				<AccountBalance<T>>::get((collection.id, from))303					.checked_sub(1)304					// Should not occur305					.ok_or(ArithmeticError::Underflow)?,306			)307		} else {308			None309		};310		// Account data is created in token, AccountBalance should be increased311		// But only if from != to as we shouldn't check overflow in this case312		let account_balance_to = if create_target && from_to_differ {313			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))314				.checked_add(1)315				.ok_or(ArithmeticError::Overflow)?;316			ensure!(317				account_balance_to < collection.limits.account_token_ownership_limit(),318				<CommonError<T>>::AccountTokenLimitExceeded,319			);320321			Some(account_balance_to)322		} else {323			None324		};325326		// =========327328		if let Some(balance_to) = balance_to {329			// from != to330			if balance_from == 0 {331				<Balance<T>>::remove((collection.id, token, from));332			} else {333				<Balance<T>>::insert((collection.id, token, from), balance_from);334			}335			<Balance<T>>::insert((collection.id, token, to), balance_to);336			if let Some(account_balance_from) = account_balance_from {337				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);338				<Owned<T>>::remove((collection.id, from, token));339			}340			if let Some(account_balance_to) = account_balance_to {341				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);342				<Owned<T>>::insert((collection.id, to, token), true);343			}344		}345346		// TODO: ERC20 transfer event347		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(348			collection.id,349			token,350			from.clone(),351			to.clone(),352			amount,353		));354		Ok(())355	}356357	pub fn create_multiple_items(358		collection: &RefungibleHandle<T>,359		sender: &T::CrossAccountId,360		data: Vec<CreateItemData<T>>,361	) -> DispatchResult {362		let unrestricted_minting = collection.is_owner_or_admin(sender)?;363		if !unrestricted_minting {364			ensure!(365				collection.mint_mode,366				<CommonError<T>>::PublicMintingNotAllowed367			);368			collection.check_allowlist(sender)?;369370			for item in data.iter() {371				for (user, _) in &item.users {372					collection.check_allowlist(&user)?;373				}374			}375		}376377		for item in data.iter() {378			for (owner, _) in item.users.iter() {379				<PalletCommon<T>>::ensure_correct_receiver(owner)?;380			}381		}382383		// Total pieces per tokens384		let totals = data385			.iter()386			.map(|data| {387				Ok(data388					.users389					.iter()390					.map(|u| u.1)391					.try_fold(0u128, |acc, v| acc.checked_add(*v))392					.ok_or(ArithmeticError::Overflow)?)393			})394			.collect::<Result<Vec<_>, DispatchError>>()?;395		for total in &totals {396			ensure!(397				*total <= MAX_REFUNGIBLE_PIECES,398				<Error<T>>::WrongRefungiblePieces399			);400		}401402		let first_token_id = <TokensMinted<T>>::get(collection.id);403		let tokens_minted = first_token_id404			.checked_add(data.len() as u32)405			.ok_or(ArithmeticError::Overflow)?;406		ensure!(407			tokens_minted < collection.limits.token_limit(),408			<CommonError<T>>::CollectionTokenLimitExceeded409		);410411		let mut balances = BTreeMap::new();412		for data in &data {413			for (owner, _) in &data.users {414				let balance = balances415					.entry(owner)416					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));417				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;418419				ensure!(420					*balance <= collection.limits.account_token_ownership_limit(),421					<CommonError<T>>::AccountTokenLimitExceeded,422				);423			}424		}425426		// =========427428		<TokensMinted<T>>::insert(collection.id, tokens_minted);429		for (account, balance) in balances {430			<AccountBalance<T>>::insert((collection.id, account), balance);431		}432		for (i, token) in data.into_iter().enumerate() {433			let token_id = first_token_id + i as u32 + 1;434			<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);435436			<TokenData<T>>::insert(437				(collection.id, token_id),438				ItemData {439					const_data: token.const_data.into(),440					variable_data: token.variable_data.into(),441				},442			);443			for (user, amount) in token.users.into_iter() {444				if amount == 0 {445					continue;446				}447				<Balance<T>>::insert((collection.id, token_id, &user), amount);448				<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);449				// TODO: ERC20 transfer event450				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(451					collection.id,452					TokenId(token_id),453					user,454					amount,455				));456			}457		}458		Ok(())459	}460461	pub fn set_allowance_unchecked(462		collection: &RefungibleHandle<T>,463		sender: &T::CrossAccountId,464		spender: &T::CrossAccountId,465		token: TokenId,466		amount: u128,467	) {468		<Allowance<T>>::insert((collection.id, token, sender, spender), amount);469		// TODO: ERC20 approval event470		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(471			collection.id,472			token,473			sender.clone(),474			spender.clone(),475			amount,476		))477	}478479	pub fn set_allowance(480		collection: &RefungibleHandle<T>,481		sender: &T::CrossAccountId,482		spender: &T::CrossAccountId,483		token: TokenId,484		amount: u128,485	) -> DispatchResult {486		if collection.access == AccessMode::AllowList {487			collection.check_allowlist(&sender)?;488			collection.check_allowlist(&spender)?;489		}490491		<PalletCommon<T>>::ensure_correct_receiver(spender)?;492493		if <Balance<T>>::get((collection.id, token, sender)) < amount {494			ensure!(495				collection.ignores_owned_amount(sender)? && Self::token_exists(collection, token),496				<CommonError<T>>::CantApproveMoreThanOwned497			);498		}499500		// =========501502		Self::set_allowance_unchecked(collection, sender, spender, token, amount);503		Ok(())504	}505506	pub fn transfer_from(507		collection: &RefungibleHandle<T>,508		spender: &T::CrossAccountId,509		from: &T::CrossAccountId,510		to: &T::CrossAccountId,511		token: TokenId,512		amount: u128,513	) -> DispatchResult {514		if spender.conv_eq(from) {515			return Self::transfer(collection, from, to, token, amount);516		}517		if collection.access == AccessMode::AllowList {518			// `from`, `to` checked in [`transfer`]519			collection.check_allowlist(spender)?;520		}521522		let allowance =523			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);524		if allowance.is_none() {525			ensure!(526				collection.ignores_allowance(spender)?,527				<CommonError<T>>::TokenValueNotEnough528			);529		}530531		// =========532533		Self::transfer(collection, from, to, token, amount)?;534		if let Some(allowance) = allowance {535			Self::set_allowance_unchecked(collection, from, spender, token, allowance);536		}537		Ok(())538	}539540	pub fn burn_from(541		collection: &RefungibleHandle<T>,542		spender: &T::CrossAccountId,543		from: &T::CrossAccountId,544		token: TokenId,545		amount: u128,546	) -> DispatchResult {547		if spender.conv_eq(from) {548			return Self::burn(collection, from, token, amount);549		}550		if collection.access == AccessMode::AllowList {551			// `from` checked in [`burn`]552			collection.check_allowlist(spender)?;553		}554555		let allowance =556			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);557		if allowance.is_none() {558			ensure!(559				collection.ignores_allowance(spender)?,560				<CommonError<T>>::TokenValueNotEnough561			);562		}563564		// =========565566		Self::burn(collection, from, token, amount)?;567		if let Some(allowance) = allowance {568			Self::set_allowance_unchecked(collection, from, spender, token, allowance);569		}570		Ok(())571	}572573	pub fn set_variable_metadata(574		collection: &RefungibleHandle<T>,575		sender: &T::CrossAccountId,576		token: TokenId,577		data: Vec<u8>,578	) -> DispatchResult {579		ensure!(580			data.len() as u32 <= CUSTOM_DATA_LIMIT,581			<CommonError<T>>::TokenVariableDataLimitExceeded582		);583		collection.check_can_update_meta(584			sender,585			&T::CrossAccountId::from_sub(collection.owner.clone()),586		)?;587588		collection.consume_sstore()?;589		let token_data = <TokenData<T>>::get((collection.id, token));590591		// =========592593		<TokenData<T>>::insert(594			(collection.id, token),595			ItemData {596				variable_data: data,597				..token_data598			},599		);600		Ok(())601	}602603	/// Delegated to `create_multiple_items`604	pub fn create_item(605		collection: &RefungibleHandle<T>,606		sender: &T::CrossAccountId,607		data: CreateItemData<T>,608	) -> DispatchResult {609		Self::create_multiple_items(collection, sender, vec![data])610	}611}
after · pallets/refungible/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23use frame_support::{ensure, BoundedVec};4use nft_data_structs::{5	AccessMode, CUSTOM_DATA_LIMIT, Collection, CollectionId, CustomDataLimit,6	MAX_REFUNGIBLE_PIECES, TokenId,7};8use pallet_common::{9	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,10};11use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};12use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};13use core::ops::Deref;14use codec::{Encode, Decode};15use scale_info::TypeInfo;1617pub use pallet::*;18#[cfg(feature = "runtime-benchmarks")]19pub mod benchmarking;20pub mod common;21pub mod erc;22pub mod weights;23pub struct CreateItemData<T: Config> {24	pub const_data: BoundedVec<u8, CustomDataLimit>,25	pub variable_data: BoundedVec<u8, CustomDataLimit>,26	pub users: BTreeMap<T::CrossAccountId, u128>,27}28pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2930#[derive(Encode, Decode, Default, TypeInfo)]31pub struct ItemData {32	pub const_data: Vec<u8>,33	pub variable_data: Vec<u8>,34}3536#[frame_support::pallet]37pub mod pallet {38	use super::*;39	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};40	use nft_data_structs::{CollectionId, TokenId};41	use super::weights::WeightInfo;4243	#[pallet::error]44	pub enum Error<T> {45		/// Not Refungible item data used to mint in Refungible collection.46		NotRefungibleDataUsedToMintFungibleCollectionToken,47		/// Maximum refungibility exceeded48		WrongRefungiblePieces,49	}5051	#[pallet::config]52	pub trait Config: frame_system::Config + pallet_common::Config {53		type WeightInfo: WeightInfo;54	}5556	#[pallet::pallet]57	#[pallet::generate_store(pub(super) trait Store)]58	pub struct Pallet<T>(_);5960	#[pallet::storage]61	pub(super) type TokensMinted<T: Config> =62		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;63	#[pallet::storage]64	pub(super) type TokensBurnt<T: Config> =65		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;6667	#[pallet::storage]68	pub(super) type TokenData<T: Config> = StorageNMap<69		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),70		Value = ItemData,71		QueryKind = ValueQuery,72	>;7374	#[pallet::storage]75	pub(super) type TotalSupply<T: Config> = StorageNMap<76		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),77		Value = u128,78		QueryKind = ValueQuery,79	>;8081	/// Used to enumerate tokens owned by account82	#[pallet::storage]83	pub(super) type Owned<T: Config> = StorageNMap<84		Key = (85			Key<Twox64Concat, CollectionId>,86			Key<Blake2_128Concat, T::CrossAccountId>,87			Key<Twox64Concat, TokenId>,88		),89		Value = bool,90		QueryKind = ValueQuery,91	>;9293	#[pallet::storage]94	pub(super) type AccountBalance<T: Config> = StorageNMap<95		Key = (96			Key<Twox64Concat, CollectionId>,97			// Owner98			Key<Blake2_128Concat, T::CrossAccountId>,99		),100		Value = u32,101		QueryKind = ValueQuery,102	>;103104	#[pallet::storage]105	pub(super) type Balance<T: Config> = StorageNMap<106		Key = (107			Key<Twox64Concat, CollectionId>,108			Key<Twox64Concat, TokenId>,109			// Owner110			Key<Blake2_128Concat, T::CrossAccountId>,111		),112		Value = u128,113		QueryKind = ValueQuery,114	>;115116	#[pallet::storage]117	pub(super) type Allowance<T: Config> = StorageNMap<118		Key = (119			Key<Twox64Concat, CollectionId>,120			Key<Twox64Concat, TokenId>,121			// Owner122			Key<Blake2_128, T::CrossAccountId>,123			// Spender124			Key<Blake2_128Concat, T::CrossAccountId>,125		),126		Value = u128,127		QueryKind = ValueQuery,128	>;129}130131pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);132impl<T: Config> RefungibleHandle<T> {133	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {134		Self(inner)135	}136	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {137		self.0138	}139}140impl<T: Config> Deref for RefungibleHandle<T> {141	type Target = pallet_common::CollectionHandle<T>;142143	fn deref(&self) -> &Self::Target {144		&self.0145	}146}147148impl<T: Config> Pallet<T> {149	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {150		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)151	}152	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {153		<TotalSupply<T>>::contains_key((collection.id, token))154	}155}156157// unchecked calls skips any permission checks158impl<T: Config> Pallet<T> {159	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {160		<PalletCommon<T>>::init_collection(data)161	}162	pub fn destroy_collection(163		collection: RefungibleHandle<T>,164		sender: &T::CrossAccountId,165	) -> DispatchResult {166		let id = collection.id;167168		// =========169170		PalletCommon::destroy_collection(collection.0, sender)?;171172		<TokensMinted<T>>::remove(id);173		<TokensBurnt<T>>::remove(id);174		<TokenData<T>>::remove_prefix((id,), None);175		<TotalSupply<T>>::remove_prefix((id,), None);176		<Balance<T>>::remove_prefix((id,), None);177		<Allowance<T>>::remove_prefix((id,), None);178		Ok(())179	}180181	pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {182		let burnt = <TokensBurnt<T>>::get(collection.id)183			.checked_add(1)184			.ok_or(ArithmeticError::Overflow)?;185186		<TokensBurnt<T>>::insert(collection.id, burnt);187		<TokenData<T>>::remove((collection.id, token_id));188		<TotalSupply<T>>::remove((collection.id, token_id));189		<Balance<T>>::remove_prefix((collection.id, token_id), None);190		<Allowance<T>>::remove_prefix((collection.id, token_id), None);191		// TODO: ERC721 transfer event192		return Ok(());193	}194195	pub fn burn(196		collection: &RefungibleHandle<T>,197		owner: &T::CrossAccountId,198		token: TokenId,199		amount: u128,200	) -> DispatchResult {201		let total_supply = <TotalSupply<T>>::get((collection.id, token))202			.checked_sub(amount)203			.ok_or(<CommonError<T>>::TokenValueTooLow)?;204205		// This was probally last owner of this token?206		if total_supply == 0 {207			// Ensure user actually owns this amount208			ensure!(209				<Balance<T>>::get((collection.id, token, owner)) == amount,210				<CommonError<T>>::TokenValueTooLow211			);212			let account_balance = <AccountBalance<T>>::get((collection.id, owner))213				.checked_sub(1)214				// Should not occur215				.ok_or(ArithmeticError::Underflow)?;216217			// =========218219			<Owned<T>>::remove((collection.id, owner, token));220			<AccountBalance<T>>::insert((collection.id, owner), account_balance);221			Self::burn_token(collection, token)?;222			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(223				collection.id,224				token,225				owner.clone(),226				amount,227			));228			return Ok(());229		}230231		let balance = <Balance<T>>::get((collection.id, token, owner))232			.checked_sub(amount)233			.ok_or(<CommonError<T>>::TokenValueTooLow)?;234		let account_balance = if balance == 0 {235			<AccountBalance<T>>::get((collection.id, owner))236				.checked_sub(1)237				// Should not occur238				.ok_or(ArithmeticError::Underflow)?239		} else {240			0241		};242243		// =========244245		if balance == 0 {246			<Owned<T>>::remove((collection.id, owner, token));247			<Balance<T>>::remove((collection.id, token, owner));248			<AccountBalance<T>>::insert((collection.id, owner), account_balance);249		} else {250			<Balance<T>>::insert((collection.id, token, owner), balance);251		}252		<TotalSupply<T>>::insert((collection.id, token), total_supply);253		// TODO: ERC20 transfer event254		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(255			collection.id,256			token,257			owner.clone(),258			amount,259		));260		Ok(())261	}262263	pub fn transfer(264		collection: &RefungibleHandle<T>,265		from: &T::CrossAccountId,266		to: &T::CrossAccountId,267		token: TokenId,268		amount: u128,269	) -> DispatchResult {270		ensure!(271			collection.limits.transfers_enabled(),272			<CommonError<T>>::TransferNotAllowed273		);274275		if collection.access == AccessMode::AllowList {276			collection.check_allowlist(from)?;277			collection.check_allowlist(to)?;278		}279		<PalletCommon<T>>::ensure_correct_receiver(to)?;280281		let balance_from = <Balance<T>>::get((collection.id, token, from))282			.checked_sub(amount)283			.ok_or(<CommonError<T>>::TokenValueTooLow)?;284		let mut create_target = false;285		let from_to_differ = from != to;286		let balance_to = if from != to {287			let old_balance = <Balance<T>>::get((collection.id, token, to));288			if old_balance == 0 {289				create_target = true;290			}291			Some(292				old_balance293					.checked_add(amount)294					.ok_or(ArithmeticError::Overflow)?,295			)296		} else {297			None298		};299300		let account_balance_from = if balance_from == 0 {301			Some(302				<AccountBalance<T>>::get((collection.id, from))303					.checked_sub(1)304					// Should not occur305					.ok_or(ArithmeticError::Underflow)?,306			)307		} else {308			None309		};310		// Account data is created in token, AccountBalance should be increased311		// But only if from != to as we shouldn't check overflow in this case312		let account_balance_to = if create_target && from_to_differ {313			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))314				.checked_add(1)315				.ok_or(ArithmeticError::Overflow)?;316			ensure!(317				account_balance_to < collection.limits.account_token_ownership_limit(),318				<CommonError<T>>::AccountTokenLimitExceeded,319			);320321			Some(account_balance_to)322		} else {323			None324		};325326		// =========327328		if let Some(balance_to) = balance_to {329			// from != to330			if balance_from == 0 {331				<Balance<T>>::remove((collection.id, token, from));332			} else {333				<Balance<T>>::insert((collection.id, token, from), balance_from);334			}335			<Balance<T>>::insert((collection.id, token, to), balance_to);336			if let Some(account_balance_from) = account_balance_from {337				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);338				<Owned<T>>::remove((collection.id, from, token));339			}340			if let Some(account_balance_to) = account_balance_to {341				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);342				<Owned<T>>::insert((collection.id, to, token), true);343			}344		}345346		// TODO: ERC20 transfer event347		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(348			collection.id,349			token,350			from.clone(),351			to.clone(),352			amount,353		));354		Ok(())355	}356357	pub fn create_multiple_items(358		collection: &RefungibleHandle<T>,359		sender: &T::CrossAccountId,360		data: Vec<CreateItemData<T>>,361	) -> DispatchResult {362		let unrestricted_minting = collection.is_owner_or_admin(sender)?;363		if !unrestricted_minting {364			ensure!(365				collection.mint_mode,366				<CommonError<T>>::PublicMintingNotAllowed367			);368			collection.check_allowlist(sender)?;369370			for item in data.iter() {371				for (user, _) in &item.users {372					collection.check_allowlist(&user)?;373				}374			}375		}376377		for item in data.iter() {378			for (owner, _) in item.users.iter() {379				<PalletCommon<T>>::ensure_correct_receiver(owner)?;380			}381		}382383		// Total pieces per tokens384		let totals = data385			.iter()386			.map(|data| {387				Ok(data388					.users389					.iter()390					.map(|u| u.1)391					.try_fold(0u128, |acc, v| acc.checked_add(*v))392					.ok_or(ArithmeticError::Overflow)?)393			})394			.collect::<Result<Vec<_>, DispatchError>>()?;395		for total in &totals {396			ensure!(397				*total <= MAX_REFUNGIBLE_PIECES,398				<Error<T>>::WrongRefungiblePieces399			);400		}401402		let first_token_id = <TokensMinted<T>>::get(collection.id);403		let tokens_minted = first_token_id404			.checked_add(data.len() as u32)405			.ok_or(ArithmeticError::Overflow)?;406		ensure!(407			tokens_minted < collection.limits.token_limit(),408			<CommonError<T>>::CollectionTokenLimitExceeded409		);410411		let mut balances = BTreeMap::new();412		for data in &data {413			for (owner, _) in &data.users {414				let balance = balances415					.entry(owner)416					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));417				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;418419				ensure!(420					*balance <= collection.limits.account_token_ownership_limit(),421					<CommonError<T>>::AccountTokenLimitExceeded,422				);423			}424		}425426		// =========427428		<TokensMinted<T>>::insert(collection.id, tokens_minted);429		for (account, balance) in balances {430			<AccountBalance<T>>::insert((collection.id, account), balance);431		}432		for (i, token) in data.into_iter().enumerate() {433			let token_id = first_token_id + i as u32 + 1;434			<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);435436			<TokenData<T>>::insert(437				(collection.id, token_id),438				ItemData {439					const_data: token.const_data.into(),440					variable_data: token.variable_data.into(),441				},442			);443			for (user, amount) in token.users.into_iter() {444				if amount == 0 {445					continue;446				}447				<Balance<T>>::insert((collection.id, token_id, &user), amount);448				<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);449				// TODO: ERC20 transfer event450				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(451					collection.id,452					TokenId(token_id),453					user,454					amount,455				));456			}457		}458		Ok(())459	}460461	pub fn set_allowance_unchecked(462		collection: &RefungibleHandle<T>,463		sender: &T::CrossAccountId,464		spender: &T::CrossAccountId,465		token: TokenId,466		amount: u128,467	) {468		<Allowance<T>>::insert((collection.id, token, sender, spender), amount);469		// TODO: ERC20 approval event470		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(471			collection.id,472			token,473			sender.clone(),474			spender.clone(),475			amount,476		))477	}478479	pub fn set_allowance(480		collection: &RefungibleHandle<T>,481		sender: &T::CrossAccountId,482		spender: &T::CrossAccountId,483		token: TokenId,484		amount: u128,485	) -> DispatchResult {486		if collection.access == AccessMode::AllowList {487			collection.check_allowlist(&sender)?;488			collection.check_allowlist(&spender)?;489		}490491		<PalletCommon<T>>::ensure_correct_receiver(spender)?;492493		if <Balance<T>>::get((collection.id, token, sender)) < amount {494			ensure!(495				collection.ignores_owned_amount(sender)? && Self::token_exists(collection, token),496				<CommonError<T>>::CantApproveMoreThanOwned497			);498		}499500		// =========501502		Self::set_allowance_unchecked(collection, sender, spender, token, amount);503		Ok(())504	}505506	pub fn transfer_from(507		collection: &RefungibleHandle<T>,508		spender: &T::CrossAccountId,509		from: &T::CrossAccountId,510		to: &T::CrossAccountId,511		token: TokenId,512		amount: u128,513	) -> DispatchResult {514		if spender.conv_eq(from) {515			return Self::transfer(collection, from, to, token, amount);516		}517		if collection.access == AccessMode::AllowList {518			// `from`, `to` checked in [`transfer`]519			collection.check_allowlist(spender)?;520		}521522		let allowance =523			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);524		if allowance.is_none() {525			ensure!(526				collection.ignores_allowance(spender)?,527				<CommonError<T>>::TokenValueNotEnough528			);529		}530531		// =========532533		Self::transfer(collection, from, to, token, amount)?;534		if let Some(allowance) = allowance {535			Self::set_allowance_unchecked(collection, from, spender, token, allowance);536		}537		Ok(())538	}539540	pub fn burn_from(541		collection: &RefungibleHandle<T>,542		spender: &T::CrossAccountId,543		from: &T::CrossAccountId,544		token: TokenId,545		amount: u128,546	) -> DispatchResult {547		if spender.conv_eq(from) {548			return Self::burn(collection, from, token, amount);549		}550		if collection.access == AccessMode::AllowList {551			// `from` checked in [`burn`]552			collection.check_allowlist(spender)?;553		}554555		let allowance =556			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);557		if allowance.is_none() {558			ensure!(559				collection.ignores_allowance(spender)?,560				<CommonError<T>>::TokenValueNotEnough561			);562		}563564		// =========565566		Self::burn(collection, from, token, amount)?;567		if let Some(allowance) = allowance {568			Self::set_allowance_unchecked(collection, from, spender, token, allowance);569		}570		Ok(())571	}572573	pub fn set_variable_metadata(574		collection: &RefungibleHandle<T>,575		sender: &T::CrossAccountId,576		token: TokenId,577		data: Vec<u8>,578	) -> DispatchResult {579		ensure!(580			data.len() as u32 <= CUSTOM_DATA_LIMIT,581			<CommonError<T>>::TokenVariableDataLimitExceeded582		);583		collection.check_can_update_meta(584			sender,585			&T::CrossAccountId::from_sub(collection.owner.clone()),586		)?;587588		collection.consume_sstore()?;589		let token_data = <TokenData<T>>::get((collection.id, token));590591		// =========592593		<TokenData<T>>::insert(594			(collection.id, token),595			ItemData {596				variable_data: data,597				..token_data598			},599		);600		Ok(())601	}602603	/// Delegated to `create_multiple_items`604	pub fn create_item(605		collection: &RefungibleHandle<T>,606		sender: &T::CrossAccountId,607		data: CreateItemData<T>,608	) -> DispatchResult {609		Self::create_multiple_items(collection, sender, vec![data])610	}611}
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
--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -1040,14 +1040,23 @@
 				.or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))
 		}
 		fn adminlist(collection: CollectionId) -> Vec<CrossAccountId> {
-			<pallet_nft::Pallet<Runtime>>::adminlist(collection)
+			<pallet_common::Pallet<Runtime>>::adminlist(collection)
 		}
 		fn allowlist(collection: CollectionId) -> Vec<CrossAccountId> {
-			<pallet_nft::Pallet<Runtime>>::allowlist(collection)
+			<pallet_common::Pallet<Runtime>>::allowlist(collection)
+		}
+		fn allowed(collection: CollectionId, user: CrossAccountId) -> bool {
+			<pallet_common::Pallet<Runtime>>::allowed(collection, user)
 		}
 		fn last_token_id(collection: CollectionId) -> TokenId {
 			dispatch_nft_runtime!(collection.last_token_id())
 		}
+		fn collection_by_id(collection: CollectionId) -> Option<Collection<AccountId>> {
+			<pallet_common::CollectionById<Runtime>>::get(collection)
+		}
+		fn collection_stats() -> CollectionStats {
+			<pallet_common::Pallet<Runtime>>::collection_stats()
+		}
 	}
 
 	impl sp_api::Core<Block> for Runtime {
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> {