git.delta.rocks / unique-network / refs/commits / bba462e4a170

difftreelog

Merge pull request #232 from UniqueNetwork/refactor/pallet-common-rpcs

kozyrevdev2021-11-23parents: #55bb4eb #8b6a5ec.patch.diff
in: master
Prefer api.rpc.nft to api.query.common

38 files changed

modified.devcontainer/devcontainer.jsondiffbeforeafterboth
--- a/.devcontainer/devcontainer.json
+++ b/.devcontainer/devcontainer.json
@@ -1,8 +1,8 @@
 {
 	"name": "Rust",
     "dockerComposeFile": "./docker-compose.yml",
-    "service": "nft_private",
-    "workspaceFolder": "/workspaces/nft_private",
+    "service": "unique-chain",
+    "workspaceFolder": "/workspaces/unique-chain",
 	"settings": { 
 		"terminal.integrated.shell.linux": "/bin/bash",
 		"lldb.executable": "/usr/bin/lldb",
modified.devcontainer/docker-compose.ymldiffbeforeafterboth
--- a/.devcontainer/docker-compose.yml
+++ b/.devcontainer/docker-compose.yml
@@ -1,13 +1,13 @@
 version: '3'
 services:
-  nft_private:
+  unique-chain:
     build: 
         context: .
     environment:
       - JAEGER_AGENT_HOST=jaeger
       - JAEGER_AGENT_PORT=6831
     volumes:
-      - ..:/workspaces/nft_private:cached
+      - ..:/workspaces/unique-chain:cached
       - ../../polkadot:/workspaces/polkadot:cached
       - ../../polkadot-launch:/workspaces/polkadot-launch:cached
       #- ../../frontier:/workspaces/frontier
modified.github/workflows/node_build_test.ymldiffbeforeafterboth
--- a/.github/workflows/node_build_test.yml
+++ b/.github/workflows/node_build_test.yml
@@ -35,10 +35,10 @@
           script: |
             eval $(ssh-agent -s)
             ssh-add /home/devops/.ssh/git_hub
-            git clone git@github.com:UniqueNetwork/nft_private.git
-            cd nft_private
+            git clone git@github.com:UniqueNetwork/unique-chain.git
+            cd unique-chain
             git checkout develop
             # git pull --all
             chmod +x ci_node.sh
             ./ci_node.sh
-            rm -rf /home/polkadot/nft_private
+            rm -rf /home/polkadot/unique-chain
modifiedDockerfile-parachaindiffbeforeafterboth
--- a/Dockerfile-parachain
+++ b/Dockerfile-parachain
@@ -98,7 +98,7 @@
     npm install --global yarn && \
     yarn
 
-COPY --from=builder /nft_parachain/target/$PROFILE/nft /nft_private/target/$PROFILE/
+COPY --from=builder /nft_parachain/target/$PROFILE/nft /unique-chain/target/$PROFILE/
 COPY --from=builder-polkadot /nft_parachain/polkadot/target/$PROFILE/polkadot /polkadot/target/$PROFILE/
 
 CMD export NVM_DIR="$HOME/.nvm" && \
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);
 }
modifiedlaunch-config.jsondiffbeforeafterboth
--- a/launch-config.json
+++ b/launch-config.json
@@ -55,7 +55,7 @@
     },
     "parachains": [
         {
-            "bin": "../nft_private/target/release/nft",
+            "bin": "../unique-chain/target/release/nft",
             "id": "2000",
             "balance": "1000000000000000000000",
             "nodes": [
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,11 @@
 		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 +360,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/lib.rsdiffbeforeafterboth
before · pallets/nft/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#![recursion_limit = "1024"]7#![cfg_attr(not(feature = "std"), no_std)]8#![allow(9	clippy::too_many_arguments,10	clippy::unnecessary_mut_passed,11	clippy::unused_unit12)]1314extern crate alloc;1516pub use serde::{Serialize, Deserialize};1718pub use frame_support::{19	construct_runtime, decl_module, decl_storage, decl_error,20	dispatch::DispatchResult,21	ensure, fail, parameter_types,22	traits::{23		ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced, Randomness,24		IsSubType, WithdrawReasons,25	},26	weights::{27		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},28		DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,29		WeightToFeePolynomial, DispatchClass,30	},31	StorageValue, transactional,32	pallet_prelude::DispatchResultWithPostInfo,33};34use scale_info::TypeInfo;35use frame_system::{self as system, ensure_signed};36use sp_runtime::{sp_std::prelude::Vec};37use nft_data_structs::{38	MAX_DECIMAL_POINTS, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, CUSTOM_DATA_LIMIT,39	VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT,40	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,41	NFT_SPONSOR_TRANSFER_TIMEOUT, AccessMode, Collection, CreateItemData, CollectionLimits,42	CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,43};44use pallet_common::{45	account::CrossAccountId, CollectionHandle, IsAdmin, Pallet as PalletCommon,46	Error as CommonError, CommonWeightInfo, Allowlist,47};48use pallet_refungible::{Pallet as PalletRefungible, RefungibleHandle};49use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};50use pallet_nonfungible::{Pallet as PalletNonfungible, NonfungibleHandle};5152#[cfg(test)]53mod mock;5455#[cfg(test)]56mod tests;5758mod eth;59mod sponsorship;60pub use sponsorship::NftSponsorshipHandler;61pub use eth::sponsoring::NftEthSponsorshipHandler;6263pub use eth::NftErcSupport;6465pub mod common;66use common::CommonWeights;67pub mod dispatch;68use dispatch::dispatch_call;6970#[cfg(feature = "runtime-benchmarks")]71mod benchmarking;72pub mod weights;73use weights::WeightInfo;7475decl_error! {76	/// Error for non-fungible-token module.77	pub enum Error for Module<T: Config> {78		/// Decimal_points parameter must be lower than MAX_DECIMAL_POINTS constant, currently it is 30.79		CollectionDecimalPointLimitExceeded,80		/// This address is not set as sponsor, use setCollectionSponsor first.81		ConfirmUnsetSponsorFail,82		/// Length of items properties must be greater than 0.83		EmptyArgument,84		/// Collection limit bounds per collection exceeded85		CollectionLimitBoundsExceeded,86		/// Tried to enable permissions which are only permitted to be disabled87		OwnerPermissionsCantBeReverted,88	}89}90pub trait Config:91	system::Config92	+ pallet_evm_coder_substrate::Config93	+ pallet_common::Config94	+ pallet_nonfungible::Config95	+ pallet_refungible::Config96	+ pallet_fungible::Config97	+ Sized98	+ TypeInfo99{100	/// Weight information for extrinsics in this pallet.101	type WeightInfo: WeightInfo;102}103104type SelfWeightOf<T> = <T as Config>::WeightInfo;105106// # Used definitions107//108// ## User control levels109//110// chain-controlled - key is uncontrolled by user111//                    i.e autoincrementing index112//                    can use non-cryptographic hash113// real - key is controlled by user114//        but it is hard to generate enough colliding values, i.e owner of signed txs115//        can use non-cryptographic hash116// controlled - key is completly controlled by users117//              i.e maps with mutable keys118//              should use cryptographic hash119//120// ## User control level downgrade reasons121//122// ?1 - chain-controlled -> controlled123//      collections/tokens can be destroyed, resulting in massive holes124// ?2 - chain-controlled -> controlled125//      same as ?1, but can be only added, resulting in easier exploitation126// ?3 - real -> controlled127//      no confirmation required, so addresses can be easily generated128decl_storage! {129	trait Store for Module<T: Config> as Nft {130131		//#region Private members132		/// Used for migrations133		ChainVersion: u64;134		//#endregion135136		//#region Tokens transfer rate limit baskets137		/// (Collection id (controlled?2), who created (real))138		/// TODO: Off chain worker should remove from this map when collection gets removed139		pub CreateItemBasket get(fn create_item_basket): map hasher(blake2_128_concat) (CollectionId, T::AccountId) => Option<T::BlockNumber>;140		/// Collection id (controlled?2), token id (controlled?2)141		pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;142		/// Collection id (controlled?2), owning user (real)143		pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;144		/// Collection id (controlled?2), token id (controlled?2)145		pub ReFungibleTransferBasket get(fn refungible_transfer_basket): nmap hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;146		//#endregion147148		/// Variable metadata sponsoring149		/// Collection id (controlled?2), token id (controlled?2)150		pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;151		/// Approval sponsoring152		pub NftApproveBasket get(fn nft_approve_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;153		pub FungibleApproveBasket get(fn fungible_approve_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;154		pub RefungibleApproveBasket get(fn refungible_approve_basket): nmap hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;155	}156}157158decl_module! {159	pub struct Module<T: Config> for enum Call160	where161		origin: T::Origin162	{163		type Error = Error<T>;164165		fn on_initialize(_now: T::BlockNumber) -> Weight {166			0167		}168169		/// This method creates a Collection of NFTs. Each Token may have multiple properties encoded as an array of bytes of certain length. The initial owner and admin of the collection are set to the address that signed the transaction. Both addresses can be changed later.170		///171		/// # Permissions172		///173		/// * Anyone.174		///175		/// # Arguments176		///177		/// * collection_name: UTF-16 string with collection name (limit 64 characters), will be stored as zero-terminated.178		///179		/// * collection_description: UTF-16 string with collection description (limit 256 characters), will be stored as zero-terminated.180		///181		/// * token_prefix: UTF-8 string with token prefix.182		///183		/// * mode: [CollectionMode] collection type and type dependent data.184		// returns collection ID185		#[weight = <SelfWeightOf<T>>::create_collection()]186		#[transactional]187		pub fn create_collection(origin,188								 collection_name: Vec<u16>,189								 collection_description: Vec<u16>,190								 token_prefix: Vec<u8>,191								 mode: CollectionMode) -> DispatchResult {192193			// Anyone can create a collection194			let who = ensure_signed(origin)?;195196			// Create new collection197			let new_collection = Collection::<T> {198				owner: who.clone(),199				name: collection_name,200				mode: mode.clone(),201				mint_mode: false,202				access: AccessMode::Normal,203				description: collection_description,204				token_prefix,205				offchain_schema: Vec::new(),206				schema_version: SchemaVersion::ImageURL,207				sponsorship: SponsorshipState::Disabled,208				variable_on_chain_schema: Vec::new(),209				const_on_chain_schema: Vec::new(),210				limits: Default::default(),211				meta_update_permission: Default::default(),212			};213214			let _id = match mode {215				CollectionMode::NFT => {PalletNonfungible::init_collection(new_collection)?},216				CollectionMode::Fungible(decimal_points) => {217					// check params218					ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);219					PalletFungible::init_collection(new_collection)?220				}221				CollectionMode::ReFungible => {222					PalletRefungible::init_collection(new_collection)?223				}224			};225226			Ok(())227		}228229		/// **DANGEROUS**: Destroys collection and all NFTs within this collection. Users irrecoverably lose their assets and may lose real money.230		///231		/// # Permissions232		///233		/// * Collection Owner.234		///235		/// # Arguments236		///237		/// * collection_id: collection to destroy.238		#[weight = <SelfWeightOf<T>>::destroy_collection()]239		#[transactional]240		pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {241			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);242243			let collection = <CollectionHandle<T>>::try_get(collection_id)?;244			collection.check_is_owner(&sender)?;245246			// =========247248			match collection.mode {249				CollectionMode::ReFungible => PalletRefungible::destroy_collection(RefungibleHandle::cast(collection), &sender)?,250				CollectionMode::Fungible(_) => PalletFungible::destroy_collection(FungibleHandle::cast(collection), &sender)?,251				CollectionMode::NFT => PalletNonfungible::destroy_collection(NonfungibleHandle::cast(collection), &sender)?,252			}253254			<NftTransferBasket<T>>::remove_prefix(collection_id, None);255			<FungibleTransferBasket<T>>::remove_prefix(collection_id, None);256			<ReFungibleTransferBasket<T>>::remove_prefix((collection_id,), None);257258			<VariableMetaDataBasket<T>>::remove_prefix(collection_id, None);259			<NftApproveBasket<T>>::remove_prefix(collection_id, None);260			<FungibleApproveBasket<T>>::remove_prefix(collection_id, None);261			<RefungibleApproveBasket<T>>::remove_prefix((collection_id,), None);262263			Ok(())264		}265266		/// Add an address to allow list.267		///268		/// # Permissions269		///270		/// * Collection Owner271		/// * Collection Admin272		///273		/// # Arguments274		///275		/// * collection_id.276		///277		/// * address.278		#[weight = <SelfWeightOf<T>>::add_to_allow_list()]279		#[transactional]280		pub fn add_to_allow_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{281282			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);283			let collection = <CollectionHandle<T>>::try_get(collection_id)?;284285			<PalletCommon<T>>::toggle_allowlist(286				&collection,287				&sender,288				&address,289				true,290			)?;291292			Ok(())293		}294295		/// Remove an address from allow list.296		///297		/// # Permissions298		///299		/// * Collection Owner300		/// * Collection Admin301		///302		/// # Arguments303		///304		/// * collection_id.305		///306		/// * address.307		#[weight = <SelfWeightOf<T>>::remove_from_allow_list()]308		#[transactional]309		pub fn remove_from_allow_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{310311			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);312			let collection = <CollectionHandle<T>>::try_get(collection_id)?;313314			<PalletCommon<T>>::toggle_allowlist(315				&collection,316				&sender,317				&address,318				false,319			)?;320321			Ok(())322		}323324		/// Toggle between normal and allow list access for the methods with access for `Anyone`.325		///326		/// # Permissions327		///328		/// * Collection Owner.329		///330		/// # Arguments331		///332		/// * collection_id.333		///334		/// * mode: [AccessMode]335		#[weight = <SelfWeightOf<T>>::set_public_access_mode()]336		#[transactional]337		pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult338		{339			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);340341			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;342			target_collection.check_is_owner(&sender)?;343344			target_collection.access = mode;345			target_collection.save()346		}347348		/// Allows Anyone to create tokens if:349		/// * Allow List is enabled, and350		/// * Address is added to allow list, and351		/// * This method was called with True parameter352		///353		/// # Permissions354		/// * Collection Owner355		///356		/// # Arguments357		///358		/// * collection_id.359		///360		/// * mint_permission: Boolean parameter. If True, allows minting to Anyone with conditions above.361		#[weight = <SelfWeightOf<T>>::set_mint_permission()]362		#[transactional]363		pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult364		{365			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);366367			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;368			target_collection.check_is_owner(&sender)?;369370			target_collection.mint_mode = mint_permission;371			target_collection.save()372		}373374		/// Change the owner of the collection.375		///376		/// # Permissions377		///378		/// * Collection Owner.379		///380		/// # Arguments381		///382		/// * collection_id.383		///384		/// * new_owner.385		#[weight = <SelfWeightOf<T>>::change_collection_owner()]386		#[transactional]387		pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {388389			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);390391			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;392			target_collection.check_is_owner(&sender)?;393394			target_collection.owner = new_owner;395			target_collection.save()396		}397398		/// Adds an admin of the Collection.399		/// NFT Collection can be controlled by multiple admin addresses (some which can also be servers, for example). Admins can issue and burn NFTs, as well as add and remove other admins, but cannot change NFT or Collection ownership.400		///401		/// # Permissions402		///403		/// * Collection Owner.404		/// * Collection Admin.405		///406		/// # Arguments407		///408		/// * collection_id: ID of the Collection to add admin for.409		///410		/// * new_admin_id: Address of new admin to add.411		#[weight = <SelfWeightOf<T>>::add_collection_admin()]412		#[transactional]413		pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::CrossAccountId) -> DispatchResult {414			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);415			let collection = <CollectionHandle<T>>::try_get(collection_id)?;416417			<PalletCommon<T>>::toggle_admin(&collection, &sender, &new_admin_id, true)418		}419420		/// Remove admin address of the Collection. An admin address can remove itself. List of admins may become empty, in which case only Collection Owner will be able to add an Admin.421		///422		/// # Permissions423		///424		/// * Collection Owner.425		/// * Collection Admin.426		///427		/// # Arguments428		///429		/// * collection_id: ID of the Collection to remove admin for.430		///431		/// * account_id: Address of admin to remove.432		#[weight = <SelfWeightOf<T>>::remove_collection_admin()]433		#[transactional]434		pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::CrossAccountId) -> DispatchResult {435			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);436			let collection = <CollectionHandle<T>>::try_get(collection_id)?;437438			<PalletCommon<T>>::toggle_admin(&collection, &sender, &account_id, false)439		}440441		/// # Permissions442		///443		/// * Collection Owner444		///445		/// # Arguments446		///447		/// * collection_id.448		///449		/// * new_sponsor.450		#[weight = <SelfWeightOf<T>>::set_collection_sponsor()]451		#[transactional]452		pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {453			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);454455			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;456			target_collection.check_is_owner(&sender)?;457458			target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor);459			target_collection.save()460		}461462		/// # Permissions463		///464		/// * Sponsor.465		///466		/// # Arguments467		///468		/// * collection_id.469		#[weight = <SelfWeightOf<T>>::confirm_sponsorship()]470		#[transactional]471		pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {472			let sender = ensure_signed(origin)?;473474			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;475			ensure!(476				target_collection.sponsorship.pending_sponsor() == Some(&sender),477				Error::<T>::ConfirmUnsetSponsorFail478			);479480			target_collection.sponsorship = SponsorshipState::Confirmed(sender);481			target_collection.save()482		}483484		/// Switch back to pay-per-own-transaction model.485		///486		/// # Permissions487		///488		/// * Collection owner.489		///490		/// # Arguments491		///492		/// * collection_id.493		#[weight = <SelfWeightOf<T>>::remove_collection_sponsor()]494		#[transactional]495		pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {496			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);497498			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;499			target_collection.check_is_owner(&sender)?;500501			target_collection.sponsorship = SponsorshipState::Disabled;502			target_collection.save()503		}504505		/// This method creates a concrete instance of NFT Collection created with CreateCollection method.506		///507		/// # Permissions508		///509		/// * Collection Owner.510		/// * Collection Admin.511		/// * Anyone if512		///     * Allow List is enabled, and513		///     * Address is added to allow list, and514		///     * MintPermission is enabled (see SetMintPermission method)515		///516		/// # Arguments517		///518		/// * collection_id: ID of the collection.519		///520		/// * owner: Address, initial owner of the NFT.521		///522		/// * data: Token data to store on chain.523		#[weight = <CommonWeights<T>>::create_item()]524		#[transactional]525		pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResultWithPostInfo {526			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);527528			dispatch_call::<T, _>(collection_id, |d| d.create_item(sender, owner, data))529		}530531		/// This method creates multiple items in a collection created with CreateCollection method.532		///533		/// # Permissions534		///535		/// * Collection Owner.536		/// * Collection Admin.537		/// * Anyone if538		///     * Allow List is enabled, and539		///     * Address is added to allow list, and540		///     * MintPermission is enabled (see SetMintPermission method)541		///542		/// # Arguments543		///544		/// * collection_id: ID of the collection.545		///546		/// * itemsData: Array items properties. Each property is an array of bytes itself, see [create_item].547		///548		/// * owner: Address, initial owner of the NFT.549		#[weight = <CommonWeights<T>>::create_multiple_items(items_data.len() as u32)]550		#[transactional]551		pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResultWithPostInfo {552			ensure!(!items_data.is_empty(), Error::<T>::EmptyArgument);553			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);554555			dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items(sender, owner, items_data))556		}557558		// TODO! transaction weight559560		/// Set transfers_enabled value for particular collection561		///562		/// # Permissions563		///564		/// * Collection Owner.565		///566		/// # Arguments567		///568		/// * collection_id: ID of the collection.569		///570		/// * value: New flag value.571		#[weight = <SelfWeightOf<T>>::set_transfers_enabled_flag()]572		#[transactional]573		pub fn set_transfers_enabled_flag(origin, collection_id: CollectionId, value: bool) -> DispatchResult {574			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);575			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;576			target_collection.check_is_owner(&sender)?;577578			// =========579580			target_collection.limits.transfers_enabled = Some(value);581			target_collection.save()582		}583584		/// Destroys a concrete instance of NFT.585		///586		/// # Permissions587		///588		/// * Collection Owner.589		/// * Collection Admin.590		/// * Current NFT Owner.591		///592		/// # Arguments593		///594		/// * collection_id: ID of the collection.595		///596		/// * item_id: ID of NFT to burn.597		#[weight = <CommonWeights<T>>::burn_item()]598		#[transactional]599		pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {600			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);601602			let post_info = dispatch_call::<T, _>(collection_id, |d| d.burn_item(sender, item_id, value))?;603			if value == 1 {604				<NftTransferBasket<T>>::remove(collection_id, item_id);605				<NftApproveBasket<T>>::remove(collection_id, item_id);606			}607			// Those maps should be cleared only if token disappears completly, need to move this part of logic to pallets?608			// <FungibleApproveBasket<T>>::remove(collection_id, sender.as_sub());609			// <RefungibleApproveBasket<T>>::remove((collection_id, item_id, sender.as_sub()));610			Ok(post_info)611		}612613		/// Destroys a concrete instance of NFT on behalf of the owner614		/// See also: [`approve`]615		///616		/// # Permissions617		///618		/// * Collection Owner.619		/// * Collection Admin.620		/// * Current NFT Owner.621		///622		/// # Arguments623		///624		/// * collection_id: ID of the collection.625		///626		/// * item_id: ID of NFT to burn.627		///628		/// * from: owner of item629		#[weight = <CommonWeights<T>>::burn_from()]630		#[transactional]631		pub fn burn_from(origin, collection_id: CollectionId, from: T::CrossAccountId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {632			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);633634			dispatch_call::<T, _>(collection_id, |d| d.burn_from(sender, from, item_id, value))635		}636637		/// Change ownership of the token.638		///639		/// # Permissions640		///641		/// * Collection Owner642		/// * Collection Admin643		/// * Current NFT owner644		///645		/// # Arguments646		///647		/// * recipient: Address of token recipient.648		///649		/// * collection_id.650		///651		/// * item_id: ID of the item652		///     * Non-Fungible Mode: Required.653		///     * Fungible Mode: Ignored.654		///     * Re-Fungible Mode: Required.655		///656		/// * value: Amount to transfer.657		///     * Non-Fungible Mode: Ignored658		///     * Fungible Mode: Must specify transferred amount659		///     * Re-Fungible Mode: Must specify transferred portion (between 0 and 1)660		#[weight = <CommonWeights<T>>::transfer()]661		#[transactional]662		pub fn transfer(origin, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {663			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);664665			dispatch_call::<T, _>(collection_id, |d| d.transfer(sender, recipient, item_id, value))666		}667668		/// Set, change, or remove approved address to transfer the ownership of the NFT.669		///670		/// # Permissions671		///672		/// * Collection Owner673		/// * Collection Admin674		/// * Current NFT owner675		///676		/// # Arguments677		///678		/// * approved: Address that is approved to transfer this NFT or zero (if needed to remove approval).679		///680		/// * collection_id.681		///682		/// * item_id: ID of the item.683		#[weight = <CommonWeights<T>>::approve()]684		#[transactional]685		pub fn approve(origin, spender: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResultWithPostInfo {686			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);687688			dispatch_call::<T, _>(collection_id, |d| d.approve(sender, spender, item_id, amount))689		}690691		/// Change ownership of a NFT on behalf of the owner. See Approve method for additional information. After this method executes, the approval is removed so that the approved address will not be able to transfer this NFT again from this owner.692		///693		/// # Permissions694		/// * Collection Owner695		/// * Collection Admin696		/// * Current NFT owner697		/// * Address approved by current NFT owner698		///699		/// # Arguments700		///701		/// * from: Address that owns token.702		///703		/// * recipient: Address of token recipient.704		///705		/// * collection_id.706		///707		/// * item_id: ID of the item.708		///709		/// * value: Amount to transfer.710		#[weight = <CommonWeights<T>>::transfer_from()]711		#[transactional]712		pub fn transfer_from(origin, from: T::CrossAccountId, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResultWithPostInfo {713			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);714715			dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value))716		}717718		/// Set off-chain data schema.719		///720		/// # Permissions721		///722		/// * Collection Owner723		/// * Collection Admin724		///725		/// # Arguments726		///727		/// * collection_id.728		///729		/// * schema: String representing the offchain data schema.730		#[weight = <CommonWeights<T>>::set_variable_metadata(data.len() as u32)]731		#[transactional]732		pub fn set_variable_meta_data (733			origin,734			collection_id: CollectionId,735			item_id: TokenId,736			data: Vec<u8>737		) -> DispatchResultWithPostInfo {738			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);739740			dispatch_call::<T, _>(collection_id, |d| d.set_variable_metadata(sender, item_id, data))741		}742743		/// Set meta_update_permission value for particular collection744		///745		/// # Permissions746		///747		/// * Collection Owner.748		///749		/// # Arguments750		///751		/// * collection_id: ID of the collection.752		///753		/// * value: New flag value.754		#[weight = <SelfWeightOf<T>>::set_meta_update_permission_flag()]755		#[transactional]756		pub fn set_meta_update_permission_flag(origin, collection_id: CollectionId, value: MetaUpdatePermission) -> DispatchResult {757			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);758			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;759760			ensure!(761				target_collection.meta_update_permission != MetaUpdatePermission::None,762				<CommonError<T>>::MetadataFlagFrozen,763			);764			target_collection.check_is_owner(&sender)?;765766			target_collection.meta_update_permission = value;767768			target_collection.save()769		}770771		/// Set schema standard772		/// ImageURL773		/// Unique774		///775		/// # Permissions776		///777		/// * Collection Owner778		/// * Collection Admin779		///780		/// # Arguments781		///782		/// * collection_id.783		///784		/// * schema: SchemaVersion: enum785		#[weight = <SelfWeightOf<T>>::set_schema_version()]786		#[transactional]787		pub fn set_schema_version(788			origin,789			collection_id: CollectionId,790			version: SchemaVersion791		) -> DispatchResult {792			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);793			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;794			target_collection.check_is_owner_or_admin(&sender)?;795			target_collection.schema_version = version;796			target_collection.save()797		}798799		/// Set off-chain data schema.800		///801		/// # Permissions802		///803		/// * Collection Owner804		/// * Collection Admin805		///806		/// # Arguments807		///808		/// * collection_id.809		///810		/// * schema: String representing the offchain data schema.811		#[weight = <SelfWeightOf<T>>::set_offchain_schema(schema.len() as u32)]812		#[transactional]813		pub fn set_offchain_schema(814			origin,815			collection_id: CollectionId,816			schema: Vec<u8>817		) -> DispatchResult {818			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);819			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;820			target_collection.check_is_owner_or_admin(&sender)?;821822			// check schema limit823			ensure!(schema.len() as u32 <= OFFCHAIN_SCHEMA_LIMIT, "");824825			target_collection.offchain_schema = schema;826			target_collection.save()827		}828829		/// Set const on-chain data schema.830		///831		/// # Permissions832		///833		/// * Collection Owner834		/// * Collection Admin835		///836		/// # Arguments837		///838		/// * collection_id.839		///840		/// * schema: String representing the const on-chain data schema.841		#[weight = <SelfWeightOf<T>>::set_const_on_chain_schema(schema.len() as u32)]842		#[transactional]843		pub fn set_const_on_chain_schema (844			origin,845			collection_id: CollectionId,846			schema: Vec<u8>847		) -> DispatchResult {848			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);849			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;850			target_collection.check_is_owner_or_admin(&sender)?;851852			// check schema limit853			ensure!(schema.len() as u32 <= CONST_ON_CHAIN_SCHEMA_LIMIT, "");854855			target_collection.const_on_chain_schema = schema;856			target_collection.save()857		}858859		/// Set variable on-chain data schema.860		///861		/// # Permissions862		///863		/// * Collection Owner864		/// * Collection Admin865		///866		/// # Arguments867		///868		/// * collection_id.869		///870		/// * schema: String representing the variable on-chain data schema.871		#[weight = <SelfWeightOf<T>>::set_const_on_chain_schema(schema.len() as u32)]872		#[transactional]873		pub fn set_variable_on_chain_schema (874			origin,875			collection_id: CollectionId,876			schema: Vec<u8>877		) -> DispatchResult {878			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);879			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;880			target_collection.check_is_owner_or_admin(&sender)?;881882			// check schema limit883			ensure!(schema.len() as u32 <= VARIABLE_ON_CHAIN_SCHEMA_LIMIT, "");884885			target_collection.variable_on_chain_schema = schema;886			target_collection.save()887		}888889		#[weight = <SelfWeightOf<T>>::set_collection_limits()]890		#[transactional]891		pub fn set_collection_limits(892			origin,893			collection_id: CollectionId,894			new_limit: CollectionLimits,895		) -> DispatchResult {896			let mut new_limit = new_limit;897			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);898			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;899			target_collection.check_is_owner(&sender)?;900			let old_limit = &target_collection.limits;901902			macro_rules! limit_default {903				($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{904					$(905						if let Some($new) = $new.$field {906							let $old = $old.$field($($arg)?);907							let _ = $new;908							let _ = $old;909							$check910						} else {911							$new.$field = $old.$field912						}913					)*914				}};915			}916917			limit_default!(old_limit, new_limit,918				account_token_ownership_limit => ensure!(919					new_limit <= MAX_TOKEN_OWNERSHIP,920					<Error<T>>::CollectionLimitBoundsExceeded,921				),922				sponsor_transfer_timeout(match target_collection.mode {923					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,924					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,925					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,926				}) => ensure!(927					new_limit <= MAX_SPONSOR_TIMEOUT,928					<Error<T>>::CollectionLimitBoundsExceeded,929				),930				sponsored_data_size => ensure!(931					new_limit <= CUSTOM_DATA_LIMIT,932					<Error<T>>::CollectionLimitBoundsExceeded,933				),934				token_limit => ensure!(935					old_limit >= new_limit && new_limit > 0,936					<CommonError<T>>::CollectionTokenLimitExceeded937				),938				owner_can_transfer => ensure!(939					old_limit || !new_limit,940					<Error<T>>::OwnerPermissionsCantBeReverted,941				),942				owner_can_destroy => ensure!(943					old_limit || !new_limit,944					<Error<T>>::OwnerPermissionsCantBeReverted,945				),946				sponsored_data_rate_limit => {},947				transfers_enabled => {},948			);949950			target_collection.limits = new_limit;951952			target_collection.save()953		}954	}955}956957// TODO: limit returned entries?958impl<T: Config> Pallet<T> {959	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {960		<IsAdmin<T>>::iter_prefix((collection,))961			.map(|(a, _)| a)962			.collect()963	}964	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {965		<Allowlist<T>>::iter_prefix((collection,))966			.map(|(a, _)| a)967			.collect()968	}969}
after · pallets/nft/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#![recursion_limit = "1024"]7#![cfg_attr(not(feature = "std"), no_std)]8#![allow(9	clippy::too_many_arguments,10	clippy::unnecessary_mut_passed,11	clippy::unused_unit12)]1314extern crate alloc;1516pub use serde::{Serialize, Deserialize};1718pub use frame_support::{19	construct_runtime, decl_module, decl_storage, decl_error,20	dispatch::DispatchResult,21	ensure, fail, parameter_types,22	traits::{23		ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced, Randomness,24		IsSubType, WithdrawReasons,25	},26	weights::{27		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},28		DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,29		WeightToFeePolynomial, DispatchClass,30	},31	StorageValue, transactional,32	pallet_prelude::DispatchResultWithPostInfo,33};34use scale_info::TypeInfo;35use frame_system::{self as system, ensure_signed};36use sp_runtime::{sp_std::prelude::Vec};37use nft_data_structs::{38	MAX_DECIMAL_POINTS, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, CUSTOM_DATA_LIMIT,39	VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT,40	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,41	NFT_SPONSOR_TRANSFER_TIMEOUT, AccessMode, Collection, CreateItemData, CollectionLimits,42	CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,43};44use pallet_common::{45	account::CrossAccountId, CollectionHandle, Pallet as PalletCommon, Error as CommonError,46	CommonWeightInfo,47};48use pallet_refungible::{Pallet as PalletRefungible, RefungibleHandle};49use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};50use pallet_nonfungible::{Pallet as PalletNonfungible, NonfungibleHandle};5152#[cfg(test)]53mod mock;5455#[cfg(test)]56mod tests;5758mod eth;59mod sponsorship;60pub use sponsorship::NftSponsorshipHandler;61pub use eth::sponsoring::NftEthSponsorshipHandler;6263pub use eth::NftErcSupport;6465pub mod common;66use common::CommonWeights;67pub mod dispatch;68use dispatch::dispatch_call;6970#[cfg(feature = "runtime-benchmarks")]71mod benchmarking;72pub mod weights;73use weights::WeightInfo;7475decl_error! {76	/// Error for non-fungible-token module.77	pub enum Error for Module<T: Config> {78		/// Decimal_points parameter must be lower than MAX_DECIMAL_POINTS constant, currently it is 30.79		CollectionDecimalPointLimitExceeded,80		/// This address is not set as sponsor, use setCollectionSponsor first.81		ConfirmUnsetSponsorFail,82		/// Length of items properties must be greater than 0.83		EmptyArgument,84		/// Collection limit bounds per collection exceeded85		CollectionLimitBoundsExceeded,86		/// Tried to enable permissions which are only permitted to be disabled87		OwnerPermissionsCantBeReverted,88	}89}90pub trait Config:91	system::Config92	+ pallet_evm_coder_substrate::Config93	+ pallet_common::Config94	+ pallet_nonfungible::Config95	+ pallet_refungible::Config96	+ pallet_fungible::Config97	+ Sized98	+ TypeInfo99{100	/// Weight information for extrinsics in this pallet.101	type WeightInfo: WeightInfo;102}103104type SelfWeightOf<T> = <T as Config>::WeightInfo;105106// # Used definitions107//108// ## User control levels109//110// chain-controlled - key is uncontrolled by user111//                    i.e autoincrementing index112//                    can use non-cryptographic hash113// real - key is controlled by user114//        but it is hard to generate enough colliding values, i.e owner of signed txs115//        can use non-cryptographic hash116// controlled - key is completly controlled by users117//              i.e maps with mutable keys118//              should use cryptographic hash119//120// ## User control level downgrade reasons121//122// ?1 - chain-controlled -> controlled123//      collections/tokens can be destroyed, resulting in massive holes124// ?2 - chain-controlled -> controlled125//      same as ?1, but can be only added, resulting in easier exploitation126// ?3 - real -> controlled127//      no confirmation required, so addresses can be easily generated128decl_storage! {129	trait Store for Module<T: Config> as Nft {130131		//#region Private members132		/// Used for migrations133		ChainVersion: u64;134		//#endregion135136		//#region Tokens transfer rate limit baskets137		/// (Collection id (controlled?2), who created (real))138		/// TODO: Off chain worker should remove from this map when collection gets removed139		pub CreateItemBasket get(fn create_item_basket): map hasher(blake2_128_concat) (CollectionId, T::AccountId) => Option<T::BlockNumber>;140		/// Collection id (controlled?2), token id (controlled?2)141		pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;142		/// Collection id (controlled?2), owning user (real)143		pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;144		/// Collection id (controlled?2), token id (controlled?2)145		pub ReFungibleTransferBasket get(fn refungible_transfer_basket): nmap hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;146		//#endregion147148		/// Variable metadata sponsoring149		/// Collection id (controlled?2), token id (controlled?2)150		pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;151		/// Approval sponsoring152		pub NftApproveBasket get(fn nft_approve_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;153		pub FungibleApproveBasket get(fn fungible_approve_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;154		pub RefungibleApproveBasket get(fn refungible_approve_basket): nmap hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;155	}156}157158decl_module! {159	pub struct Module<T: Config> for enum Call160	where161		origin: T::Origin162	{163		type Error = Error<T>;164165		fn on_initialize(_now: T::BlockNumber) -> Weight {166			0167		}168169		/// This method creates a Collection of NFTs. Each Token may have multiple properties encoded as an array of bytes of certain length. The initial owner and admin of the collection are set to the address that signed the transaction. Both addresses can be changed later.170		///171		/// # Permissions172		///173		/// * Anyone.174		///175		/// # Arguments176		///177		/// * collection_name: UTF-16 string with collection name (limit 64 characters), will be stored as zero-terminated.178		///179		/// * collection_description: UTF-16 string with collection description (limit 256 characters), will be stored as zero-terminated.180		///181		/// * token_prefix: UTF-8 string with token prefix.182		///183		/// * mode: [CollectionMode] collection type and type dependent data.184		// returns collection ID185		#[weight = <SelfWeightOf<T>>::create_collection()]186		#[transactional]187		pub fn create_collection(origin,188								 collection_name: Vec<u16>,189								 collection_description: Vec<u16>,190								 token_prefix: Vec<u8>,191								 mode: CollectionMode) -> DispatchResult {192193			// Anyone can create a collection194			let who = ensure_signed(origin)?;195196			// Create new collection197			let new_collection = Collection {198				owner: who.clone(),199				name: collection_name,200				mode: mode.clone(),201				mint_mode: false,202				access: AccessMode::Normal,203				description: collection_description,204				token_prefix,205				offchain_schema: Vec::new(),206				schema_version: SchemaVersion::ImageURL,207				sponsorship: SponsorshipState::Disabled,208				variable_on_chain_schema: Vec::new(),209				const_on_chain_schema: Vec::new(),210				limits: Default::default(),211				meta_update_permission: Default::default(),212			};213214			let _id = match mode {215				CollectionMode::NFT => {<PalletNonfungible<T>>::init_collection(new_collection)?},216				CollectionMode::Fungible(decimal_points) => {217					// check params218					ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);219					<PalletFungible<T>>::init_collection(new_collection)?220				}221				CollectionMode::ReFungible => {222					<PalletRefungible<T>>::init_collection(new_collection)?223				}224			};225226			Ok(())227		}228229		/// **DANGEROUS**: Destroys collection and all NFTs within this collection. Users irrecoverably lose their assets and may lose real money.230		///231		/// # Permissions232		///233		/// * Collection Owner.234		///235		/// # Arguments236		///237		/// * collection_id: collection to destroy.238		#[weight = <SelfWeightOf<T>>::destroy_collection()]239		#[transactional]240		pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {241			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);242243			let collection = <CollectionHandle<T>>::try_get(collection_id)?;244			collection.check_is_owner(&sender)?;245246			// =========247248			match collection.mode {249				CollectionMode::ReFungible => PalletRefungible::destroy_collection(RefungibleHandle::cast(collection), &sender)?,250				CollectionMode::Fungible(_) => PalletFungible::destroy_collection(FungibleHandle::cast(collection), &sender)?,251				CollectionMode::NFT => PalletNonfungible::destroy_collection(NonfungibleHandle::cast(collection), &sender)?,252			}253254			<NftTransferBasket<T>>::remove_prefix(collection_id, None);255			<FungibleTransferBasket<T>>::remove_prefix(collection_id, None);256			<ReFungibleTransferBasket<T>>::remove_prefix((collection_id,), None);257258			<VariableMetaDataBasket<T>>::remove_prefix(collection_id, None);259			<NftApproveBasket<T>>::remove_prefix(collection_id, None);260			<FungibleApproveBasket<T>>::remove_prefix(collection_id, None);261			<RefungibleApproveBasket<T>>::remove_prefix((collection_id,), None);262263			Ok(())264		}265266		/// Add an address to allow list.267		///268		/// # Permissions269		///270		/// * Collection Owner271		/// * Collection Admin272		///273		/// # Arguments274		///275		/// * collection_id.276		///277		/// * address.278		#[weight = <SelfWeightOf<T>>::add_to_allow_list()]279		#[transactional]280		pub fn add_to_allow_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{281282			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);283			let collection = <CollectionHandle<T>>::try_get(collection_id)?;284285			<PalletCommon<T>>::toggle_allowlist(286				&collection,287				&sender,288				&address,289				true,290			)?;291292			Ok(())293		}294295		/// Remove an address from allow list.296		///297		/// # Permissions298		///299		/// * Collection Owner300		/// * Collection Admin301		///302		/// # Arguments303		///304		/// * collection_id.305		///306		/// * address.307		#[weight = <SelfWeightOf<T>>::remove_from_allow_list()]308		#[transactional]309		pub fn remove_from_allow_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{310311			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);312			let collection = <CollectionHandle<T>>::try_get(collection_id)?;313314			<PalletCommon<T>>::toggle_allowlist(315				&collection,316				&sender,317				&address,318				false,319			)?;320321			Ok(())322		}323324		/// Toggle between normal and allow list access for the methods with access for `Anyone`.325		///326		/// # Permissions327		///328		/// * Collection Owner.329		///330		/// # Arguments331		///332		/// * collection_id.333		///334		/// * mode: [AccessMode]335		#[weight = <SelfWeightOf<T>>::set_public_access_mode()]336		#[transactional]337		pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult338		{339			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);340341			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;342			target_collection.check_is_owner(&sender)?;343344			target_collection.access = mode;345			target_collection.save()346		}347348		/// Allows Anyone to create tokens if:349		/// * Allow List is enabled, and350		/// * Address is added to allow list, and351		/// * This method was called with True parameter352		///353		/// # Permissions354		/// * Collection Owner355		///356		/// # Arguments357		///358		/// * collection_id.359		///360		/// * mint_permission: Boolean parameter. If True, allows minting to Anyone with conditions above.361		#[weight = <SelfWeightOf<T>>::set_mint_permission()]362		#[transactional]363		pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult364		{365			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);366367			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;368			target_collection.check_is_owner(&sender)?;369370			target_collection.mint_mode = mint_permission;371			target_collection.save()372		}373374		/// Change the owner of the collection.375		///376		/// # Permissions377		///378		/// * Collection Owner.379		///380		/// # Arguments381		///382		/// * collection_id.383		///384		/// * new_owner.385		#[weight = <SelfWeightOf<T>>::change_collection_owner()]386		#[transactional]387		pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {388389			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);390391			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;392			target_collection.check_is_owner(&sender)?;393394			target_collection.owner = new_owner;395			target_collection.save()396		}397398		/// Adds an admin of the Collection.399		/// NFT Collection can be controlled by multiple admin addresses (some which can also be servers, for example). Admins can issue and burn NFTs, as well as add and remove other admins, but cannot change NFT or Collection ownership.400		///401		/// # Permissions402		///403		/// * Collection Owner.404		/// * Collection Admin.405		///406		/// # Arguments407		///408		/// * collection_id: ID of the Collection to add admin for.409		///410		/// * new_admin_id: Address of new admin to add.411		#[weight = <SelfWeightOf<T>>::add_collection_admin()]412		#[transactional]413		pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::CrossAccountId) -> DispatchResult {414			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);415			let collection = <CollectionHandle<T>>::try_get(collection_id)?;416417			<PalletCommon<T>>::toggle_admin(&collection, &sender, &new_admin_id, true)418		}419420		/// Remove admin address of the Collection. An admin address can remove itself. List of admins may become empty, in which case only Collection Owner will be able to add an Admin.421		///422		/// # Permissions423		///424		/// * Collection Owner.425		/// * Collection Admin.426		///427		/// # Arguments428		///429		/// * collection_id: ID of the Collection to remove admin for.430		///431		/// * account_id: Address of admin to remove.432		#[weight = <SelfWeightOf<T>>::remove_collection_admin()]433		#[transactional]434		pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::CrossAccountId) -> DispatchResult {435			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);436			let collection = <CollectionHandle<T>>::try_get(collection_id)?;437438			<PalletCommon<T>>::toggle_admin(&collection, &sender, &account_id, false)439		}440441		/// # Permissions442		///443		/// * Collection Owner444		///445		/// # Arguments446		///447		/// * collection_id.448		///449		/// * new_sponsor.450		#[weight = <SelfWeightOf<T>>::set_collection_sponsor()]451		#[transactional]452		pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {453			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);454455			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;456			target_collection.check_is_owner(&sender)?;457458			target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor);459			target_collection.save()460		}461462		/// # Permissions463		///464		/// * Sponsor.465		///466		/// # Arguments467		///468		/// * collection_id.469		#[weight = <SelfWeightOf<T>>::confirm_sponsorship()]470		#[transactional]471		pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {472			let sender = ensure_signed(origin)?;473474			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;475			ensure!(476				target_collection.sponsorship.pending_sponsor() == Some(&sender),477				Error::<T>::ConfirmUnsetSponsorFail478			);479480			target_collection.sponsorship = SponsorshipState::Confirmed(sender);481			target_collection.save()482		}483484		/// Switch back to pay-per-own-transaction model.485		///486		/// # Permissions487		///488		/// * Collection owner.489		///490		/// # Arguments491		///492		/// * collection_id.493		#[weight = <SelfWeightOf<T>>::remove_collection_sponsor()]494		#[transactional]495		pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {496			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);497498			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;499			target_collection.check_is_owner(&sender)?;500501			target_collection.sponsorship = SponsorshipState::Disabled;502			target_collection.save()503		}504505		/// This method creates a concrete instance of NFT Collection created with CreateCollection method.506		///507		/// # Permissions508		///509		/// * Collection Owner.510		/// * Collection Admin.511		/// * Anyone if512		///     * Allow List is enabled, and513		///     * Address is added to allow list, and514		///     * MintPermission is enabled (see SetMintPermission method)515		///516		/// # Arguments517		///518		/// * collection_id: ID of the collection.519		///520		/// * owner: Address, initial owner of the NFT.521		///522		/// * data: Token data to store on chain.523		#[weight = <CommonWeights<T>>::create_item()]524		#[transactional]525		pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResultWithPostInfo {526			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);527528			dispatch_call::<T, _>(collection_id, |d| d.create_item(sender, owner, data))529		}530531		/// This method creates multiple items in a collection created with CreateCollection method.532		///533		/// # Permissions534		///535		/// * Collection Owner.536		/// * Collection Admin.537		/// * Anyone if538		///     * Allow List is enabled, and539		///     * Address is added to allow list, and540		///     * MintPermission is enabled (see SetMintPermission method)541		///542		/// # Arguments543		///544		/// * collection_id: ID of the collection.545		///546		/// * itemsData: Array items properties. Each property is an array of bytes itself, see [create_item].547		///548		/// * owner: Address, initial owner of the NFT.549		#[weight = <CommonWeights<T>>::create_multiple_items(items_data.len() as u32)]550		#[transactional]551		pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResultWithPostInfo {552			ensure!(!items_data.is_empty(), Error::<T>::EmptyArgument);553			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);554555			dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items(sender, owner, items_data))556		}557558		// TODO! transaction weight559560		/// Set transfers_enabled value for particular collection561		///562		/// # Permissions563		///564		/// * Collection Owner.565		///566		/// # Arguments567		///568		/// * collection_id: ID of the collection.569		///570		/// * value: New flag value.571		#[weight = <SelfWeightOf<T>>::set_transfers_enabled_flag()]572		#[transactional]573		pub fn set_transfers_enabled_flag(origin, collection_id: CollectionId, value: bool) -> DispatchResult {574			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);575			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;576			target_collection.check_is_owner(&sender)?;577578			// =========579580			target_collection.limits.transfers_enabled = Some(value);581			target_collection.save()582		}583584		/// Destroys a concrete instance of NFT.585		///586		/// # Permissions587		///588		/// * Collection Owner.589		/// * Collection Admin.590		/// * Current NFT Owner.591		///592		/// # Arguments593		///594		/// * collection_id: ID of the collection.595		///596		/// * item_id: ID of NFT to burn.597		#[weight = <CommonWeights<T>>::burn_item()]598		#[transactional]599		pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {600			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);601602			let post_info = dispatch_call::<T, _>(collection_id, |d| d.burn_item(sender, item_id, value))?;603			if value == 1 {604				<NftTransferBasket<T>>::remove(collection_id, item_id);605				<NftApproveBasket<T>>::remove(collection_id, item_id);606			}607			// Those maps should be cleared only if token disappears completly, need to move this part of logic to pallets?608			// <FungibleApproveBasket<T>>::remove(collection_id, sender.as_sub());609			// <RefungibleApproveBasket<T>>::remove((collection_id, item_id, sender.as_sub()));610			Ok(post_info)611		}612613		/// Destroys a concrete instance of NFT on behalf of the owner614		/// See also: [`approve`]615		///616		/// # Permissions617		///618		/// * Collection Owner.619		/// * Collection Admin.620		/// * Current NFT Owner.621		///622		/// # Arguments623		///624		/// * collection_id: ID of the collection.625		///626		/// * item_id: ID of NFT to burn.627		///628		/// * from: owner of item629		#[weight = <CommonWeights<T>>::burn_from()]630		#[transactional]631		pub fn burn_from(origin, collection_id: CollectionId, from: T::CrossAccountId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {632			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);633634			dispatch_call::<T, _>(collection_id, |d| d.burn_from(sender, from, item_id, value))635		}636637		/// Change ownership of the token.638		///639		/// # Permissions640		///641		/// * Collection Owner642		/// * Collection Admin643		/// * Current NFT owner644		///645		/// # Arguments646		///647		/// * recipient: Address of token recipient.648		///649		/// * collection_id.650		///651		/// * item_id: ID of the item652		///     * Non-Fungible Mode: Required.653		///     * Fungible Mode: Ignored.654		///     * Re-Fungible Mode: Required.655		///656		/// * value: Amount to transfer.657		///     * Non-Fungible Mode: Ignored658		///     * Fungible Mode: Must specify transferred amount659		///     * Re-Fungible Mode: Must specify transferred portion (between 0 and 1)660		#[weight = <CommonWeights<T>>::transfer()]661		#[transactional]662		pub fn transfer(origin, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {663			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);664665			dispatch_call::<T, _>(collection_id, |d| d.transfer(sender, recipient, item_id, value))666		}667668		/// Set, change, or remove approved address to transfer the ownership of the NFT.669		///670		/// # Permissions671		///672		/// * Collection Owner673		/// * Collection Admin674		/// * Current NFT owner675		///676		/// # Arguments677		///678		/// * approved: Address that is approved to transfer this NFT or zero (if needed to remove approval).679		///680		/// * collection_id.681		///682		/// * item_id: ID of the item.683		#[weight = <CommonWeights<T>>::approve()]684		#[transactional]685		pub fn approve(origin, spender: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResultWithPostInfo {686			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);687688			dispatch_call::<T, _>(collection_id, |d| d.approve(sender, spender, item_id, amount))689		}690691		/// Change ownership of a NFT on behalf of the owner. See Approve method for additional information. After this method executes, the approval is removed so that the approved address will not be able to transfer this NFT again from this owner.692		///693		/// # Permissions694		/// * Collection Owner695		/// * Collection Admin696		/// * Current NFT owner697		/// * Address approved by current NFT owner698		///699		/// # Arguments700		///701		/// * from: Address that owns token.702		///703		/// * recipient: Address of token recipient.704		///705		/// * collection_id.706		///707		/// * item_id: ID of the item.708		///709		/// * value: Amount to transfer.710		#[weight = <CommonWeights<T>>::transfer_from()]711		#[transactional]712		pub fn transfer_from(origin, from: T::CrossAccountId, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResultWithPostInfo {713			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);714715			dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value))716		}717718		/// Set off-chain data schema.719		///720		/// # Permissions721		///722		/// * Collection Owner723		/// * Collection Admin724		///725		/// # Arguments726		///727		/// * collection_id.728		///729		/// * schema: String representing the offchain data schema.730		#[weight = <CommonWeights<T>>::set_variable_metadata(data.len() as u32)]731		#[transactional]732		pub fn set_variable_meta_data (733			origin,734			collection_id: CollectionId,735			item_id: TokenId,736			data: Vec<u8>737		) -> DispatchResultWithPostInfo {738			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);739740			dispatch_call::<T, _>(collection_id, |d| d.set_variable_metadata(sender, item_id, data))741		}742743		/// Set meta_update_permission value for particular collection744		///745		/// # Permissions746		///747		/// * Collection Owner.748		///749		/// # Arguments750		///751		/// * collection_id: ID of the collection.752		///753		/// * value: New flag value.754		#[weight = <SelfWeightOf<T>>::set_meta_update_permission_flag()]755		#[transactional]756		pub fn set_meta_update_permission_flag(origin, collection_id: CollectionId, value: MetaUpdatePermission) -> DispatchResult {757			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);758			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;759760			ensure!(761				target_collection.meta_update_permission != MetaUpdatePermission::None,762				<CommonError<T>>::MetadataFlagFrozen,763			);764			target_collection.check_is_owner(&sender)?;765766			target_collection.meta_update_permission = value;767768			target_collection.save()769		}770771		/// Set schema standard772		/// ImageURL773		/// Unique774		///775		/// # Permissions776		///777		/// * Collection Owner778		/// * Collection Admin779		///780		/// # Arguments781		///782		/// * collection_id.783		///784		/// * schema: SchemaVersion: enum785		#[weight = <SelfWeightOf<T>>::set_schema_version()]786		#[transactional]787		pub fn set_schema_version(788			origin,789			collection_id: CollectionId,790			version: SchemaVersion791		) -> DispatchResult {792			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);793			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;794			target_collection.check_is_owner_or_admin(&sender)?;795			target_collection.schema_version = version;796			target_collection.save()797		}798799		/// Set off-chain data schema.800		///801		/// # Permissions802		///803		/// * Collection Owner804		/// * Collection Admin805		///806		/// # Arguments807		///808		/// * collection_id.809		///810		/// * schema: String representing the offchain data schema.811		#[weight = <SelfWeightOf<T>>::set_offchain_schema(schema.len() as u32)]812		#[transactional]813		pub fn set_offchain_schema(814			origin,815			collection_id: CollectionId,816			schema: Vec<u8>817		) -> DispatchResult {818			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);819			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;820			target_collection.check_is_owner_or_admin(&sender)?;821822			// check schema limit823			ensure!(schema.len() as u32 <= OFFCHAIN_SCHEMA_LIMIT, "");824825			target_collection.offchain_schema = schema;826			target_collection.save()827		}828829		/// Set const on-chain data schema.830		///831		/// # Permissions832		///833		/// * Collection Owner834		/// * Collection Admin835		///836		/// # Arguments837		///838		/// * collection_id.839		///840		/// * schema: String representing the const on-chain data schema.841		#[weight = <SelfWeightOf<T>>::set_const_on_chain_schema(schema.len() as u32)]842		#[transactional]843		pub fn set_const_on_chain_schema (844			origin,845			collection_id: CollectionId,846			schema: Vec<u8>847		) -> DispatchResult {848			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);849			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;850			target_collection.check_is_owner_or_admin(&sender)?;851852			// check schema limit853			ensure!(schema.len() as u32 <= CONST_ON_CHAIN_SCHEMA_LIMIT, "");854855			target_collection.const_on_chain_schema = schema;856			target_collection.save()857		}858859		/// Set variable on-chain data schema.860		///861		/// # Permissions862		///863		/// * Collection Owner864		/// * Collection Admin865		///866		/// # Arguments867		///868		/// * collection_id.869		///870		/// * schema: String representing the variable on-chain data schema.871		#[weight = <SelfWeightOf<T>>::set_const_on_chain_schema(schema.len() as u32)]872		#[transactional]873		pub fn set_variable_on_chain_schema (874			origin,875			collection_id: CollectionId,876			schema: Vec<u8>877		) -> DispatchResult {878			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);879			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;880			target_collection.check_is_owner_or_admin(&sender)?;881882			// check schema limit883			ensure!(schema.len() as u32 <= VARIABLE_ON_CHAIN_SCHEMA_LIMIT, "");884885			target_collection.variable_on_chain_schema = schema;886			target_collection.save()887		}888889		#[weight = <SelfWeightOf<T>>::set_collection_limits()]890		#[transactional]891		pub fn set_collection_limits(892			origin,893			collection_id: CollectionId,894			new_limit: CollectionLimits,895		) -> DispatchResult {896			let mut new_limit = new_limit;897			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);898			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;899			target_collection.check_is_owner(&sender)?;900			let old_limit = &target_collection.limits;901902			macro_rules! limit_default {903				($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{904					$(905						if let Some($new) = $new.$field {906							let $old = $old.$field($($arg)?);907							let _ = $new;908							let _ = $old;909							$check910						} else {911							$new.$field = $old.$field912						}913					)*914				}};915			}916917			limit_default!(old_limit, new_limit,918				account_token_ownership_limit => ensure!(919					new_limit <= MAX_TOKEN_OWNERSHIP,920					<Error<T>>::CollectionLimitBoundsExceeded,921				),922				sponsor_transfer_timeout(match target_collection.mode {923					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,924					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,925					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,926				}) => ensure!(927					new_limit <= MAX_SPONSOR_TIMEOUT,928					<Error<T>>::CollectionLimitBoundsExceeded,929				),930				sponsored_data_size => ensure!(931					new_limit <= CUSTOM_DATA_LIMIT,932					<Error<T>>::CollectionLimitBoundsExceeded,933				),934				token_limit => ensure!(935					old_limit >= new_limit && new_limit > 0,936					<CommonError<T>>::CollectionTokenLimitExceeded937				),938				owner_can_transfer => ensure!(939					old_limit || !new_limit,940					<Error<T>>::OwnerPermissionsCantBeReverted,941				),942				owner_can_destroy => ensure!(943					old_limit || !new_limit,944					<Error<T>>::OwnerPermissionsCantBeReverted,945				),946				sponsored_data_rate_limit => {},947				transfers_enabled => {},948			);949950			target_collection.limits = new_limit;951952			target_collection.save()953		}954	}955}
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
@@ -209,8 +209,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
@@ -219,7 +219,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>,    //
@@ -424,3 +424,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
@@ -1045,14 +1045,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,
   transferFromExpectSuccess,
   transferFromExpectFail,
 } from './util/helpers';
@@ -411,13 +412,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';
@@ -330,7 +331,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/creditFeesToTreasury.test.tsdiffbeforeafterboth
--- a/tests/src/creditFeesToTreasury.test.ts
+++ b/tests/src/creditFeesToTreasury.test.ts
@@ -14,6 +14,7 @@
   createItemExpectSuccess,
   getGenericResult,
   transferExpectSuccess,
+  UNIQUE,
 } from './util/helpers';
 
 import {default as waitNewBlocks} from './substrate/wait-new-blocks';
@@ -169,12 +170,11 @@
       const aliceBalanceBefore: bigint = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();
       await transferExpectSuccess(collectionId, tokenId, alice, bob, 1, 'NFT');
       const aliceBalanceAfter: bigint = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();
-      const fee = aliceBalanceBefore - aliceBalanceAfter;
+      const fee = Number(aliceBalanceBefore - aliceBalanceAfter) / Number(UNIQUE);
 
-      // console.log(fee.toString());
       const expectedTransferFee = 0.1;
       const tolerance = 0.001;
-      expect(Number(fee) / 1e15 - expectedTransferFee).to.be.lessThan(tolerance);
+      expect(Number(fee) / Number(UNIQUE) - expectedTransferFee).to.be.lessThan(tolerance);
     });
   });
 
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,
   toSubstrateAddress,
   getTokenOwner,
   normalizeAccountId,
@@ -136,13 +137,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;
@@ -1058,7 +1058,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
@@ -1106,7 +1106,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);
   });
@@ -1138,15 +1138,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));
@@ -1154,14 +1152,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));
@@ -1169,7 +1167,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;
   });
 }
 
@@ -1215,16 +1213,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> {