git.delta.rocks / unique-network / refs/commits / 9836c2113849

difftreelog

Merge branch 'develop' into feature/internal-audit

Igor Kozyrev2021-11-23parents: #6a168a1 #bba462e.patch.diff
in: master

57 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
modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5097,6 +5097,7 @@
  "frame-system-rpc-runtime-api",
  "hex-literal",
  "nft-data-structs",
+ "orml-vesting",
  "pallet-aura",
  "pallet-balances",
  "pallet-common",
@@ -5109,7 +5110,6 @@
  "pallet-fungible",
  "pallet-inflation",
  "pallet-nft",
- "pallet-nft-transaction-payment",
  "pallet-nonfungible",
  "pallet-randomness-collective-flip",
  "pallet-refungible",
@@ -5120,7 +5120,6 @@
  "pallet-transaction-payment-rpc-runtime-api",
  "pallet-treasury",
  "pallet-unq-scheduler",
- "pallet-vesting",
  "pallet-xcm",
  "parachain-info",
  "parity-scale-codec",
@@ -5142,6 +5141,7 @@
  "sp-transaction-pool",
  "sp-version",
  "substrate-wasm-builder",
+ "up-evm-mapping",
  "up-rpc",
  "xcm",
  "xcm-builder",
@@ -5308,6 +5308,21 @@
 ]
 
 [[package]]
+name = "orml-vesting"
+version = "0.4.1-dev"
+source = "git+https://github.com/UniqueNetwork/open-runtime-module-library#d69f226e332ae29b7b33d53d2f06f309d2986ea0"
+dependencies = [
+ "frame-support",
+ "frame-system",
+ "parity-scale-codec",
+ "scale-info",
+ "serde",
+ "sp-io",
+ "sp-runtime",
+ "sp-std",
+]
+
+[[package]]
 name = "owning_ref"
 version = "0.4.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -5575,6 +5590,7 @@
  "sp-core",
  "sp-runtime",
  "sp-std",
+ "up-evm-mapping",
 ]
 
 [[package]]
@@ -5824,6 +5840,7 @@
  "sp-io",
  "sp-runtime",
  "sp-std",
+ "up-evm-mapping",
  "up-sponsorship",
 ]
 
@@ -6072,24 +6089,7 @@
  "sp-io",
  "sp-runtime",
  "sp-std",
- "up-sponsorship",
-]
-
-[[package]]
-name = "pallet-nft-transaction-payment"
-version = "3.0.0"
-dependencies = [
- "frame-benchmarking",
- "frame-support",
- "frame-system",
- "pallet-transaction-payment",
- "parity-scale-codec",
- "scale-info",
- "serde",
- "sp-core",
- "sp-io",
- "sp-runtime",
- "sp-std",
+ "up-evm-mapping",
  "up-sponsorship",
 ]
 
@@ -11832,6 +11832,14 @@
 checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a"
 
 [[package]]
+name = "up-evm-mapping"
+version = "0.1.0"
+dependencies = [
+ "frame-support",
+ "sp-core",
+]
+
+[[package]]
 name = "up-rpc"
 version = "0.1.0"
 dependencies = [
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/Cargo.tomldiffbeforeafterboth
--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -15,10 +15,10 @@
 sp-runtime = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
 sp-std = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
 sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+up-evm-mapping = { default-features = false, path = '../../primitives/evm-mapping' }
 nft-data-structs = { default-features = false, path = '../../primitives/nft' }
 pallet-evm-coder-substrate = { default-features = false, path = '../../pallets/evm-coder-substrate' }
 evm-coder = { default-features = false, path = '../../crates/evm-coder' }
-
 pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
 serde = { version = "1.0.130", default-features = false }
 scale-info = { version = "1.0.0", default-features = false, features = [
@@ -32,6 +32,7 @@
     "frame-system/std",
     "sp-runtime/std",
     "sp-std/std",
+    "up-evm-mapping/std",
     "nft-data-structs/std",
     "pallet-evm/std",
 ]
modifiedpallets/common/src/account.rsdiffbeforeafterboth
--- a/pallets/common/src/account.rs
+++ b/pallets/common/src/account.rs
@@ -2,12 +2,12 @@
 use codec::{Encode, EncodeLike, Decode};
 use sp_core::H160;
 use scale_info::{Type, TypeInfo};
-use sp_core::crypto::AccountId32;
 use core::cmp::Ordering;
 use serde::{Serialize, Deserialize};
 use pallet_evm::AddressMapping;
 use sp_std::vec::Vec;
 use sp_std::clone::Clone;
+use up_evm_mapping::EvmBackwardsAddressMapping;
 
 pub trait CrossAccountId<AccountId>:
 	Encode + EncodeLike + Decode + TypeInfo + Clone + PartialEq + Ord + core::fmt::Debug + Default
@@ -174,19 +174,5 @@
 		} else {
 			BasicCrossAccountIdRepr::Substrate(v.as_sub().clone())
 		}
-	}
-}
-
-pub trait EvmBackwardsAddressMapping<AccountId> {
-	fn from_account_id(account_id: AccountId) -> H160;
-}
-
-/// Should have same mapping as EnsureAddressTruncated
-pub struct MapBackwardsAddressTruncated;
-impl EvmBackwardsAddressMapping<AccountId32> for MapBackwardsAddressTruncated {
-	fn from_account_id(account_id: AccountId32) -> H160 {
-		let mut out = [0; 20];
-		out.copy_from_slice(&(account_id.as_ref() as &[u8])[0..20]);
-		H160(out)
 	}
 }
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
@@ -141,7 +141,7 @@
 pub mod pallet {
 	use super::*;
 	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key};
-	use account::{EvmBackwardsAddressMapping, CrossAccountId};
+	use account::CrossAccountId;
 	use frame_support::traits::Currency;
 	use nft_data_structs::TokenId;
 	use scale_info::TypeInfo;
@@ -153,7 +153,7 @@
 		type CrossAccountId: CrossAccountId<Self::AccountId>;
 
 		type EvmAddressMapping: pallet_evm::AddressMapping<Self::AccountId>;
-		type EvmBackwardsAddressMapping: EvmBackwardsAddressMapping<Self::AccountId>;
+		type EvmBackwardsAddressMapping: up_evm_mapping::EvmBackwardsAddressMapping<Self::AccountId>;
 
 		type Currency: Currency<Self::AccountId>;
 		type CollectionCreationPrice: Get<
@@ -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/evm-contract-helpers/src/eth.rsdiffbeforeafterboth
--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -59,7 +59,8 @@
 
 	fn allowed(&self, contract_address: address, user: address) -> Result<bool> {
 		self.0.consume_sload()?;
-		Ok(<Pallet<T>>::allowed(contract_address, user, true))
+		Ok(<Pallet<T>>::allowed(contract_address, user)
+			|| !<AllowlistEnabled<T>>::get(contract_address))
 	}
 
 	fn allowlist_enabled(&self, contract_address: address) -> Result<bool> {
@@ -113,7 +114,7 @@
 		value: sp_core::U256,
 	) -> Option<PrecompileOutput> {
 		// TODO: Extract to another OnMethodCall handler
-		if !<Pallet<T>>::allowed(*target, *source, true) {
+		if <AllowlistEnabled<T>>::get(target) && !<Pallet<T>>::allowed(*target, *source) {
 			return Some(PrecompileOutput {
 				exit_status: ExitReason::Revert(ExitRevert::Reverted),
 				cost: 0,
@@ -151,22 +152,26 @@
 pub struct HelpersContractSponsoring<T: Config>(PhantomData<*const T>);
 impl<T: Config> SponsorshipHandler<H160, (H160, Vec<u8>)> for HelpersContractSponsoring<T> {
 	fn get_sponsor(who: &H160, call: &(H160, Vec<u8>)) -> Option<H160> {
-		if <SelfSponsoring<T>>::get(&call.0) && <Pallet<T>>::allowed(call.0, *who, false) {
-			let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
-			if let Some(last_tx_block) = <SponsorBasket<T>>::get(&call.0, who) {
-				let rate_limit = <SponsoringRateLimit<T>>::get(&call.0);
-				let limit_time = last_tx_block + rate_limit;
+		if !<SelfSponsoring<T>>::get(&call.0) {
+			return None;
+		}
+		if !<Pallet<T>>::allowed(call.0, *who) {
+			return None;
+		}
+		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
 
-				if block_number > limit_time {
-					<SponsorBasket<T>>::insert(&call.0, who, block_number);
-					return Some(call.0);
-				}
-			} else {
-				<SponsorBasket<T>>::insert(&call.0, who, block_number);
-				return Some(call.0);
+		if let Some(last_tx_block) = <SponsorBasket<T>>::get(&call.0, who) {
+			let limit = <SponsoringRateLimit<T>>::get(&call.0);
+
+			let timeout = last_tx_block + limit.into();
+			if block_number < timeout {
+				return None;
 			}
 		}
-		None
+
+		<SponsorBasket<T>>::insert(&call.0, who, block_number);
+
+		Some(call.0)
 	}
 }
 
modifiedpallets/evm-contract-helpers/src/lib.rsdiffbeforeafterboth
--- a/pallets/evm-contract-helpers/src/lib.rs
+++ b/pallets/evm-contract-helpers/src/lib.rs
@@ -76,11 +76,7 @@
 			<SponsoringRateLimit<T>>::insert(contract, rate_limit);
 		}
 
-		/// Default is returned if allowlist is disabled
-		pub fn allowed(contract: H160, user: H160, default: bool) -> bool {
-			if !<AllowlistEnabled<T>>::get(contract) {
-				return default;
-			}
+		pub fn allowed(contract: H160, user: H160) -> bool {
 			<Allowlist<T>>::get(&contract, &user) || <Owner<T>>::get(&contract) == user
 		}
 
modifiedpallets/evm-transaction-payment/Cargo.tomldiffbeforeafterboth
--- a/pallets/evm-transaction-payment/Cargo.toml
+++ b/pallets/evm-transaction-payment/Cargo.toml
@@ -15,6 +15,7 @@
 fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
 pallet-ethereum = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.12" }
 up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/UniqueNetwork/pallet-sponsoring" } 
+up-evm-mapping = { default-features = false, path = "../../primitives/evm-mapping" }
 
 [dependencies.codec]
 default-features = false
@@ -35,4 +36,5 @@
     "pallet-ethereum/std",
     "fp-evm/std",
     "up-sponsorship/std",
+    "up-evm-mapping/std",
 ]
modifiedpallets/evm-transaction-payment/src/lib.rsdiffbeforeafterboth
--- a/pallets/evm-transaction-payment/src/lib.rs
+++ b/pallets/evm-transaction-payment/src/lib.rs
@@ -1,98 +1,140 @@
 #![cfg_attr(not(feature = "std"), no_std)]
 
+use core::marker::PhantomData;
+use fp_evm::WithdrawReason;
+use frame_support::traits::{Currency, IsSubType};
 pub use pallet::*;
+use pallet_evm::{EVMCurrencyAdapter, EnsureAddressOrigin};
+use sp_core::{H160, U256};
+use sp_runtime::TransactionOutcome;
+use up_sponsorship::SponsorshipHandler;
+use up_evm_mapping::EvmBackwardsAddressMapping;
+use pallet_evm::AddressMapping;
 
 #[frame_support::pallet]
 pub mod pallet {
-	use core::marker::PhantomData;
+	use super::*;
+
 	use frame_support::traits::Currency;
-	use pallet_evm::EVMCurrencyAdapter;
-	use fp_evm::WithdrawReason;
-	use sp_core::{H160, U256};
-	use sp_runtime::TransactionOutcome;
-	use up_sponsorship::SponsorshipHandler;
 	use sp_std::vec::Vec;
 
-	type NegativeImbalanceOf<C, T> =
-		<C as Currency<<T as frame_system::Config>::AccountId>>::NegativeImbalance;
-
 	#[pallet::config]
 	pub trait Config: frame_system::Config {
-		type SponsorshipHandler: SponsorshipHandler<H160, (H160, Vec<u8>)>;
+		type EvmSponsorshipHandler: SponsorshipHandler<H160, (H160, Vec<u8>)>;
 		type Currency: Currency<Self::AccountId>;
+		type EvmBackwardsAddressMapping: EvmBackwardsAddressMapping<Self::AccountId>;
+		type EvmAddressMapping: AddressMapping<Self::AccountId>;
 	}
 
 	#[pallet::pallet]
 	#[pallet::generate_store(pub(super) trait Store)]
 	pub struct Pallet<T>(_);
+}
 
-	pub struct ChargeEvmLiquidityInfo<T>
-	where
-		T: Config,
-		T: pallet_evm::Config,
-	{
-		who: H160,
-		negative_imbalance: NegativeImbalanceOf<<T as Config>::Currency, T>,
-	}
+type NegativeImbalanceOf<C, T> =
+	<C as Currency<<T as frame_system::Config>::AccountId>>::NegativeImbalance;
 
-	pub struct TransactionValidityHack<T: Config>(PhantomData<*const T>);
-	impl<T: Config> fp_evm::TransactionValidityHack for TransactionValidityHack<T> {
-		fn who_pays_fee(origin: H160, reason: &WithdrawReason) -> Option<H160> {
-			match reason {
-				WithdrawReason::Call { target, input } => {
-					// This method is only used for checking, we shouldn't touch storage in it
-					frame_support::storage::with_transaction(|| {
-						TransactionOutcome::Rollback(T::SponsorshipHandler::get_sponsor(
-							&origin,
-							&(*target, input.clone()),
-						))
-					})
-				}
-				_ => None,
+pub struct ChargeEvmLiquidityInfo<T>
+where
+	T: Config,
+	T: pallet_evm::Config,
+{
+	who: H160,
+	negative_imbalance: NegativeImbalanceOf<<T as Config>::Currency, T>,
+}
+
+pub struct TransactionValidityHack<T: Config>(PhantomData<*const T>);
+impl<T: Config> fp_evm::TransactionValidityHack for TransactionValidityHack<T> {
+	fn who_pays_fee(origin: H160, reason: &WithdrawReason) -> Option<H160> {
+		match reason {
+			WithdrawReason::Call { target, input } => {
+				// This method is only used for checking, we shouldn't touch storage in it
+				frame_support::storage::with_transaction(|| {
+					TransactionOutcome::Rollback(T::EvmSponsorshipHandler::get_sponsor(
+						&origin,
+						&(*target, input.clone()),
+					))
+				})
 			}
+			_ => None,
+		}
+	}
+}
+pub struct OnChargeTransaction<T: Config>(PhantomData<*const T>);
+impl<T> pallet_evm::OnChargeEVMTransaction<T> for OnChargeTransaction<T>
+where
+	T: Config,
+	T: pallet_evm::Config,
+{
+	type LiquidityInfo = Option<ChargeEvmLiquidityInfo<T>>;
+
+	fn withdraw_fee(
+		who: &H160,
+		reason: WithdrawReason,
+		fee: U256,
+	) -> core::result::Result<Self::LiquidityInfo, pallet_evm::Error<T>> {
+		let mut who_pays_fee = *who;
+		if let WithdrawReason::Call { target, input } = &reason {
+			who_pays_fee = T::EvmSponsorshipHandler::get_sponsor(who, &(*target, input.clone()))
+				.unwrap_or(who_pays_fee);
 		}
+		let negative_imbalance = EVMCurrencyAdapter::<<T as Config>::Currency, ()>::withdraw_fee(
+			&who_pays_fee,
+			reason,
+			fee,
+		)?;
+		Ok(negative_imbalance.map(|i| ChargeEvmLiquidityInfo {
+			who: who_pays_fee,
+			negative_imbalance: i,
+		}))
 	}
 
-	pub struct OnChargeTransaction<T: Config>(PhantomData<*const T>);
-	impl<T> pallet_evm::OnChargeEVMTransaction<T> for OnChargeTransaction<T>
-	where
-		T: Config,
-		T: pallet_evm::Config,
-	{
-		type LiquidityInfo = Option<ChargeEvmLiquidityInfo<T>>;
+	fn correct_and_deposit_fee(
+		who: &H160,
+		corrected_fee: U256,
+		already_withdrawn: Self::LiquidityInfo,
+	) {
+		<EVMCurrencyAdapter<<T as Config>::Currency, ()> as pallet_evm::OnChargeEVMTransaction<T>>::correct_and_deposit_fee(
+			&already_withdrawn.as_ref().map(|e| e.who).unwrap_or(*who),
+			corrected_fee,
+			already_withdrawn.map(|e| e.negative_imbalance),
+		)
+	}
+}
 
-		fn withdraw_fee(
-			who: &H160,
-			reason: WithdrawReason,
-			fee: U256,
-		) -> core::result::Result<Self::LiquidityInfo, pallet_evm::Error<T>> {
-			let mut who_pays_fee = *who;
-			if let WithdrawReason::Call { target, input } = &reason {
-				who_pays_fee = T::SponsorshipHandler::get_sponsor(who, &(*target, input.clone()))
-					.unwrap_or(who_pays_fee);
+/// Implements sponsoring for evm calls performed from pallet-evm (via api.tx.ethereum.transact/api.tx.evm.call)
+pub struct BridgeSponsorshipHandler<T>(PhantomData<T>);
+impl<T, C> SponsorshipHandler<T::AccountId, C> for BridgeSponsorshipHandler<T>
+where
+	T: Config + pallet_evm::Config,
+	C: IsSubType<pallet_evm::Call<T>>,
+{
+	fn get_sponsor(who: &T::AccountId, call: &C) -> Option<T::AccountId> {
+		match call.is_sub_type()? {
+			pallet_evm::Call::call {
+				source,
+				target,
+				input,
+				..
+			} => {
+				let _ = T::CallOrigin::ensure_address_origin(
+					source,
+					<frame_system::RawOrigin<T::AccountId>>::Signed(who.clone()).into(),
+				)
+				.ok()?;
+				let who = T::EvmBackwardsAddressMapping::from_account_id(who.clone());
+				// Effects from EvmSponsorshipHandler are applied in OnChargeEvmTransaction by pallet_evm::runner
+				// TODO: Should we implement simulation mode (test, but do not apply effects) in `up-sponsorship`?
+				let sponsor = frame_support::storage::with_transaction(|| {
+					TransactionOutcome::Rollback(T::EvmSponsorshipHandler::get_sponsor(
+						&who,
+						&(target.clone(), input.clone()),
+					))
+				})?;
+				let sponsor = T::EvmAddressMapping::into_account_id(sponsor);
+				Some(sponsor)
 			}
-			let negative_imbalance =
-				EVMCurrencyAdapter::<<T as Config>::Currency, ()>::withdraw_fee(
-					&who_pays_fee,
-					reason,
-					fee,
-				)?;
-			Ok(negative_imbalance.map(|i| ChargeEvmLiquidityInfo {
-				who: who_pays_fee,
-				negative_imbalance: i,
-			}))
-		}
-
-		fn correct_and_deposit_fee(
-			who: &H160,
-			corrected_fee: U256,
-			already_withdrawn: Self::LiquidityInfo,
-		) {
-			<EVMCurrencyAdapter<<T as Config>::Currency, ()> as pallet_evm::OnChargeEVMTransaction<T>>::correct_and_deposit_fee(
-				&already_withdrawn.as_ref().map(|e| e.who).unwrap_or(*who),
-				corrected_fee,
-				already_withdrawn.map(|e| e.negative_imbalance),
-			)
+			_ => None,
 		}
 	}
 }
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -52,7 +52,7 @@
 		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;
 
 	#[pallet::storage]
-	pub(super) type Balance<T: Config> = StorageNMap<
+	pub type Balance<T: Config> = StorageNMap<
 		Key = (
 			Key<Twox64Concat, CollectionId>,
 			Key<Blake2_128Concat, T::CrossAccountId>,
@@ -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>,
deletedpallets/nft-transaction-payment/Cargo.tomldiffbeforeafterboth
--- a/pallets/nft-transaction-payment/Cargo.toml
+++ /dev/null
@@ -1,51 +0,0 @@
-[package]
-authors = ['Substrate DevHub <https://github.com/substrate-developer-hub>']
-description = 'Unqiue pallet nft specific transaction payment'
-edition = '2018'
-homepage = 'https://substrate.io'
-license = 'Unlicense'
-name = 'pallet-nft-transaction-payment'
-repository = 'https://github.com/usetech-llc/nft_private/'
-version = '3.0.0'
-
-[package.metadata.docs.rs]
-targets = ['x86_64-unknown-linux-gnu']
-
-# alias "parity-scale-code" to "codec"
-[dependencies.codec]
-default-features = false
-features = ['derive']
-package = 'parity-scale-codec'
-version = '2.3.0'
-
-[dependencies]
-scale-info = { version = "1.0.0", default-features = false, features = ["derive"] }
-serde = { version = "1.0.130", default-features = false }
-frame-support = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
-frame-system = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
-pallet-transaction-payment = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
-sp-std = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
-frame-benchmarking = { default-features = false, optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
-sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
-sp-io = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
-sp-runtime = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
-
-up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/UniqueNetwork/pallet-sponsoring" } 
-
-[features]
-default = ['std']
-std = [
-    'codec/std',
-    'serde/std',
-    'frame-support/std',
-    'frame-system/std',
-    'sp-core/std',
-    'sp-io/std',
-    'pallet-transaction-payment/std',
-    'sp-std/std',
-    'sp-runtime/std',
-    'frame-benchmarking/std',
-
-    'up-sponsorship/std',
-]
-runtime-benchmarks = ["frame-benchmarking"]
deletedpallets/nft-transaction-payment/README.mddiffbeforeafterboth
--- a/pallets/nft-transaction-payment/README.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# Nft Transaction Payment
-
-## Overview
-
-A module containing the sponsoring logic for paying for sponsored collections
-
-**NOTE:** The scheduled calls will be dispatched with the default filter
-for the origin: namely `frame_system::Config::BaseCallFilter` for all origin
-except root which will get no filter. And not the filter contained in origin
-use to call `fn schedule`.
-
-If a call is scheduled using proxy or whatever mecanism which adds filter,
-then those filter will not be used when dispatching the schedule call.
deletedpallets/nft-transaction-payment/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft-transaction-payment/src/lib.rs
+++ /dev/null
@@ -1,39 +0,0 @@
-//
-// This file is subject to the terms and conditions defined in
-// file 'LICENSE', which is part of this source code package.
-//
-
-#![cfg_attr(not(feature = "std"), no_std)]
-
-#[cfg(feature = "std")]
-pub use std::*;
-
-#[cfg(feature = "std")]
-pub use serde::*;
-
-use frame_support::{decl_module, decl_storage};
-use sp_std::prelude::*;
-use up_sponsorship::SponsorshipHandler;
-
-pub trait Config: frame_system::Config + pallet_transaction_payment::Config {
-	type SponsorshipHandler: SponsorshipHandler<Self::AccountId, Self::Call>;
-}
-
-decl_storage! {
-	trait Store for Module<T: Config> as NftTransactionPayment{
-	}
-}
-
-decl_module! {
-	pub struct Module<T: Config> for enum Call
-	where
-		origin: T::Origin,
-	{
-	}
-}
-
-impl<T: Config> Module<T> {
-	pub fn withdraw_type(who: &T::AccountId, call: &T::Call) -> Option<T::AccountId> {
-		T::SponsorshipHandler::get_sponsor(who, call)
-	}
-}
modifiedpallets/nft/Cargo.tomldiffbeforeafterboth
--- a/pallets/nft/Cargo.toml
+++ b/pallets/nft/Cargo.toml
@@ -34,6 +34,7 @@
     'fp-evm/std',
     'nft-data-structs/std',
     'up-sponsorship/std',
+    'up-evm-mapping/std',
     'sp-std/std',
     'sp-api/std',
     'sp-runtime/std',
@@ -135,7 +136,7 @@
 sp-api = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.12" }
 
 up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/UniqueNetwork/pallet-sponsoring" } 
-
+up-evm-mapping = { default-features = false, path = "../../primitives/evm-mapping" }
 evm-coder = { default-features = false, path = "../../crates/evm-coder" }
 pallet-evm-coder-substrate = { default-features = false, path = "../../pallets/evm-coder-substrate" }
 primitive-types = { version = "0.10.1", default-features = false, features = [
modifiedpallets/nft/src/eth/sponsoring.rsdiffbeforeafterboth
--- a/pallets/nft/src/eth/sponsoring.rs
+++ b/pallets/nft/src/eth/sponsoring.rs
@@ -1,123 +1,74 @@
 //! Implements EVM sponsoring logic via OnChargeEVMTransaction
 
-use crate::{Collection, Config, FungibleTransferBasket, NftTransferBasket};
+use crate::{Config, sponsorship::*};
 use evm_coder::{Call, abi::AbiReader};
-use frame_support::{
-	storage::{StorageDoubleMap},
-};
-use pallet_common::eth::map_eth_to_id;
+use pallet_common::{CollectionHandle, eth::map_eth_to_id};
 use sp_core::H160;
 use sp_std::prelude::*;
 use up_sponsorship::SponsorshipHandler;
 use core::marker::PhantomData;
 use core::convert::TryInto;
-use nft_data_structs::{CollectionId, NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT};
-use pallet_common::{
-	CollectionById,
-	account::{CrossAccountId, EvmBackwardsAddressMapping},
-};
+use nft_data_structs::TokenId;
+use up_evm_mapping::EvmBackwardsAddressMapping;
+use pallet_common::account::CrossAccountId;
 
 use pallet_nonfungible::erc::{UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721Call};
 use pallet_fungible::erc::{UniqueFungibleCall, ERC20Call};
 
-struct AnyError;
-
-fn try_sponsor<T: Config>(
-	caller: &H160,
-	collection_id: CollectionId,
-	collection: &Collection<T>,
-	call: &[u8],
-) -> Result<(), AnyError> {
-	let (method_id, mut reader) = AbiReader::new_call(call).map_err(|_| AnyError)?;
-	match &collection.mode {
-		crate::CollectionMode::NFT => {
-			let call: UniqueNFTCall = UniqueNFTCall::parse(method_id, &mut reader)
-				.map_err(|_| AnyError)?
-				.ok_or(AnyError)?;
-			match call {
-				UniqueNFTCall::ERC721UniqueExtensions(ERC721UniqueExtensionsCall::Transfer {
-					token_id,
-					..
-				})
-				| UniqueNFTCall::ERC721(ERC721Call::TransferFrom { token_id, .. }) => {
-					let token_id: u32 = token_id.try_into().map_err(|_| AnyError)?;
-					let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
-					let collection_limits = &collection.limits;
-					let limit =
-						collection_limits.sponsor_transfer_timeout(NFT_SPONSOR_TRANSFER_TIMEOUT);
-
-					let mut sponsor = true;
-					if <NftTransferBasket<T>>::contains_key(collection_id, token_id) {
-						let last_tx_block = <NftTransferBasket<T>>::get(collection_id, token_id);
-						let limit_time = last_tx_block + limit.into();
-						if block_number <= limit_time {
-							sponsor = false;
-						}
+pub struct NftEthSponsorshipHandler<T: Config>(PhantomData<*const T>);
+impl<T: Config> SponsorshipHandler<H160, (H160, Vec<u8>)> for NftEthSponsorshipHandler<T> {
+	fn get_sponsor(who: &H160, call: &(H160, Vec<u8>)) -> Option<H160> {
+		let collection_id = map_eth_to_id(&call.0)?;
+		let collection = <CollectionHandle<T>>::new(collection_id)?;
+		let sponsor = collection.sponsorship.sponsor()?.clone();
+		let sponsor =
+			<T as pallet_common::Config>::EvmBackwardsAddressMapping::from_account_id(sponsor);
+		let who = T::CrossAccountId::from_eth(*who);
+		let (method_id, mut reader) = AbiReader::new_call(&call.1).ok()?;
+		match &collection.mode {
+			crate::CollectionMode::NFT => {
+				let call = UniqueNFTCall::parse(method_id, &mut reader).ok()??;
+				match call {
+					UniqueNFTCall::ERC721UniqueExtensions(
+						ERC721UniqueExtensionsCall::Transfer { token_id, .. },
+					) => {
+						let token_id: TokenId = token_id.try_into().ok()?;
+						withdraw_transfer::<T>(&collection, &who, &token_id).map(|()| sponsor)
 					}
-					if sponsor {
-						<NftTransferBasket<T>>::insert(collection_id, token_id, block_number);
-						return Ok(());
+					UniqueNFTCall::ERC721(ERC721Call::TransferFrom { token_id, from, .. }) => {
+						let token_id: TokenId = token_id.try_into().ok()?;
+						let from = T::CrossAccountId::from_eth(from);
+						withdraw_transfer::<T>(&collection, &from, &token_id).map(|()| sponsor)
 					}
+					UniqueNFTCall::ERC721(ERC721Call::Approve { token_id, .. }) => {
+						let token_id: TokenId = token_id.try_into().ok()?;
+						withdraw_approve::<T>(&collection, who.as_sub(), &token_id)
+							.map(|()| sponsor)
+					}
+					_ => None,
 				}
-				_ => {}
 			}
-		}
-		crate::CollectionMode::Fungible(_) => {
-			let call: UniqueFungibleCall = UniqueFungibleCall::parse(method_id, &mut reader)
-				.map_err(|_| AnyError)?
-				.ok_or(AnyError)?;
-			#[allow(clippy::single_match)]
-			match call {
-				UniqueFungibleCall::ERC20(ERC20Call::Transfer { .. }) => {
-					let who = T::CrossAccountId::from_eth(*caller);
-					let collection_limits = &collection.limits;
-					let limit = collection_limits
-						.sponsor_transfer_timeout(FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT);
-
-					let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
-					let mut sponsored = true;
-					if <FungibleTransferBasket<T>>::contains_key(collection_id, who.as_sub()) {
-						let last_tx_block =
-							<FungibleTransferBasket<T>>::get(collection_id, who.as_sub());
-						let limit_time = last_tx_block + limit.into();
-						if block_number <= limit_time {
-							sponsored = false;
-						}
+			crate::CollectionMode::Fungible(_) => {
+				let call = UniqueFungibleCall::parse(method_id, &mut reader).ok()??;
+				#[allow(clippy::single_match)]
+				match call {
+					UniqueFungibleCall::ERC20(ERC20Call::Transfer { .. }) => {
+						withdraw_transfer::<T>(&collection, &who, &TokenId::default())
+							.map(|()| sponsor)
 					}
-					if sponsored {
-						<FungibleTransferBasket<T>>::insert(
-							collection_id,
-							who.as_sub(),
-							block_number,
-						);
-						return Ok(());
+					UniqueFungibleCall::ERC20(ERC20Call::TransferFrom { from, .. }) => {
+						let from = T::CrossAccountId::from_eth(from);
+						withdraw_transfer::<T>(&collection, &from, &TokenId::default())
+							.map(|()| sponsor)
 					}
-				}
-				_ => {}
-			}
-		}
-		_ => {}
-	}
-	Err(AnyError)
-}
-
-pub struct NftEthSponsorshipHandler<T: Config>(PhantomData<*const T>);
-impl<T: Config> SponsorshipHandler<H160, (H160, Vec<u8>)> for NftEthSponsorshipHandler<T> {
-	fn get_sponsor(who: &H160, call: &(H160, Vec<u8>)) -> Option<H160> {
-		if let Some(collection_id) = map_eth_to_id(&call.0) {
-			if let Some(collection) = <CollectionById<T>>::get(collection_id) {
-				if !collection.sponsorship.confirmed() {
-					return None;
+					UniqueFungibleCall::ERC20(ERC20Call::Approve { .. }) => {
+						withdraw_approve::<T>(&collection, who.as_sub(), &TokenId::default())
+							.map(|()| sponsor)
+					}
+					_ => None,
 				}
-				if try_sponsor(who, collection_id, &collection, &call.1).is_ok() {
-					return collection
-						.sponsorship
-						.sponsor()
-						.cloned()
-						.map(T::EvmBackwardsAddressMapping::from_account_id);
-				}
 			}
+			_ => None,
 		}
-		None
 	}
 }
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -42,8 +42,8 @@
 	CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
 };
 use pallet_common::{
-	account::CrossAccountId, CollectionHandle, IsAdmin, Pallet as PalletCommon,
-	Error as CommonError, CommonWeightInfo, Allowlist,
+	account::CrossAccountId, CollectionHandle, Pallet as PalletCommon, Error as CommonError,
+	CommonWeightInfo,
 };
 use pallet_refungible::{Pallet as PalletRefungible, RefungibleHandle};
 use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};
@@ -136,18 +136,22 @@
 		//#region Tokens transfer rate limit baskets
 		/// (Collection id (controlled?2), who created (real))
 		/// TODO: Off chain worker should remove from this map when collection gets removed
-		pub CreateItemBasket get(fn create_item_basket): map hasher(blake2_128_concat) (CollectionId, T::AccountId) => T::BlockNumber;
+		pub CreateItemBasket get(fn create_item_basket): map hasher(blake2_128_concat) (CollectionId, T::AccountId) => Option<T::BlockNumber>;
 		/// Collection id (controlled?2), token id (controlled?2)
-		pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;
+		pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;
 		/// Collection id (controlled?2), owning user (real)
-		pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => T::BlockNumber;
+		pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;
 		/// Collection id (controlled?2), token id (controlled?2)
-		pub ReFungibleTransferBasket get(fn refungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;
+		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>;
 		//#endregion
 
 		/// Variable metadata sponsoring
 		/// Collection id (controlled?2), token id (controlled?2)
-		pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber> = None;
+		pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;
+		/// Approval sponsoring
+		pub NftApproveBasket get(fn nft_approve_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;
+		pub FungibleApproveBasket get(fn fungible_approve_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;
+		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>;
 	}
 }
 
@@ -190,7 +194,7 @@
 			let who = ensure_signed(origin)?;
 
 			// Create new collection
-			let new_collection = Collection::<T> {
+			let new_collection = Collection {
 				owner: who.clone(),
 				name: collection_name,
 				mode: mode.clone(),
@@ -208,14 +212,14 @@
 			};
 
 			let _id = match mode {
-				CollectionMode::NFT => {PalletNonfungible::init_collection(new_collection)?},
+				CollectionMode::NFT => {<PalletNonfungible<T>>::init_collection(new_collection)?},
 				CollectionMode::Fungible(decimal_points) => {
 					// check params
 					ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);
-					PalletFungible::init_collection(new_collection)?
+					<PalletFungible<T>>::init_collection(new_collection)?
 				}
 				CollectionMode::ReFungible => {
-					PalletRefungible::init_collection(new_collection)?
+					<PalletRefungible<T>>::init_collection(new_collection)?
 				}
 			};
 
@@ -249,9 +253,12 @@
 
 			<NftTransferBasket<T>>::remove_prefix(collection_id, None);
 			<FungibleTransferBasket<T>>::remove_prefix(collection_id, None);
-			<ReFungibleTransferBasket<T>>::remove_prefix(collection_id, None);
+			<ReFungibleTransferBasket<T>>::remove_prefix((collection_id,), None);
 
 			<VariableMetaDataBasket<T>>::remove_prefix(collection_id, None);
+			<NftApproveBasket<T>>::remove_prefix(collection_id, None);
+			<FungibleApproveBasket<T>>::remove_prefix(collection_id, None);
+			<RefungibleApproveBasket<T>>::remove_prefix((collection_id,), None);
 
 			Ok(())
 		}
@@ -592,7 +599,15 @@
 		pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 
-			dispatch_call::<T, _>(collection_id, |d| d.burn_item(sender, item_id, value))
+			let post_info = dispatch_call::<T, _>(collection_id, |d| d.burn_item(sender, item_id, value))?;
+			if value == 1 {
+				<NftTransferBasket<T>>::remove(collection_id, item_id);
+				<NftApproveBasket<T>>::remove(collection_id, item_id);
+			}
+			// Those maps should be cleared only if token disappears completly, need to move this part of logic to pallets?
+			// <FungibleApproveBasket<T>>::remove(collection_id, sender.as_sub());
+			// <RefungibleApproveBasket<T>>::remove((collection_id, item_id, sender.as_sub()));
+			Ok(post_info)
 		}
 
 		/// Destroys a concrete instance of NFT on behalf of the owner
@@ -936,19 +951,5 @@
 
 			target_collection.save()
 		}
-	}
-}
-
-// TODO: limit returned entries?
-impl<T: Config> Pallet<T> {
-	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {
-		<IsAdmin<T>>::iter_prefix((collection,))
-			.map(|(a, _)| a)
-			.collect()
-	}
-	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {
-		<Allowlist<T>>::iter_prefix((collection,))
-			.map(|(a, _)| a)
-			.collect()
 	}
 }
modifiedpallets/nft/src/sponsorship.rsdiffbeforeafterboth
--- a/pallets/nft/src/sponsorship.rs
+++ b/pallets/nft/src/sponsorship.rs
@@ -1,175 +1,222 @@
 use crate::{
 	Config, Call, CreateItemBasket, VariableMetaDataBasket, ReFungibleTransferBasket,
-	FungibleTransferBasket, NftTransferBasket, CreateItemData, CollectionMode,
+	FungibleTransferBasket, NftTransferBasket, CreateItemData, CollectionMode, NftApproveBasket,
+	FungibleApproveBasket, RefungibleApproveBasket,
 };
 use core::marker::PhantomData;
 use up_sponsorship::SponsorshipHandler;
 use frame_support::{
 	traits::{IsSubType},
-	storage::{StorageMap, StorageDoubleMap},
+	storage::{StorageMap, StorageDoubleMap, StorageNMap},
 };
 use nft_data_structs::{
-	TokenId, CollectionId, NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
-	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+	CollectionId, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MetaUpdatePermission,
+	NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, TokenId,
 };
-use pallet_common::{CollectionById};
-
-pub struct NftSponsorshipHandler<T>(PhantomData<T>);
-impl<T: Config> NftSponsorshipHandler<T> {
-	pub fn withdraw_create_item(
-		who: &T::AccountId,
-		collection_id: &CollectionId,
-		_properties: &CreateItemData,
-	) -> Option<T::AccountId> {
-		let collection = CollectionById::<T>::get(collection_id)?;
-
-		// sponsor timeout
-		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+use pallet_common::{CollectionHandle};
+use pallet_common::account::CrossAccountId;
 
-		let limit = collection
-			.limits
-			.sponsor_transfer_timeout(match _properties {
-				CreateItemData::NFT(_) => NFT_SPONSOR_TRANSFER_TIMEOUT,
-				CreateItemData::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
-				CreateItemData::ReFungible(_) => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
-			});
-		if CreateItemBasket::<T>::contains_key((collection_id, &who)) {
-			let last_tx_block = CreateItemBasket::<T>::get((collection_id, &who));
-			let limit_time = last_tx_block + limit.into();
-			if block_number <= limit_time {
+pub fn withdraw_transfer<T: Config>(
+	collection: &CollectionHandle<T>,
+	who: &T::CrossAccountId,
+	item_id: &TokenId,
+) -> Option<()> {
+	// preliminary sponsoring correctness check
+	match collection.mode {
+		CollectionMode::NFT => {
+			let owner = pallet_nonfungible::TokenData::<T>::get((collection.id, item_id))?.owner;
+			if !owner.conv_eq(who) {
 				return None;
 			}
 		}
-		CreateItemBasket::<T>::insert((collection_id, who.clone()), block_number);
+		CollectionMode::Fungible(_) => {
+			if item_id != &TokenId::default() {
+				return None;
+			}
+			if <pallet_fungible::Balance<T>>::get((collection.id, who)) == 0 {
+				return None;
+			}
+		}
+		CollectionMode::ReFungible => {
+			if !<pallet_refungible::Owned<T>>::get((collection.id, who, item_id)) {
+				return None;
+			}
+		}
+	}
+
+	// sponsor timeout
+	let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+	let limit = collection
+		.limits
+		.sponsor_transfer_timeout(match collection.mode {
+			CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,
+			CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+			CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+		});
+
+	let last_tx_block = match collection.mode {
+		CollectionMode::NFT => <NftTransferBasket<T>>::get(collection.id, item_id),
+		CollectionMode::Fungible(_) => {
+			<FungibleTransferBasket<T>>::get(collection.id, who.as_sub())
+		}
+		CollectionMode::ReFungible => {
+			<ReFungibleTransferBasket<T>>::get((collection.id, item_id, who.as_sub()))
+		}
+	};
 
-		// check free create limit
-		if collection.limits.sponsored_data_size() >= (_properties.data_size() as u32) {
-			collection.sponsorship.sponsor().cloned()
-		} else {
-			None
+	if let Some(last_tx_block) = last_tx_block {
+		let timeout = last_tx_block + limit.into();
+		if block_number < timeout {
+			return None;
 		}
 	}
 
-	pub fn withdraw_transfer(
-		who: &T::AccountId,
-		collection_id: &CollectionId,
-		item_id: &TokenId,
-	) -> Option<T::AccountId> {
-		let collection = CollectionById::<T>::get(collection_id)?;
+	match collection.mode {
+		CollectionMode::NFT => <NftTransferBasket<T>>::insert(collection.id, item_id, block_number),
+		CollectionMode::Fungible(_) => {
+			<FungibleTransferBasket<T>>::insert(collection.id, who.as_sub(), block_number)
+		}
+		CollectionMode::ReFungible => <ReFungibleTransferBasket<T>>::insert(
+			(collection.id, item_id, who.as_sub()),
+			block_number,
+		),
+	};
 
-		let mut sponsor_transfer = false;
-		if collection.sponsorship.confirmed() {
-			let collection_limits = collection.limits.clone();
-			let collection_mode = collection.mode.clone();
+	Some(())
+}
 
-			// sponsor timeout
-			let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
-			sponsor_transfer = match collection_mode {
-				CollectionMode::NFT => {
-					// get correct limit
-					let limit =
-						collection_limits.sponsor_transfer_timeout(NFT_SPONSOR_TRANSFER_TIMEOUT);
+pub fn withdraw_create_item<T: Config>(
+	collection: &CollectionHandle<T>,
+	who: &T::AccountId,
+	_properties: &CreateItemData,
+) -> Option<()> {
+	if _properties.data_size() as u32 > collection.limits.sponsored_data_size() {
+		return None;
+	}
 
-					let mut sponsored = true;
-					if NftTransferBasket::<T>::contains_key(collection_id, item_id) {
-						let last_tx_block = NftTransferBasket::<T>::get(collection_id, item_id);
-						let limit_time = last_tx_block + limit.into();
-						if block_number <= limit_time {
-							sponsored = false;
-						}
-					}
-					if sponsored {
-						NftTransferBasket::<T>::insert(collection_id, item_id, block_number);
-					}
+	// sponsor timeout
+	let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+	let limit = collection
+		.limits
+		.sponsor_transfer_timeout(match _properties {
+			CreateItemData::NFT(_) => NFT_SPONSOR_TRANSFER_TIMEOUT,
+			CreateItemData::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+			CreateItemData::ReFungible(_) => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+		});
+
+	if let Some(last_tx_block) = <CreateItemBasket<T>>::get((collection.id, &who)) {
+		let timeout = last_tx_block + limit.into();
+		if block_number < timeout {
+			return None;
+		}
+	}
 
-					sponsored
-				}
-				CollectionMode::Fungible(_) => {
-					// get correct limit
-					let limit = collection_limits
-						.sponsor_transfer_timeout(FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT);
+	CreateItemBasket::<T>::insert((collection.id, who.clone()), block_number);
 
-					let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
-					let mut sponsored = true;
-					if FungibleTransferBasket::<T>::contains_key(collection_id, who) {
-						let last_tx_block = FungibleTransferBasket::<T>::get(collection_id, who);
-						let limit_time = last_tx_block + limit.into();
-						if block_number <= limit_time {
-							sponsored = false;
-						}
-					}
-					if sponsored {
-						FungibleTransferBasket::<T>::insert(collection_id, who, block_number);
-					}
+	Some(())
+}
 
-					sponsored
-				}
-				CollectionMode::ReFungible => {
-					// get correct limit
-					let limit = collection_limits
-						.sponsor_transfer_timeout(REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT);
+pub fn withdraw_set_variable_meta_data<T: Config>(
+	who: &T::CrossAccountId,
+	collection: &CollectionHandle<T>,
+	item_id: &TokenId,
+	data: &[u8],
+) -> Option<()> {
+	// TODO: make it work for admins
+	if collection.meta_update_permission != MetaUpdatePermission::ItemOwner {
+		return None;
+	}
+	// preliminary sponsoring correctness check
+	match collection.mode {
+		CollectionMode::NFT => {
+			let owner = pallet_nonfungible::TokenData::<T>::get((collection.id, item_id))?.owner;
+			if !owner.conv_eq(who) {
+				return None;
+			}
+		}
+		CollectionMode::Fungible(_) => {
+			if item_id != &TokenId::default() {
+				return None;
+			}
+			if <pallet_fungible::Balance<T>>::get((collection.id, who)) == 0 {
+				return None;
+			}
+		}
+		CollectionMode::ReFungible => {
+			if !<pallet_refungible::Owned<T>>::get((collection.id, who, item_id)) {
+				return None;
+			}
+		}
+	}
 
-					let mut sponsored = true;
-					if ReFungibleTransferBasket::<T>::contains_key(collection_id, item_id) {
-						let last_tx_block =
-							ReFungibleTransferBasket::<T>::get(collection_id, item_id);
-						let limit_time = last_tx_block + limit.into();
-						if block_number <= limit_time {
-							sponsored = false;
-						}
-					}
-					if sponsored {
-						ReFungibleTransferBasket::<T>::insert(collection_id, item_id, block_number);
-					}
+	// Can't sponsor fungible collection, this tx will be rejected
+	// as invalid
+	if matches!(collection.mode, CollectionMode::Fungible(_)) {
+		return None;
+	}
+	if data.len() > collection.limits.sponsored_data_size() as usize {
+		return None;
+	}
 
-					sponsored
-				}
-			};
-		}
+	let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+	let limit = collection.limits.sponsored_data_rate_limit()?;
 
-		if !sponsor_transfer {
-			None
-		} else {
-			collection.sponsorship.sponsor().cloned()
+	if let Some(last_tx_block) = VariableMetaDataBasket::<T>::get(collection.id, item_id) {
+		let timeout = last_tx_block + limit.into();
+		if block_number < timeout {
+			return None;
 		}
 	}
 
-	pub fn withdraw_set_variable_meta_data(
-		collection_id: &CollectionId,
-		item_id: &TokenId,
-		data: &[u8],
-	) -> Option<T::AccountId> {
-		let mut sponsor_metadata_changes = false;
+	<VariableMetaDataBasket<T>>::insert(collection.id, item_id, block_number);
 
-		let collection = CollectionById::<T>::get(collection_id)?;
+	Some(())
+}
 
-		if collection.sponsorship.confirmed() &&
-			// Can't sponsor fungible collection, this tx will be rejected
-			// as invalid
-			!matches!(collection.mode, CollectionMode::Fungible(_)) &&
-			data.len() <= collection.limits.sponsored_data_size() as usize
-		{
-			if let Some(rate_limit) = collection.limits.sponsored_data_rate_limit() {
-				let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+pub fn withdraw_approve<T: Config>(
+	collection: &CollectionHandle<T>,
+	who: &T::AccountId,
+	item_id: &TokenId,
+) -> Option<()> {
+	// sponsor timeout
+	let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+	let limit = collection.limits.sponsor_approve_timeout();
 
-				if VariableMetaDataBasket::<T>::get(collection_id, item_id)
-					.map(|last_block| block_number - last_block > rate_limit.into())
-					.unwrap_or(true)
-				{
-					sponsor_metadata_changes = true;
-					VariableMetaDataBasket::<T>::insert(collection_id, item_id, block_number);
-				}
-			}
+	let last_tx_block = match collection.mode {
+		CollectionMode::NFT => <NftApproveBasket<T>>::get(collection.id, item_id),
+		CollectionMode::Fungible(_) => <FungibleApproveBasket<T>>::get(collection.id, who),
+		CollectionMode::ReFungible => {
+			<RefungibleApproveBasket<T>>::get((collection.id, item_id, who))
 		}
+	};
 
-		if !sponsor_metadata_changes {
-			None
-		} else {
-			collection.sponsorship.sponsor().cloned()
+	if let Some(last_tx_block) = last_tx_block {
+		let timeout = last_tx_block + limit.into();
+		if block_number < timeout {
+			return None;
 		}
 	}
+
+	match collection.mode {
+		CollectionMode::NFT => <NftApproveBasket<T>>::insert(collection.id, item_id, block_number),
+		CollectionMode::Fungible(_) => {
+			<FungibleApproveBasket<T>>::insert(collection.id, who, block_number)
+		}
+		CollectionMode::ReFungible => {
+			<RefungibleApproveBasket<T>>::insert((collection.id, item_id, who), block_number)
+		}
+	};
+
+	Some(())
+}
+
+fn load<T: Config>(id: CollectionId) -> Option<(T::AccountId, CollectionHandle<T>)> {
+	let collection = CollectionHandle::new(id)?;
+	let sponsor = collection.sponsorship.sponsor().cloned()?;
+	Some((sponsor, collection))
 }
 
+pub struct NftSponsorshipHandler<T>(PhantomData<T>);
 impl<T, C> SponsorshipHandler<T::AccountId, C> for NftSponsorshipHandler<T>
 where
 	T: Config,
@@ -181,17 +228,54 @@
 				collection_id,
 				data,
 				..
-			} => Self::withdraw_create_item(who, collection_id, data),
+			} => {
+				let (sponsor, collection) = load(*collection_id)?;
+				withdraw_create_item::<T>(&collection, who, data).map(|()| sponsor)
+			}
 			Call::transfer {
 				collection_id,
 				item_id,
 				..
-			} => Self::withdraw_transfer(who, collection_id, item_id),
+			} => {
+				let (sponsor, collection) = load(*collection_id)?;
+				withdraw_transfer::<T>(
+					&collection,
+					&T::CrossAccountId::from_sub(who.clone()),
+					item_id,
+				)
+				.map(|()| sponsor)
+			}
+			Call::transfer_from {
+				collection_id,
+				item_id,
+				from,
+				..
+			} => {
+				let (sponsor, collection) = load(*collection_id)?;
+				withdraw_transfer::<T>(&collection, from, item_id).map(|()| sponsor)
+			}
+			Call::approve {
+				collection_id,
+				item_id,
+				..
+			} => {
+				let (sponsor, collection) = load(*collection_id)?;
+				withdraw_approve::<T>(&collection, who, item_id).map(|()| sponsor)
+			}
 			Call::set_variable_meta_data {
 				collection_id,
 				item_id,
 				data,
-			} => Self::withdraw_set_variable_meta_data(collection_id, item_id, data),
+			} => {
+				let (sponsor, collection) = load(*collection_id)?;
+				withdraw_set_variable_meta_data::<T>(
+					&T::CrossAccountId::from_sub(who.clone()),
+					&collection,
+					item_id,
+					data,
+				)
+				.map(|()| sponsor)
+			}
 			_ => None,
 		}
 	}
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -58,18 +58,18 @@
 	}
 
 	#[pallet::pallet]
-	#[pallet::generate_store(pub(super) trait Store)]
+	#[pallet::generate_store(pub trait Store)]
 	pub struct Pallet<T>(_);
 
 	#[pallet::storage]
-	pub(super) type TokensMinted<T: Config> =
+	pub type TokensMinted<T: Config> =
 		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;
 	#[pallet::storage]
-	pub(super) type TokensBurnt<T: Config> =
+	pub type TokensBurnt<T: Config> =
 		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;
 
 	#[pallet::storage]
-	pub(super) type TokenData<T: Config> = StorageNMap<
+	pub type TokenData<T: Config> = StorageNMap<
 		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),
 		Value = ItemData<T>,
 		QueryKind = OptionQuery,
@@ -77,7 +77,7 @@
 
 	/// Used to enumerate tokens owned by account
 	#[pallet::storage]
-	pub(super) type Owned<T: Config> = StorageNMap<
+	pub type Owned<T: Config> = StorageNMap<
 		Key = (
 			Key<Twox64Concat, CollectionId>,
 			Key<Blake2_128Concat, T::CrossAccountId>,
@@ -88,7 +88,7 @@
 	>;
 
 	#[pallet::storage]
-	pub(super) type AccountBalance<T: Config> = StorageNMap<
+	pub type AccountBalance<T: Config> = StorageNMap<
 		Key = (
 			Key<Twox64Concat, CollectionId>,
 			Key<Blake2_128Concat, T::CrossAccountId>,
@@ -98,7 +98,7 @@
 	>;
 
 	#[pallet::storage]
-	pub(super) type Allowance<T: Config> = StorageNMap<
+	pub type Allowance<T: Config> = StorageNMap<
 		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),
 		Value = T::CrossAccountId,
 		QueryKind = OptionQuery,
@@ -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
@@ -54,25 +54,25 @@
 	}
 
 	#[pallet::pallet]
-	#[pallet::generate_store(pub(super) trait Store)]
+	#[pallet::generate_store(pub trait Store)]
 	pub struct Pallet<T>(_);
 
 	#[pallet::storage]
-	pub(super) type TokensMinted<T: Config> =
+	pub type TokensMinted<T: Config> =
 		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;
 	#[pallet::storage]
-	pub(super) type TokensBurnt<T: Config> =
+	pub type TokensBurnt<T: Config> =
 		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;
 
 	#[pallet::storage]
-	pub(super) type TokenData<T: Config> = StorageNMap<
+	pub type TokenData<T: Config> = StorageNMap<
 		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),
 		Value = ItemData,
 		QueryKind = ValueQuery,
 	>;
 
 	#[pallet::storage]
-	pub(super) type TotalSupply<T: Config> = StorageNMap<
+	pub type TotalSupply<T: Config> = StorageNMap<
 		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),
 		Value = u128,
 		QueryKind = ValueQuery,
@@ -80,7 +80,7 @@
 
 	/// Used to enumerate tokens owned by account
 	#[pallet::storage]
-	pub(super) type Owned<T: Config> = StorageNMap<
+	pub type Owned<T: Config> = StorageNMap<
 		Key = (
 			Key<Twox64Concat, CollectionId>,
 			Key<Blake2_128Concat, T::CrossAccountId>,
@@ -91,7 +91,7 @@
 	>;
 
 	#[pallet::storage]
-	pub(super) type AccountBalance<T: Config> = StorageNMap<
+	pub type AccountBalance<T: Config> = StorageNMap<
 		Key = (
 			Key<Twox64Concat, CollectionId>,
 			// Owner
@@ -102,7 +102,7 @@
 	>;
 
 	#[pallet::storage]
-	pub(super) type Balance<T: Config> = StorageNMap<
+	pub type Balance<T: Config> = StorageNMap<
 		Key = (
 			Key<Twox64Concat, CollectionId>,
 			Key<Twox64Concat, TokenId>,
@@ -114,7 +114,7 @@
 	>;
 
 	#[pallet::storage]
-	pub(super) type Allowance<T: Config> = StorageNMap<
+	pub type Allowance<T: Config> = StorageNMap<
 		Key = (
 			Key<Twox64Concat, CollectionId>,
 			Key<Twox64Concat, TokenId>,
@@ -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>,
addedprimitives/evm-mapping/Cargo.tomldiffbeforeafterboth
--- /dev/null
+++ b/primitives/evm-mapping/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "up-evm-mapping"
+version = "0.1.0"
+edition = "2018"
+
+[dependencies]
+sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+frame-support = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.12' }
+
+[features]
+default = ["std"]
+std = [
+	"sp-core/std",
+	"frame-support/std",
+]
addedprimitives/evm-mapping/src/lib.rsdiffbeforeafterboth
--- /dev/null
+++ b/primitives/evm-mapping/src/lib.rs
@@ -0,0 +1,23 @@
+#![cfg_attr(not(feature = "std"), no_std)]
+
+use frame_support::sp_runtime::AccountId32;
+use sp_core::H160;
+
+/// Transforms substrate addresses to ethereum (Reverse of `EvmAddressMapping`)
+/// pallet_evm doesn't have this, as it only checks if eth address
+/// is owned by substrate via `EnsureAddressOrigin` trait
+///
+/// This trait implementations shouldn't conflict with used `EnsureAddressOrigin`
+pub trait EvmBackwardsAddressMapping<AccountId> {
+	fn from_account_id(account_id: AccountId) -> H160;
+}
+
+/// Should have same mapping as EnsureAddressTruncated
+pub struct MapBackwardsAddressTruncated;
+impl EvmBackwardsAddressMapping<AccountId32> for MapBackwardsAddressTruncated {
+	fn from_account_id(account_id: AccountId32) -> H160 {
+		let mut out = [0; 20];
+		out.copy_from_slice(&(account_id.as_ref() as &[u8])[0..20]);
+		H160(out)
+	}
+}
modifiedprimitives/nft/src/lib.rsdiffbeforeafterboth
--- a/primitives/nft/src/lib.rs
+++ b/primitives/nft/src/lib.rs
@@ -54,6 +54,8 @@
 pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;
 pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;
 
+pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;
+
 // Schema limits
 pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 1024;
 pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 1024;
@@ -207,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
@@ -217,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>,    //
@@ -246,6 +248,7 @@
 	pub variable_data: Vec<u8>,
 }
 
+/// All fields are wrapped in `Option`s, where None means chain default
 #[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo)]
 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
 pub struct CollectionLimits {
@@ -254,11 +257,12 @@
 	/// None - setVariableMetadata is not sponsored
 	/// Some(v) - setVariableMetadata is sponsored
 	///           if there is v block between txs
-	pub sponsored_data_rate_limit: Option<u32>,
+	pub sponsored_data_rate_limit: Option<(Option<u32>,)>,
 	pub token_limit: Option<u32>,
 
 	// Timeouts for item types in passed blocks
 	pub sponsor_transfer_timeout: Option<u32>,
+	pub sponsor_approve_timeout: Option<u32>,
 	pub owner_can_transfer: Option<bool>,
 	pub owner_can_destroy: Option<bool>,
 	pub transfers_enabled: Option<bool>,
@@ -285,6 +289,11 @@
 			.unwrap_or(default)
 			.min(MAX_SPONSOR_TIMEOUT)
 	}
+	pub fn sponsor_approve_timeout(&self) -> u32 {
+		self.sponsor_approve_timeout
+			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)
+			.min(MAX_SPONSOR_TIMEOUT)
+	}
 	pub fn owner_can_transfer(&self) -> bool {
 		self.owner_can_transfer.unwrap_or(true)
 	}
@@ -296,6 +305,8 @@
 	}
 	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {
 		self.sponsored_data_rate_limit
+			.unwrap_or((None,))
+			.0
 			.map(|v| v.min(MAX_SPONSOR_TIMEOUT))
 	}
 }
@@ -413,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/Cargo.tomldiffbeforeafterboth
--- a/runtime/Cargo.toml
+++ b/runtime/Cargo.toml
@@ -69,6 +69,7 @@
     'pallet-ethereum/std',
     'fp-rpc/std',
     'up-rpc/std',
+    'up-evm-mapping/std',
     'fp-self-contained/std',
     'parachain-info/std',
     'serde',
@@ -80,7 +81,6 @@
     'pallet-nft/std',
     'pallet-unq-scheduler/std',
     'pallet-nft-charge-transaction/std',
-    'pallet-nft-transaction-payment/std',
     'nft-data-structs/std',
     'sp-api/std',
     'sp-block-builder/std',
@@ -362,7 +362,7 @@
 default-features = false
 
 [dependencies.orml-vesting]
-git = "https://github.com/open-web3-stack/open-runtime-module-library"
+git = 'https://github.com/UniqueNetwork/open-runtime-module-library'
 version = "0.4.1-dev" 
 default-features = false
 
@@ -376,6 +376,7 @@
 derivative = "2.2.0"
 pallet-nft = { path = '../pallets/nft', default-features = false, version = '3.0.0' }
 up-rpc = { path = "../primitives/rpc", default-features = false }
+up-evm-mapping = { path = "../primitives/evm-mapping", default-features = false }
 pallet-inflation = { path = '../pallets/inflation', default-features = false, version = '3.0.0' }
 nft-data-structs = { path = '../primitives/nft', default-features = false, version = '0.9.0' }
 pallet-common = { default-features = false, path = "../pallets/common" }
@@ -384,8 +385,7 @@
 pallet-nonfungible = { default-features = false, path = "../pallets/nonfungible" }
 pallet-unq-scheduler = { path = '../pallets/scheduler', default-features = false, version = '3.0.0' }
 # pallet-contract-helpers = { path = '../pallets/contract-helpers', default-features = false, version = '0.1.0' }
-pallet-nft-transaction-payment = { path = '../pallets/nft-transaction-payment', default-features = false, version = '3.0.0' }
-pallet-nft-charge-transaction = {git = "https://github.com/UniqueNetwork/pallet-sponsoring", package = "pallet-template-transaction-payment", default-features = false, version = '3.0.0' }
+pallet-nft-charge-transaction = { git = "https://github.com/UniqueNetwork/pallet-sponsoring", package = "pallet-template-transaction-payment", default-features = false, version = '3.0.0' }
 pallet-evm-migration = { path = '../pallets/evm-migration', default-features = false }
 pallet-evm-contract-helpers = { path = '../pallets/evm-contract-helpers', default-features = false }
 pallet-evm-transaction-payment = { path = '../pallets/evm-transaction-payment', default-features = false }
modifiedruntime/src/lib.rsdiffbeforeafterboth
before · runtime/src/lib.rs
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "1024"]11#![allow(clippy::from_over_into, clippy::identity_op)]12#![allow(clippy::fn_to_numeric_cast_with_truncation)]13// Make the WASM binary available.14#[cfg(feature = "std")]15include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1617use sp_api::impl_runtime_apis;18use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};19// #[cfg(any(feature = "std", test))]20// pub use sp_runtime::BuildStorage;2122use sp_runtime::{23	Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,24	traits::{25		AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify, AccountIdConversion,26	},27	transaction_validity::{TransactionSource, TransactionValidity},28	ApplyExtrinsicResult, MultiSignature,29};3031use sp_std::prelude::*;3233#[cfg(feature = "std")]34use sp_version::NativeVersion;35use sp_version::RuntimeVersion;36pub use pallet_transaction_payment::{37	Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,38};39// A few exports that help ease life for downstream crates.40pub use pallet_balances::Call as BalancesCall;41pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};42pub use frame_support::{43	construct_runtime, match_type,44	dispatch::DispatchResult,45	PalletId, parameter_types, StorageValue, ConsensusEngineId,46	traits::{47		Everything, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem,48		LockIdentifier, OnUnbalanced, Randomness, FindAuthor,49	},50	weights::{51		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},52		DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,53		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,54	},55};56use nft_data_structs::*;57// use pallet_contracts::weights::WeightInfo;58// #[cfg(any(feature = "std", test))]59use frame_system::{60	self as system, EnsureRoot, EnsureSigned,61	limits::{BlockWeights, BlockLength},62};63use sp_arithmetic::{64	traits::{BaseArithmetic, Unsigned},65};66use smallvec::smallvec;67use codec::{Encode, Decode};68use pallet_evm::{Account as EVMAccount, FeeCalculator, OnMethodCall};69use fp_rpc::TransactionStatus;70use sp_core::crypto::Public;71use sp_runtime::{72	traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf},73	transaction_validity::TransactionValidityError,74};7576// pub use pallet_timestamp::Call as TimestampCall;77pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;7879// Polkadot imports80use pallet_xcm::XcmPassthrough;81use polkadot_parachain::primitives::Sibling;82use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};83use xcm_builder::{84	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,85	EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset,86	ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,87	SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,88	SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,89};90use xcm_executor::{Config, XcmExecutor};9192// mod chain_extension;93// use crate::chain_extension::{NFTExtension, Imbalance};9495/// An index to a block.96pub type BlockNumber = u32;9798/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.99pub type Signature = MultiSignature;100101/// Some way of identifying an account on the chain. We intentionally make it equivalent102/// to the public key of our transaction signing scheme.103pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;104105pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;106107/// The type for looking up accounts. We don't expect more than 4 billion of them, but you108/// never know...109pub type AccountIndex = u32;110111/// Balance of an account.112pub type Balance = u128;113114/// Index of a transaction in the chain.115pub type Index = u32;116117/// A hash of some data used by the chain.118pub type Hash = sp_core::H256;119120/// Digest item type.121pub type DigestItem = generic::DigestItem<Hash>;122123/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know124/// the specifics of the runtime. They can then be made to be agnostic over specific formats125/// of data like extrinsics, allowing for them to continue syncing the network through upgrades126/// to even the core data structures.127pub mod opaque {128	use super::*;129130	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;131132	/// Opaque block type.133	pub type Block = generic::Block<Header, UncheckedExtrinsic>;134135	pub type SessionHandlers = ();136137	impl_opaque_keys! {138		pub struct SessionKeys {139			pub aura: Aura,140		}141	}142}143144/// This runtime version.145pub const VERSION: RuntimeVersion = RuntimeVersion {146	spec_name: create_runtime_str!("opal"),147	impl_name: create_runtime_str!("opal"),148	authoring_version: 1,149	spec_version: 912202,150	impl_version: 1,151	apis: RUNTIME_API_VERSIONS,152	transaction_version: 1,153};154155pub const MILLISECS_PER_BLOCK: u64 = 12000;156157pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;158159// These time units are defined in number of blocks.160pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);161pub const HOURS: BlockNumber = MINUTES * 60;162pub const DAYS: BlockNumber = HOURS * 24;163164parameter_types! {165	pub const DefaultSponsoringRateLimit: BlockNumber = 1 * DAYS;166}167168#[derive(codec::Encode, codec::Decode)]169pub enum XCMPMessage<XAccountId, XBalance> {170	/// Transfer tokens to the given account from the Parachain account.171	TransferToken(XAccountId, XBalance),172}173174/// The version information used to identify this runtime when compiled natively.175#[cfg(feature = "std")]176pub fn native_version() -> NativeVersion {177	NativeVersion {178		runtime_version: VERSION,179		can_author_with: Default::default(),180	}181}182183type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;184185pub struct DealWithFees;186impl OnUnbalanced<NegativeImbalance> for DealWithFees {187	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {188		if let Some(fees) = fees_then_tips.next() {189			// for fees, 100% to treasury190			let mut split = fees.ration(100, 0);191			if let Some(tips) = fees_then_tips.next() {192				// for tips, if any, 100% to treasury193				tips.ration_merge_into(100, 0, &mut split);194			}195			Treasury::on_unbalanced(split.0);196			// Author::on_unbalanced(split.1);197		}198	}199}200201/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.202/// This is used to limit the maximal weight of a single extrinsic.203const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);204/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used205/// by  Operational  extrinsics.206const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);207/// We allow for 2 seconds of compute with a 6 second average block time.208const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2;209210parameter_types! {211	pub const BlockHashCount: BlockNumber = 2400;212	pub RuntimeBlockLength: BlockLength =213		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);214	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);215	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;216	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()217		.base_block(BlockExecutionWeight::get())218		.for_class(DispatchClass::all(), |weights| {219			weights.base_extrinsic = ExtrinsicBaseWeight::get();220		})221		.for_class(DispatchClass::Normal, |weights| {222			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);223		})224		.for_class(DispatchClass::Operational, |weights| {225			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);226			// Operational transactions have some extra reserved space, so that they227			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.228			weights.reserved = Some(229				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT230			);231		})232		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)233		.build_or_panic();234	pub const Version: RuntimeVersion = VERSION;235	pub const SS58Prefix: u8 = 42;236}237238parameter_types! {239	pub const ChainId: u64 = 8888;240}241242pub struct FixedFee;243impl FeeCalculator for FixedFee {244	fn min_gas_price() -> U256 {245		1.into()246	}247}248249impl pallet_evm::Config for Runtime {250	type BlockGasLimit = BlockGasLimit;251	type FeeCalculator = FixedFee;252	type GasWeightMapping = ();253	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;254	type CallOrigin = EnsureAddressTruncated;255	type WithdrawOrigin = EnsureAddressTruncated;256	type AddressMapping = HashedAddressMapping<Self::Hashing>;257	type Precompiles = ();258	type Currency = Balances;259	type Event = Event;260	type OnMethodCall = (261		pallet_evm_migration::OnMethodCall<Self>,262		pallet_nft::NftErcSupport<Self>,263		pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,264	);265	type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;266	type ChainId = ChainId;267	type Runner = pallet_evm::runner::stack::Runner<Self>;268	type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;269	type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;270	type FindAuthor = EthereumFindAuthor<Aura>;271}272273impl pallet_evm_migration::Config for Runtime {274	type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;275}276277pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);278impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {279	fn find_author<'a, I>(digests: I) -> Option<H160>280	where281		I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,282	{283		if let Some(author_index) = F::find_author(digests) {284			let authority_id = Aura::authorities()[author_index as usize].clone();285			return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));286		}287		None288	}289}290291parameter_types! {292	pub BlockGasLimit: U256 = U256::from(u32::max_value());293}294295impl pallet_ethereum::Config for Runtime {296	type Event = Event;297	type StateRoot = pallet_ethereum::IntermediateStateRoot;298	type EvmSubmitLog = pallet_evm::Pallet<Self>;299}300301impl pallet_randomness_collective_flip::Config for Runtime {}302303impl system::Config for Runtime {304	/// The data to be stored in an account.305	type AccountData = pallet_balances::AccountData<Balance>;306	/// The identifier used to distinguish between accounts.307	type AccountId = AccountId;308	/// The basic call filter to use in dispatchable.309	type BaseCallFilter = Everything;310	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).311	type BlockHashCount = BlockHashCount;312	/// The maximum length of a block (in bytes).313	type BlockLength = RuntimeBlockLength;314	/// The index type for blocks.315	type BlockNumber = BlockNumber;316	/// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.317	type BlockWeights = RuntimeBlockWeights;318	/// The aggregated dispatch type that is available for extrinsics.319	type Call = Call;320	/// The weight of database operations that the runtime can invoke.321	type DbWeight = RocksDbWeight;322	/// The ubiquitous event type.323	type Event = Event;324	/// The type for hashing blocks and tries.325	type Hash = Hash;326	/// The hashing algorithm used.327	type Hashing = BlakeTwo256;328	/// The header type.329	type Header = generic::Header<BlockNumber, BlakeTwo256>;330	/// The index type for storing how many extrinsics an account has signed.331	type Index = Index;332	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.333	type Lookup = AccountIdLookup<AccountId, ()>;334	/// What to do if an account is fully reaped from the system.335	type OnKilledAccount = ();336	/// What to do if a new account is created.337	type OnNewAccount = ();338	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;339	/// The ubiquitous origin type.340	type Origin = Origin;341	/// This type is being generated by `construct_runtime!`.342	type PalletInfo = PalletInfo;343	/// This is used as an identifier of the chain. 42 is the generic substrate prefix.344	type SS58Prefix = SS58Prefix;345	/// Weight information for the extrinsics of this pallet.346	type SystemWeightInfo = system::weights::SubstrateWeight<Self>;347	/// Version of the runtime.348	type Version = Version;349}350351parameter_types! {352	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;353}354355impl pallet_timestamp::Config for Runtime {356	/// A timestamp: milliseconds since the unix epoch.357	type Moment = u64;358	type OnTimestampSet = ();359	type MinimumPeriod = MinimumPeriod;360	type WeightInfo = ();361}362363parameter_types! {364	// pub const ExistentialDeposit: u128 = 500;365	pub const ExistentialDeposit: u128 = 0;366	pub const MaxLocks: u32 = 50;367}368369impl pallet_balances::Config for Runtime {370	type MaxLocks = MaxLocks;371	type MaxReserves = ();372	type ReserveIdentifier = [u8; 8];373	/// The type for recording an account's balance.374	type Balance = Balance;375	/// The ubiquitous event type.376	type Event = Event;377	type DustRemoval = Treasury;378	type ExistentialDeposit = ExistentialDeposit;379	type AccountStore = System;380	type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;381}382383pub const MICROUNIQUE: Balance = 1_000_000_000;384pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;385pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;386pub const UNIQUE: Balance = 100 * CENTIUNIQUE;387388pub const fn deposit(items: u32, bytes: u32) -> Balance {389	items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE390}391392/*393parameter_types! {394	pub TombstoneDeposit: Balance = deposit(395		1,396		sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,397	);398	pub DepositPerContract: Balance = TombstoneDeposit::get();399	pub const DepositPerStorageByte: Balance = deposit(0, 1);400	pub const DepositPerStorageItem: Balance = deposit(1, 0);401	pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);402	pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;403	pub const SignedClaimHandicap: u32 = 2;404	pub const MaxDepth: u32 = 32;405	pub const MaxValueSize: u32 = 16 * 1024;406	pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb407	// The lazy deletion runs inside on_initialize.408	pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *409		RuntimeBlockWeights::get().max_block;410	// The weight needed for decoding the queue should be less or equal than a fifth411	// of the overall weight dedicated to the lazy deletion.412	pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (413			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -414			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)415		)) / 5) as u32;416	pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();417}418419impl pallet_contracts::Config for Runtime {420	type Time = Timestamp;421	type Randomness = RandomnessCollectiveFlip;422	type Currency = Balances;423	type Event = Event;424	type RentPayment = ();425	type SignedClaimHandicap = SignedClaimHandicap;426	type TombstoneDeposit = TombstoneDeposit;427	type DepositPerContract = DepositPerContract;428	type DepositPerStorageByte = DepositPerStorageByte;429	type DepositPerStorageItem = DepositPerStorageItem;430	type RentFraction = RentFraction;431	type SurchargeReward = SurchargeReward;432	type WeightPrice = pallet_transaction_payment::Pallet<Self>;433	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;434	type ChainExtension = NFTExtension;435	type DeletionQueueDepth = DeletionQueueDepth;436	type DeletionWeightLimit = DeletionWeightLimit;437	type Schedule = Schedule;438	type CallStack = [pallet_contracts::Frame<Self>; 31];439}440*/441442parameter_types! {443	pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer444	/// This value increases the priority of `Operational` transactions by adding445	/// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.446	pub const OperationalFeeMultiplier: u8 = 5;447}448449/// Linear implementor of `WeightToFeePolynomial`450pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);451452impl<T> WeightToFeePolynomial for LinearFee<T>453where454	T: BaseArithmetic + From<u32> + Copy + Unsigned,455{456	type Balance = T;457458	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {459		smallvec!(WeightToFeeCoefficient {460			coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer461			coeff_frac: Perbill::zero(),462			negative: false,463			degree: 1,464		})465	}466}467468impl pallet_transaction_payment::Config for Runtime {469	type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;470	type TransactionByteFee = TransactionByteFee;471	type OperationalFeeMultiplier = OperationalFeeMultiplier;472	type WeightToFee = LinearFee<Balance>;473	type FeeMultiplierUpdate = ();474}475476parameter_types! {477	pub const ProposalBond: Permill = Permill::from_percent(5);478	pub const ProposalBondMinimum: Balance = 1 * UNIQUE;479	pub const SpendPeriod: BlockNumber = 5 * MINUTES;480	pub const Burn: Permill = Permill::from_percent(0);481	pub const TipCountdown: BlockNumber = 1 * DAYS;482	pub const TipFindersFee: Percent = Percent::from_percent(20);483	pub const TipReportDepositBase: Balance = 1 * UNIQUE;484	pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;485	pub const BountyDepositBase: Balance = 1 * UNIQUE;486	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;487	pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");488	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;489	pub const MaximumReasonLength: u32 = 16384;490	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);491	pub const BountyValueMinimum: Balance = 5 * UNIQUE;492	pub const MaxApprovals: u32 = 100;493}494495impl pallet_treasury::Config for Runtime {496	type PalletId = TreasuryModuleId;497	type Currency = Balances;498	type ApproveOrigin = EnsureRoot<AccountId>;499	type RejectOrigin = EnsureRoot<AccountId>;500	type Event = Event;501	type OnSlash = ();502	type ProposalBond = ProposalBond;503	type ProposalBondMinimum = ProposalBondMinimum;504	type SpendPeriod = SpendPeriod;505	type Burn = Burn;506	type BurnDestination = ();507	type SpendFunds = ();508	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;509	type MaxApprovals = MaxApprovals;510}511512impl pallet_sudo::Config for Runtime {513	type Event = Event;514	type Call = Call;515}516517pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);518519impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider520	for RelayChainBlockNumberProvider<T>521{522	type BlockNumber = BlockNumber;523524	fn current_block_number() -> Self::BlockNumber {525		cumulus_pallet_parachain_system::Pallet::<T>::validation_data()526			.map(|d| d.relay_parent_number)527			.unwrap_or_default()528	}529}530531parameter_types! {532	pub const MinVestedTransfer: Balance = 10 * UNIQUE;533	pub const MaxVestingSchedules: u32 = 28;534}535536impl orml_vesting::Config for Runtime {537	type Event = Event;538	type Currency = pallet_balances::Pallet<Runtime>;539	type MinVestedTransfer = MinVestedTransfer;540	type VestedTransferOrigin = EnsureSigned<AccountId>;541	type WeightInfo = ();542	type MaxVestingSchedules = MaxVestingSchedules;543	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;544}545546parameter_types! {547	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;548	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;549}550551impl cumulus_pallet_parachain_system::Config for Runtime {552	type Event = Event;553	type OnValidationData = ();554	type SelfParaId = parachain_info::Pallet<Self>;555	// type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<556	// 	MaxDownwardMessageWeight,557	// 	XcmExecutor<XcmConfig>,558	// 	Call,559	// >;560	type OutboundXcmpMessageSource = XcmpQueue;561	type DmpMessageHandler = DmpQueue;562	type ReservedDmpWeight = ReservedDmpWeight;563	type ReservedXcmpWeight = ReservedXcmpWeight;564	type XcmpMessageHandler = XcmpQueue;565}566567impl parachain_info::Config for Runtime {}568569impl cumulus_pallet_aura_ext::Config for Runtime {}570571parameter_types! {572	pub const RelayLocation: MultiLocation = MultiLocation::parent();573	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;574	pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();575	pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();576}577578/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used579/// when determining ownership of accounts for asset transacting and when attempting to use XCM580/// `Transact` in order to determine the dispatch Origin.581pub type LocationToAccountId = (582	// The parent (Relay-chain) origin converts to the default `AccountId`.583	ParentIsDefault<AccountId>,584	// Sibling parachain origins convert to AccountId via the `ParaId::into`.585	SiblingParachainConvertsVia<Sibling, AccountId>,586	// Straight up local `AccountId32` origins just alias directly to `AccountId`.587	AccountId32Aliases<RelayNetwork, AccountId>,588);589590/// Means for transacting assets on this chain.591pub type LocalAssetTransactor = CurrencyAdapter<592	// Use this currency:593	Balances,594	// Use this currency when it is a fungible asset matching the given location or name:595	IsConcrete<RelayLocation>,596	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:597	LocationToAccountId,598	// Our chain's account ID type (we can't get away without mentioning it explicitly):599	AccountId,600	// We don't track any teleports.601	(),602>;603604/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,605/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can606/// biases the kind of local `Origin` it will become.607pub type XcmOriginToTransactDispatchOrigin = (608	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location609	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for610	// foreign chains who want to have a local sovereign account on this chain which they control.611	SovereignSignedViaLocation<LocationToAccountId, Origin>,612	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when613	// recognised.614	RelayChainAsNative<RelayOrigin, Origin>,615	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when616	// recognised.617	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,618	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a619	// transaction from the Root origin.620	ParentAsSuperuser<Origin>,621	// Native signed account converter; this just converts an `AccountId32` origin into a normal622	// `Origin::Signed` origin of the same 32-byte value.623	SignedAccountId32AsNative<RelayNetwork, Origin>,624	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.625	XcmPassthrough<Origin>,626);627628parameter_types! {629	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.630	pub UnitWeightCost: Weight = 1_000_000;631	// 1200 UNIQUEs buy 1 second of weight.632	pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);633	pub const MaxInstructions: u32 = 100;634	pub const MaxAuthorities: u32 = 100_000;635}636637match_type! {638	pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {639		MultiLocation { parents: 1, interior: Here } |640		MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }641	};642}643644pub type Barrier = (645	TakeWeightCredit,646	AllowTopLevelPaidExecutionFrom<Everything>,647	AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,648	// ^^^ Parent & its unit plurality gets free execution649);650651pub struct XcmConfig;652impl Config for XcmConfig {653	type Call = Call;654	type XcmSender = XcmRouter;655	// How to withdraw and deposit an asset.656	type AssetTransactor = LocalAssetTransactor;657	type OriginConverter = XcmOriginToTransactDispatchOrigin;658	type IsReserve = NativeAsset;659	type IsTeleporter = (); // Teleportation is disabled660	type LocationInverter = LocationInverter<Ancestry>;661	type Barrier = Barrier;662	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;663	type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;664	type ResponseHandler = (); // Don't handle responses for now.665	type SubscriptionService = PolkadotXcm;666667	type AssetTrap = PolkadotXcm;668	type AssetClaims = PolkadotXcm;669}670671// parameter_types! {672// 	pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;673// }674675/// No local origins on this chain are allowed to dispatch XCM sends/executions.676pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);677678/// The means for routing XCM messages which are not for local execution into the right message679/// queues.680pub type XcmRouter = (681	// Two routers - use UMP to communicate with the relay chain:682	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,683	// ..and XCMP to communicate with the sibling chains.684	XcmpQueue,685);686687impl pallet_evm_coder_substrate::Config for Runtime {688	type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;689}690691impl pallet_xcm::Config for Runtime {692	type Event = Event;693	type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;694	type XcmRouter = XcmRouter;695	type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;696	type XcmExecuteFilter = Everything;697	type XcmExecutor = XcmExecutor<XcmConfig>;698	type XcmTeleportFilter = Everything;699	type XcmReserveTransferFilter = Everything;700	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;701	type LocationInverter = LocationInverter<Ancestry>;702	type Origin = Origin;703	type Call = Call;704	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;705	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;706}707708impl cumulus_pallet_xcm::Config for Runtime {709	type Event = Event;710	type XcmExecutor = XcmExecutor<XcmConfig>;711}712713impl cumulus_pallet_xcmp_queue::Config for Runtime {714	type Event = Event;715	type XcmExecutor = XcmExecutor<XcmConfig>;716	type ChannelInfo = ParachainSystem;717	type VersionWrapper = ();718}719720impl cumulus_pallet_dmp_queue::Config for Runtime {721	type Event = Event;722	type XcmExecutor = XcmExecutor<XcmConfig>;723	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;724}725726impl pallet_aura::Config for Runtime {727	type AuthorityId = AuraId;728	type DisabledValidators = ();729	type MaxAuthorities = MaxAuthorities;730}731732parameter_types! {733	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();734	pub const CollectionCreationPrice: Balance = 100 * UNIQUE;735}736737impl pallet_common::Config for Runtime {738	type Event = Event;739	type EvmBackwardsAddressMapping = pallet_common::account::MapBackwardsAddressTruncated;740	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;741	type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;742743	type Currency = Balances;744	type CollectionCreationPrice = CollectionCreationPrice;745	type TreasuryAccountId = TreasuryAccountId;746}747748impl pallet_fungible::Config for Runtime {749	type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;750}751impl pallet_refungible::Config for Runtime {752	type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;753}754impl pallet_nonfungible::Config for Runtime {755	type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;756}757758/// Used for the pallet nft in `./nft.rs`759impl pallet_nft::Config for Runtime {760	type WeightInfo = pallet_nft::weights::SubstrateWeight<Self>;761}762763parameter_types! {764	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied765}766767/// Used for the pallet inflation768impl pallet_inflation::Config for Runtime {769	type Currency = Balances;770	type TreasuryAccountId = TreasuryAccountId;771	type InflationBlockInterval = InflationBlockInterval;772}773774parameter_types! {775	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *776		RuntimeBlockWeights::get().max_block;777	pub const MaxScheduledPerBlock: u32 = 50;778}779780pub struct Sponsoring;781impl SponsoringResolve<AccountId, Call> for Sponsoring {782	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>783	where784		Call: Dispatchable<Info = DispatchInfo>,785		AccountId: AsRef<[u8]>,786	{787		pallet_nft_transaction_payment::Module::<Runtime>::withdraw_type(who, call)788	}789}790791type SponsorshipHandler = (792	pallet_nft::NftSponsorshipHandler<Runtime>,793	//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,794);795796impl pallet_unq_scheduler::Config for Runtime {797	type Event = Event;798	type Origin = Origin;799	type PalletsOrigin = OriginCaller;800	type Call = Call;801	type MaximumWeight = MaximumSchedulerWeight;802	type ScheduleOrigin = EnsureSigned<AccountId>;803	type MaxScheduledPerBlock = MaxScheduledPerBlock;804	type SponsorshipHandler = SponsorshipHandler;805	type WeightInfo = ();806}807808impl pallet_nft_transaction_payment::Config for Runtime {809	type SponsorshipHandler = SponsorshipHandler;810}811812impl pallet_evm_transaction_payment::Config for Runtime {813	type SponsorshipHandler = (814		pallet_nft::NftEthSponsorshipHandler<Self>,815		pallet_evm_contract_helpers::HelpersContractSponsoring<Self>,816	);817	type Currency = Balances;818}819820impl pallet_nft_charge_transaction::Config for Runtime {821	type SponsorshipHandler = pallet_nft::NftSponsorshipHandler<Runtime>;822}823824// impl pallet_contract_helpers::Config for Runtime {825//	 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;826// }827828parameter_types! {829	// 0x842899ECF380553E8a4de75bF534cdf6fBF64049830	pub const HelpersContractAddress: H160 = H160([831		0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,832	]);833}834835impl pallet_evm_contract_helpers::Config for Runtime {836	type ContractAddress = HelpersContractAddress;837	type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;838}839840construct_runtime!(841	pub enum Runtime where842		Block = Block,843		NodeBlock = opaque::Block,844		UncheckedExtrinsic = UncheckedExtrinsic845	{846		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,847		ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,848849		Aura: pallet_aura::{Pallet, Config<T>} = 22,850		AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,851852		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,853		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,854		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,855		TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,856		Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,857		Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,858		System: system::{Pallet, Call, Storage, Config, Event<T>} = 36,859		Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,860		// Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,861		// Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,862863		// XCM helpers.864		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,865		PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,866		CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,867		DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,868869		// Unique Pallets870		Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,871		Nft: pallet_nft::{Pallet, Call, Storage} = 61,872		Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,873		NftPayment: pallet_nft_transaction_payment::{Pallet, Call, Storage} = 63,874		Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage } = 64,875		// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,876		Common: pallet_common::{Pallet, Storage, Event<T>} = 66,877		Fungible: pallet_fungible::{Pallet, Storage} = 67,878		Refungible: pallet_refungible::{Pallet, Storage} = 68,879		Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,880881		// Frontier882		EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,883		Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,884885		EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,886		EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,887		EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,888		EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,889	}890);891892pub struct TransactionConverter;893894impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {895	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {896		UncheckedExtrinsic::new_unsigned(897			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),898		)899	}900}901902impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {903	fn convert_transaction(904		&self,905		transaction: pallet_ethereum::Transaction,906	) -> opaque::UncheckedExtrinsic {907		let extrinsic = UncheckedExtrinsic::new_unsigned(908			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),909		);910		let encoded = extrinsic.encode();911		opaque::UncheckedExtrinsic::decode(&mut &encoded[..])912			.expect("Encoded extrinsic is always valid")913	}914}915916/// The address format for describing accounts.917pub type Address = sp_runtime::MultiAddress<AccountId, ()>;918/// Block header type as expected by this runtime.919pub type Header = generic::Header<BlockNumber, BlakeTwo256>;920/// Block type as expected by this runtime.921pub type Block = generic::Block<Header, UncheckedExtrinsic>;922/// A Block signed with a Justification923pub type SignedBlock = generic::SignedBlock<Block>;924/// BlockId type as expected by this runtime.925pub type BlockId = generic::BlockId<Block>;926/// The SignedExtension to the basic transaction logic.927pub type SignedExtra = (928	system::CheckSpecVersion<Runtime>,929	// system::CheckTxVersion<Runtime>,930	system::CheckGenesis<Runtime>,931	system::CheckEra<Runtime>,932	system::CheckNonce<Runtime>,933	system::CheckWeight<Runtime>,934	pallet_nft_charge_transaction::ChargeTransactionPayment<Runtime>,935	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,936);937/// Unchecked extrinsic type as expected by this runtime.938pub type UncheckedExtrinsic =939	fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;940/// Extrinsic type that has already been checked.941pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;942/// Executive: handles dispatch to the various modules.943pub type Executive = frame_executive::Executive<944	Runtime,945	Block,946	frame_system::ChainContext<Runtime>,947	Runtime,948	AllPallets,949>;950951impl_opaque_keys! {952	pub struct SessionKeys {953		pub aura: Aura,954	}955}956957impl fp_self_contained::SelfContainedCall for Call {958	type SignedInfo = H160;959960	fn is_self_contained(&self) -> bool {961		match self {962			Call::Ethereum(call) => call.is_self_contained(),963			_ => false,964		}965	}966967	fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {968		match self {969			Call::Ethereum(call) => call.check_self_contained(),970			_ => None,971		}972	}973974	fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {975		match self {976			Call::Ethereum(call) => call.validate_self_contained(info),977			_ => None,978		}979	}980981	fn pre_dispatch_self_contained(982		&self,983		info: &Self::SignedInfo,984	) -> Option<Result<(), TransactionValidityError>> {985		match self {986			Call::Ethereum(call) => call.pre_dispatch_self_contained(info),987			_ => None,988		}989	}990991	fn apply_self_contained(992		self,993		info: Self::SignedInfo,994	) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {995		match self {996			call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(997				Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),998			)),999			_ => None,1000		}1001	}1002}10031004macro_rules! dispatch_nft_runtime {1005	($collection:ident.$method:ident($($name:ident),*)) => {{1006		use pallet_nft::dispatch::Dispatched;10071008		let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::new($collection).unwrap());1009		let dispatch = collection.as_dyn();10101011		dispatch.$method($($name),*)1012	}};1013}1014impl_runtime_apis! {1015	impl up_rpc::NftApi<Block, CrossAccountId, AccountId>1016		for Runtime1017	{1018		fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId> {1019			dispatch_nft_runtime!(collection.account_tokens(account))1020		}1021		fn token_exists(collection: CollectionId, token: TokenId) -> bool {1022			dispatch_nft_runtime!(collection.token_exists(token))1023		}10241025		fn token_owner(collection: CollectionId, token: TokenId) -> CrossAccountId {1026			dispatch_nft_runtime!(collection.token_owner(token))1027		}1028		fn const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {1029			dispatch_nft_runtime!(collection.const_metadata(token))1030		}1031		fn variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {1032			dispatch_nft_runtime!(collection.variable_metadata(token))1033		}10341035		fn collection_tokens(collection: CollectionId) -> u32 {1036			dispatch_nft_runtime!(collection.collection_tokens())1037		}1038		fn account_balance(collection: CollectionId, account: CrossAccountId) -> u32 {1039			dispatch_nft_runtime!(collection.account_balance(account))1040		}1041		fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> u128 {1042			dispatch_nft_runtime!(collection.balance(account, token))1043		}1044		fn allowance(1045			collection: CollectionId,1046			sender: CrossAccountId,1047			spender: CrossAccountId,1048			token: TokenId,1049		) -> u128 {1050			dispatch_nft_runtime!(collection.allowance(sender, spender, token))1051		}10521053		fn eth_contract_code(account: H160) -> Option<Vec<u8>> {1054			<pallet_nft::NftErcSupport<Runtime>>::get_code(&account)1055				.or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account))1056				.or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))1057		}1058		fn adminlist(collection: CollectionId) -> Vec<CrossAccountId> {1059			<pallet_nft::Pallet<Runtime>>::adminlist(collection)1060		}1061		fn allowlist(collection: CollectionId) -> Vec<CrossAccountId> {1062			<pallet_nft::Pallet<Runtime>>::allowlist(collection)1063		}1064		fn last_token_id(collection: CollectionId) -> TokenId {1065			dispatch_nft_runtime!(collection.last_token_id())1066		}1067	}10681069	impl sp_api::Core<Block> for Runtime {1070		fn version() -> RuntimeVersion {1071			VERSION1072		}10731074		fn execute_block(block: Block) {1075			Executive::execute_block(block)1076		}10771078		fn initialize_block(header: &<Block as BlockT>::Header) {1079			Executive::initialize_block(header)1080		}1081	}10821083	impl sp_api::Metadata<Block> for Runtime {1084		fn metadata() -> OpaqueMetadata {1085			OpaqueMetadata::new(Runtime::metadata().into())1086		}1087	}10881089	impl sp_block_builder::BlockBuilder<Block> for Runtime {1090		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {1091			Executive::apply_extrinsic(extrinsic)1092		}10931094		fn finalize_block() -> <Block as BlockT>::Header {1095			Executive::finalize_block()1096		}10971098		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1099			data.create_extrinsics()1100		}11011102		fn check_inherents(1103			block: Block,1104			data: sp_inherents::InherentData,1105		) -> sp_inherents::CheckInherentsResult {1106			data.check_extrinsics(&block)1107		}11081109		// fn random_seed() -> <Block as BlockT>::Hash {1110		//     RandomnessCollectiveFlip::random_seed().01111		// }1112	}11131114	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1115		fn validate_transaction(1116			source: TransactionSource,1117			tx: <Block as BlockT>::Extrinsic,1118			hash: <Block as BlockT>::Hash,1119		) -> TransactionValidity {1120			Executive::validate_transaction(source, tx, hash)1121		}1122	}11231124	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1125		fn offchain_worker(header: &<Block as BlockT>::Header) {1126			Executive::offchain_worker(header)1127		}1128	}11291130	impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1131		fn chain_id() -> u64 {1132			<Runtime as pallet_evm::Config>::ChainId::get()1133		}11341135		fn account_basic(address: H160) -> EVMAccount {1136			EVM::account_basic(&address)1137		}11381139		fn gas_price() -> U256 {1140			<Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1141		}11421143		fn account_code_at(address: H160) -> Vec<u8> {1144			EVM::account_codes(address)1145		}11461147		fn author() -> H160 {1148			<pallet_evm::Pallet<Runtime>>::find_author()1149		}11501151		fn storage_at(address: H160, index: U256) -> H256 {1152			let mut tmp = [0u8; 32];1153			index.to_big_endian(&mut tmp);1154			EVM::account_storages(address, H256::from_slice(&tmp[..]))1155		}11561157		fn call(1158			from: H160,1159			to: H160,1160			data: Vec<u8>,1161			value: U256,1162			gas_limit: U256,1163			gas_price: Option<U256>,1164			nonce: Option<U256>,1165			estimate: bool,1166		) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1167			let config = if estimate {1168				let mut config = <Runtime as pallet_evm::Config>::config().clone();1169				config.estimate = true;1170				Some(config)1171			} else {1172				None1173			};11741175			<Runtime as pallet_evm::Config>::Runner::call(1176				from,1177				to,1178				data,1179				value,1180				gas_limit.low_u64(),1181				gas_price,1182				nonce,1183				config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1184			).map_err(|err| err.into())1185		}11861187		fn create(1188			from: H160,1189			data: Vec<u8>,1190			value: U256,1191			gas_limit: U256,1192			gas_price: Option<U256>,1193			nonce: Option<U256>,1194			estimate: bool,1195		) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1196			let config = if estimate {1197				let mut config = <Runtime as pallet_evm::Config>::config().clone();1198				config.estimate = true;1199				Some(config)1200			} else {1201				None1202			};12031204			<Runtime as pallet_evm::Config>::Runner::create(1205				from,1206				data,1207				value,1208				gas_limit.low_u64(),1209				gas_price,1210				nonce,1211				config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1212			).map_err(|err| err.into())1213		}12141215		fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1216			Ethereum::current_transaction_statuses()1217		}12181219		fn current_block() -> Option<pallet_ethereum::Block> {1220			Ethereum::current_block()1221		}12221223		fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1224			Ethereum::current_receipts()1225		}12261227		fn current_all() -> (1228			Option<pallet_ethereum::Block>,1229			Option<Vec<pallet_ethereum::Receipt>>,1230			Option<Vec<TransactionStatus>>1231		) {1232			(1233				Ethereum::current_block(),1234				Ethereum::current_receipts(),1235				Ethereum::current_transaction_statuses()1236			)1237		}12381239		fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1240			xts.into_iter().filter_map(|xt| match xt.0.function {1241				Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1242				_ => None1243			}).collect()1244		}1245	}12461247	impl sp_session::SessionKeys<Block> for Runtime {1248		fn decode_session_keys(1249			encoded: Vec<u8>,1250		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1251			SessionKeys::decode_into_raw_public_keys(&encoded)1252		}12531254		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1255			SessionKeys::generate(seed)1256		}1257	}12581259	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1260		fn slot_duration() -> sp_consensus_aura::SlotDuration {1261			sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1262		}12631264		fn authorities() -> Vec<AuraId> {1265			Aura::authorities().to_vec()1266		}1267	}12681269	impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1270		fn collect_collation_info() -> cumulus_primitives_core::CollationInfo {1271			ParachainSystem::collect_collation_info()1272		}1273	}12741275	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1276		fn account_nonce(account: AccountId) -> Index {1277			System::account_nonce(account)1278		}1279	}12801281	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1282		fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1283			TransactionPayment::query_info(uxt, len)1284		}1285		fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1286			TransactionPayment::query_fee_details(uxt, len)1287		}1288	}12891290	/*1291	impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1292		for Runtime1293	{1294		fn call(1295			origin: AccountId,1296			dest: AccountId,1297			value: Balance,1298			gas_limit: u64,1299			input_data: Vec<u8>,1300		) -> pallet_contracts_primitives::ContractExecResult {1301			Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1302		}13031304		fn instantiate(1305			origin: AccountId,1306			endowment: Balance,1307			gas_limit: u64,1308			code: pallet_contracts_primitives::Code<Hash>,1309			data: Vec<u8>,1310			salt: Vec<u8>,1311		) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1312		{1313			Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1314		}13151316		fn get_storage(1317			address: AccountId,1318			key: [u8; 32],1319		) -> pallet_contracts_primitives::GetStorageResult {1320			Contracts::get_storage(address, key)1321		}13221323		fn rent_projection(1324			address: AccountId,1325		) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1326			Contracts::rent_projection(address)1327		}1328	}1329	*/13301331	#[cfg(feature = "runtime-benchmarks")]1332	impl frame_benchmarking::Benchmark<Block> for Runtime {1333		fn benchmark_metadata(extra: bool) -> (1334			Vec<frame_benchmarking::BenchmarkList>,1335			Vec<frame_support::traits::StorageInfo>,1336		) {1337			use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};1338			use frame_support::traits::StorageInfoTrait;13391340			let mut list = Vec::<BenchmarkList>::new();13411342			list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);1343			list_benchmark!(list, extra, pallet_nft, Nft);1344			list_benchmark!(list, extra, pallet_inflation, Inflation);1345			list_benchmark!(list, extra, pallet_fungible, Fungible);1346			list_benchmark!(list, extra, pallet_refungible, Refungible);1347			list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);13481349			let storage_info = AllPalletsWithSystem::storage_info();13501351			return (list, storage_info)1352		}13531354		fn dispatch_benchmark(1355			config: frame_benchmarking::BenchmarkConfig1356		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1357			use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};13581359			let allowlist: Vec<TrackedStorageKey> = vec![1360				// Block Number1361				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),1362				// Total Issuance1363				hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1364				// Execution Phase1365				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1366				// Event Count1367				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1368				// System Events1369				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1370			];13711372			let mut batches = Vec::<BenchmarkBatch>::new();1373			let params = (&config, &allowlist);13741375			add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1376			add_benchmark!(params, batches, pallet_nft, Nft);1377			add_benchmark!(params, batches, pallet_inflation, Inflation);1378			add_benchmark!(params, batches, pallet_fungible, Fungible);1379			add_benchmark!(params, batches, pallet_refungible, Refungible);1380			add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);13811382			if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1383			Ok(batches)1384		}1385	}1386}13871388struct CheckInherents;13891390impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1391	fn check_inherents(1392		block: &Block,1393		relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1394	) -> sp_inherents::CheckInherentsResult {1395		let relay_chain_slot = relay_state_proof1396			.read_slot()1397			.expect("Could not read the relay chain slot from the proof");13981399		let inherent_data =1400			cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1401				relay_chain_slot,1402				sp_std::time::Duration::from_secs(6),1403			)1404			.create_inherent_data()1405			.expect("Could not create the timestamp inherent data");14061407		inherent_data.check_extrinsics(block)1408	}1409}14101411cumulus_pallet_parachain_system::register_validate_block!(1412	Runtime = Runtime,1413	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1414	CheckInherents = CheckInherents,1415);
after · runtime/src/lib.rs
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "1024"]11#![allow(clippy::from_over_into, clippy::identity_op)]12#![allow(clippy::fn_to_numeric_cast_with_truncation)]13// Make the WASM binary available.14#[cfg(feature = "std")]15include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1617use sp_api::impl_runtime_apis;18use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};19// #[cfg(any(feature = "std", test))]20// pub use sp_runtime::BuildStorage;2122use sp_runtime::{23	Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,24	traits::{25		AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify, AccountIdConversion,26	},27	transaction_validity::{TransactionSource, TransactionValidity},28	ApplyExtrinsicResult, MultiSignature,29};3031use sp_std::prelude::*;3233#[cfg(feature = "std")]34use sp_version::NativeVersion;35use sp_version::RuntimeVersion;36pub use pallet_transaction_payment::{37	Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,38};39// A few exports that help ease life for downstream crates.40pub use pallet_balances::Call as BalancesCall;41pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};42pub use frame_support::{43	construct_runtime, match_type,44	dispatch::DispatchResult,45	PalletId, parameter_types, StorageValue, ConsensusEngineId,46	traits::{47		Everything, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem,48		LockIdentifier, OnUnbalanced, Randomness, FindAuthor,49	},50	weights::{51		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},52		DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,53		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,54	},55};56use nft_data_structs::*;57// use pallet_contracts::weights::WeightInfo;58// #[cfg(any(feature = "std", test))]59use frame_system::{60	self as system, EnsureRoot, EnsureSigned,61	limits::{BlockWeights, BlockLength},62};63use sp_arithmetic::{64	traits::{BaseArithmetic, Unsigned},65};66use smallvec::smallvec;67use codec::{Encode, Decode};68use pallet_evm::{Account as EVMAccount, FeeCalculator, OnMethodCall};69use fp_rpc::TransactionStatus;70use sp_core::crypto::Public;71use sp_runtime::{72	traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf},73	transaction_validity::TransactionValidityError,74};7576// pub use pallet_timestamp::Call as TimestampCall;77pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;7879// Polkadot imports80use pallet_xcm::XcmPassthrough;81use polkadot_parachain::primitives::Sibling;82use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};83use xcm_builder::{84	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,85	EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset,86	ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,87	SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,88	SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,89};90use xcm_executor::{Config, XcmExecutor};9192// mod chain_extension;93// use crate::chain_extension::{NFTExtension, Imbalance};9495/// An index to a block.96pub type BlockNumber = u32;9798/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.99pub type Signature = MultiSignature;100101/// Some way of identifying an account on the chain. We intentionally make it equivalent102/// to the public key of our transaction signing scheme.103pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;104105pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;106107/// The type for looking up accounts. We don't expect more than 4 billion of them, but you108/// never know...109pub type AccountIndex = u32;110111/// Balance of an account.112pub type Balance = u128;113114/// Index of a transaction in the chain.115pub type Index = u32;116117/// A hash of some data used by the chain.118pub type Hash = sp_core::H256;119120/// Digest item type.121pub type DigestItem = generic::DigestItem<Hash>;122123/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know124/// the specifics of the runtime. They can then be made to be agnostic over specific formats125/// of data like extrinsics, allowing for them to continue syncing the network through upgrades126/// to even the core data structures.127pub mod opaque {128	use super::*;129130	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;131132	/// Opaque block type.133	pub type Block = generic::Block<Header, UncheckedExtrinsic>;134135	pub type SessionHandlers = ();136137	impl_opaque_keys! {138		pub struct SessionKeys {139			pub aura: Aura,140		}141	}142}143144/// This runtime version.145pub const VERSION: RuntimeVersion = RuntimeVersion {146	spec_name: create_runtime_str!("opal"),147	impl_name: create_runtime_str!("opal"),148	authoring_version: 1,149	spec_version: 912202,150	impl_version: 1,151	apis: RUNTIME_API_VERSIONS,152	transaction_version: 1,153};154155pub const MILLISECS_PER_BLOCK: u64 = 12000;156157pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;158159// These time units are defined in number of blocks.160pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);161pub const HOURS: BlockNumber = MINUTES * 60;162pub const DAYS: BlockNumber = HOURS * 24;163164parameter_types! {165	pub const DefaultSponsoringRateLimit: BlockNumber = 1 * DAYS;166}167168#[derive(codec::Encode, codec::Decode)]169pub enum XCMPMessage<XAccountId, XBalance> {170	/// Transfer tokens to the given account from the Parachain account.171	TransferToken(XAccountId, XBalance),172}173174/// The version information used to identify this runtime when compiled natively.175#[cfg(feature = "std")]176pub fn native_version() -> NativeVersion {177	NativeVersion {178		runtime_version: VERSION,179		can_author_with: Default::default(),180	}181}182183type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;184185pub struct DealWithFees;186impl OnUnbalanced<NegativeImbalance> for DealWithFees {187	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {188		if let Some(fees) = fees_then_tips.next() {189			// for fees, 100% to treasury190			let mut split = fees.ration(100, 0);191			if let Some(tips) = fees_then_tips.next() {192				// for tips, if any, 100% to treasury193				tips.ration_merge_into(100, 0, &mut split);194			}195			Treasury::on_unbalanced(split.0);196			// Author::on_unbalanced(split.1);197		}198	}199}200201/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.202/// This is used to limit the maximal weight of a single extrinsic.203const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);204/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used205/// by  Operational  extrinsics.206const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);207/// We allow for 2 seconds of compute with a 6 second average block time.208const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2;209210parameter_types! {211	pub const BlockHashCount: BlockNumber = 2400;212	pub RuntimeBlockLength: BlockLength =213		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);214	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);215	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;216	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()217		.base_block(BlockExecutionWeight::get())218		.for_class(DispatchClass::all(), |weights| {219			weights.base_extrinsic = ExtrinsicBaseWeight::get();220		})221		.for_class(DispatchClass::Normal, |weights| {222			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);223		})224		.for_class(DispatchClass::Operational, |weights| {225			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);226			// Operational transactions have some extra reserved space, so that they227			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.228			weights.reserved = Some(229				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT230			);231		})232		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)233		.build_or_panic();234	pub const Version: RuntimeVersion = VERSION;235	pub const SS58Prefix: u8 = 42;236}237238parameter_types! {239	pub const ChainId: u64 = 8888;240}241242pub struct FixedFee;243impl FeeCalculator for FixedFee {244	fn min_gas_price() -> U256 {245		1.into()246	}247}248249impl pallet_evm::Config for Runtime {250	type BlockGasLimit = BlockGasLimit;251	type FeeCalculator = FixedFee;252	type GasWeightMapping = ();253	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;254	type CallOrigin = EnsureAddressTruncated;255	type WithdrawOrigin = EnsureAddressTruncated;256	type AddressMapping = HashedAddressMapping<Self::Hashing>;257	type Precompiles = ();258	type Currency = Balances;259	type Event = Event;260	type OnMethodCall = (261		pallet_evm_migration::OnMethodCall<Self>,262		pallet_nft::NftErcSupport<Self>,263		pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,264	);265	type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;266	type ChainId = ChainId;267	type Runner = pallet_evm::runner::stack::Runner<Self>;268	type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;269	type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;270	type FindAuthor = EthereumFindAuthor<Aura>;271}272273impl pallet_evm_migration::Config for Runtime {274	type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;275}276277pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);278impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {279	fn find_author<'a, I>(digests: I) -> Option<H160>280	where281		I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,282	{283		if let Some(author_index) = F::find_author(digests) {284			let authority_id = Aura::authorities()[author_index as usize].clone();285			return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));286		}287		None288	}289}290291parameter_types! {292	pub BlockGasLimit: U256 = U256::from(u32::max_value());293}294295impl pallet_ethereum::Config for Runtime {296	type Event = Event;297	type StateRoot = pallet_ethereum::IntermediateStateRoot;298	type EvmSubmitLog = pallet_evm::Pallet<Self>;299}300301impl pallet_randomness_collective_flip::Config for Runtime {}302303impl system::Config for Runtime {304	/// The data to be stored in an account.305	type AccountData = pallet_balances::AccountData<Balance>;306	/// The identifier used to distinguish between accounts.307	type AccountId = AccountId;308	/// The basic call filter to use in dispatchable.309	type BaseCallFilter = Everything;310	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).311	type BlockHashCount = BlockHashCount;312	/// The maximum length of a block (in bytes).313	type BlockLength = RuntimeBlockLength;314	/// The index type for blocks.315	type BlockNumber = BlockNumber;316	/// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.317	type BlockWeights = RuntimeBlockWeights;318	/// The aggregated dispatch type that is available for extrinsics.319	type Call = Call;320	/// The weight of database operations that the runtime can invoke.321	type DbWeight = RocksDbWeight;322	/// The ubiquitous event type.323	type Event = Event;324	/// The type for hashing blocks and tries.325	type Hash = Hash;326	/// The hashing algorithm used.327	type Hashing = BlakeTwo256;328	/// The header type.329	type Header = generic::Header<BlockNumber, BlakeTwo256>;330	/// The index type for storing how many extrinsics an account has signed.331	type Index = Index;332	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.333	type Lookup = AccountIdLookup<AccountId, ()>;334	/// What to do if an account is fully reaped from the system.335	type OnKilledAccount = ();336	/// What to do if a new account is created.337	type OnNewAccount = ();338	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;339	/// The ubiquitous origin type.340	type Origin = Origin;341	/// This type is being generated by `construct_runtime!`.342	type PalletInfo = PalletInfo;343	/// This is used as an identifier of the chain. 42 is the generic substrate prefix.344	type SS58Prefix = SS58Prefix;345	/// Weight information for the extrinsics of this pallet.346	type SystemWeightInfo = system::weights::SubstrateWeight<Self>;347	/// Version of the runtime.348	type Version = Version;349}350351parameter_types! {352	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;353}354355impl pallet_timestamp::Config for Runtime {356	/// A timestamp: milliseconds since the unix epoch.357	type Moment = u64;358	type OnTimestampSet = ();359	type MinimumPeriod = MinimumPeriod;360	type WeightInfo = ();361}362363parameter_types! {364	// pub const ExistentialDeposit: u128 = 500;365	pub const ExistentialDeposit: u128 = 0;366	pub const MaxLocks: u32 = 50;367}368369impl pallet_balances::Config for Runtime {370	type MaxLocks = MaxLocks;371	type MaxReserves = ();372	type ReserveIdentifier = [u8; 8];373	/// The type for recording an account's balance.374	type Balance = Balance;375	/// The ubiquitous event type.376	type Event = Event;377	type DustRemoval = Treasury;378	type ExistentialDeposit = ExistentialDeposit;379	type AccountStore = System;380	type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;381}382383pub const MICROUNIQUE: Balance = 1_000_000_000;384pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;385pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;386pub const UNIQUE: Balance = 100 * CENTIUNIQUE;387388pub const fn deposit(items: u32, bytes: u32) -> Balance {389	items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE390}391392/*393parameter_types! {394	pub TombstoneDeposit: Balance = deposit(395		1,396		sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,397	);398	pub DepositPerContract: Balance = TombstoneDeposit::get();399	pub const DepositPerStorageByte: Balance = deposit(0, 1);400	pub const DepositPerStorageItem: Balance = deposit(1, 0);401	pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);402	pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;403	pub const SignedClaimHandicap: u32 = 2;404	pub const MaxDepth: u32 = 32;405	pub const MaxValueSize: u32 = 16 * 1024;406	pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb407	// The lazy deletion runs inside on_initialize.408	pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *409		RuntimeBlockWeights::get().max_block;410	// The weight needed for decoding the queue should be less or equal than a fifth411	// of the overall weight dedicated to the lazy deletion.412	pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (413			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -414			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)415		)) / 5) as u32;416	pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();417}418419impl pallet_contracts::Config for Runtime {420	type Time = Timestamp;421	type Randomness = RandomnessCollectiveFlip;422	type Currency = Balances;423	type Event = Event;424	type RentPayment = ();425	type SignedClaimHandicap = SignedClaimHandicap;426	type TombstoneDeposit = TombstoneDeposit;427	type DepositPerContract = DepositPerContract;428	type DepositPerStorageByte = DepositPerStorageByte;429	type DepositPerStorageItem = DepositPerStorageItem;430	type RentFraction = RentFraction;431	type SurchargeReward = SurchargeReward;432	type WeightPrice = pallet_transaction_payment::Pallet<Self>;433	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;434	type ChainExtension = NFTExtension;435	type DeletionQueueDepth = DeletionQueueDepth;436	type DeletionWeightLimit = DeletionWeightLimit;437	type Schedule = Schedule;438	type CallStack = [pallet_contracts::Frame<Self>; 31];439}440*/441442parameter_types! {443	pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer444	/// This value increases the priority of `Operational` transactions by adding445	/// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.446	pub const OperationalFeeMultiplier: u8 = 5;447}448449/// Linear implementor of `WeightToFeePolynomial`450pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);451452impl<T> WeightToFeePolynomial for LinearFee<T>453where454	T: BaseArithmetic + From<u32> + Copy + Unsigned,455{456	type Balance = T;457458	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {459		smallvec!(WeightToFeeCoefficient {460			coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer461			coeff_frac: Perbill::zero(),462			negative: false,463			degree: 1,464		})465	}466}467468impl pallet_transaction_payment::Config for Runtime {469	type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;470	type TransactionByteFee = TransactionByteFee;471	type OperationalFeeMultiplier = OperationalFeeMultiplier;472	type WeightToFee = LinearFee<Balance>;473	type FeeMultiplierUpdate = ();474}475476parameter_types! {477	pub const ProposalBond: Permill = Permill::from_percent(5);478	pub const ProposalBondMinimum: Balance = 1 * UNIQUE;479	pub const SpendPeriod: BlockNumber = 5 * MINUTES;480	pub const Burn: Permill = Permill::from_percent(0);481	pub const TipCountdown: BlockNumber = 1 * DAYS;482	pub const TipFindersFee: Percent = Percent::from_percent(20);483	pub const TipReportDepositBase: Balance = 1 * UNIQUE;484	pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;485	pub const BountyDepositBase: Balance = 1 * UNIQUE;486	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;487	pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");488	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;489	pub const MaximumReasonLength: u32 = 16384;490	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);491	pub const BountyValueMinimum: Balance = 5 * UNIQUE;492	pub const MaxApprovals: u32 = 100;493}494495impl pallet_treasury::Config for Runtime {496	type PalletId = TreasuryModuleId;497	type Currency = Balances;498	type ApproveOrigin = EnsureRoot<AccountId>;499	type RejectOrigin = EnsureRoot<AccountId>;500	type Event = Event;501	type OnSlash = ();502	type ProposalBond = ProposalBond;503	type ProposalBondMinimum = ProposalBondMinimum;504	type SpendPeriod = SpendPeriod;505	type Burn = Burn;506	type BurnDestination = ();507	type SpendFunds = ();508	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;509	type MaxApprovals = MaxApprovals;510}511512impl pallet_sudo::Config for Runtime {513	type Event = Event;514	type Call = Call;515}516517pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);518519impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider520	for RelayChainBlockNumberProvider<T>521{522	type BlockNumber = BlockNumber;523524	fn current_block_number() -> Self::BlockNumber {525		cumulus_pallet_parachain_system::Pallet::<T>::validation_data()526			.map(|d| d.relay_parent_number)527			.unwrap_or_default()528	}529}530531parameter_types! {532	pub const MinVestedTransfer: Balance = 10 * UNIQUE;533	pub const MaxVestingSchedules: u32 = 28;534}535536impl orml_vesting::Config for Runtime {537	type Event = Event;538	type Currency = pallet_balances::Pallet<Runtime>;539	type MinVestedTransfer = MinVestedTransfer;540	type VestedTransferOrigin = EnsureSigned<AccountId>;541	type WeightInfo = ();542	type MaxVestingSchedules = MaxVestingSchedules;543	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;544}545546parameter_types! {547	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;548	pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;549}550551impl cumulus_pallet_parachain_system::Config for Runtime {552	type Event = Event;553	type OnValidationData = ();554	type SelfParaId = parachain_info::Pallet<Self>;555	// type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<556	// 	MaxDownwardMessageWeight,557	// 	XcmExecutor<XcmConfig>,558	// 	Call,559	// >;560	type OutboundXcmpMessageSource = XcmpQueue;561	type DmpMessageHandler = DmpQueue;562	type ReservedDmpWeight = ReservedDmpWeight;563	type ReservedXcmpWeight = ReservedXcmpWeight;564	type XcmpMessageHandler = XcmpQueue;565}566567impl parachain_info::Config for Runtime {}568569impl cumulus_pallet_aura_ext::Config for Runtime {}570571parameter_types! {572	pub const RelayLocation: MultiLocation = MultiLocation::parent();573	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;574	pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();575	pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();576}577578/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used579/// when determining ownership of accounts for asset transacting and when attempting to use XCM580/// `Transact` in order to determine the dispatch Origin.581pub type LocationToAccountId = (582	// The parent (Relay-chain) origin converts to the default `AccountId`.583	ParentIsDefault<AccountId>,584	// Sibling parachain origins convert to AccountId via the `ParaId::into`.585	SiblingParachainConvertsVia<Sibling, AccountId>,586	// Straight up local `AccountId32` origins just alias directly to `AccountId`.587	AccountId32Aliases<RelayNetwork, AccountId>,588);589590/// Means for transacting assets on this chain.591pub type LocalAssetTransactor = CurrencyAdapter<592	// Use this currency:593	Balances,594	// Use this currency when it is a fungible asset matching the given location or name:595	IsConcrete<RelayLocation>,596	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:597	LocationToAccountId,598	// Our chain's account ID type (we can't get away without mentioning it explicitly):599	AccountId,600	// We don't track any teleports.601	(),602>;603604/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,605/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can606/// biases the kind of local `Origin` it will become.607pub type XcmOriginToTransactDispatchOrigin = (608	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location609	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for610	// foreign chains who want to have a local sovereign account on this chain which they control.611	SovereignSignedViaLocation<LocationToAccountId, Origin>,612	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when613	// recognised.614	RelayChainAsNative<RelayOrigin, Origin>,615	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when616	// recognised.617	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,618	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a619	// transaction from the Root origin.620	ParentAsSuperuser<Origin>,621	// Native signed account converter; this just converts an `AccountId32` origin into a normal622	// `Origin::Signed` origin of the same 32-byte value.623	SignedAccountId32AsNative<RelayNetwork, Origin>,624	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.625	XcmPassthrough<Origin>,626);627628parameter_types! {629	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.630	pub UnitWeightCost: Weight = 1_000_000;631	// 1200 UNIQUEs buy 1 second of weight.632	pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);633	pub const MaxInstructions: u32 = 100;634	pub const MaxAuthorities: u32 = 100_000;635}636637match_type! {638	pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {639		MultiLocation { parents: 1, interior: Here } |640		MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }641	};642}643644pub type Barrier = (645	TakeWeightCredit,646	AllowTopLevelPaidExecutionFrom<Everything>,647	AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,648	// ^^^ Parent & its unit plurality gets free execution649);650651pub struct XcmConfig;652impl Config for XcmConfig {653	type Call = Call;654	type XcmSender = XcmRouter;655	// How to withdraw and deposit an asset.656	type AssetTransactor = LocalAssetTransactor;657	type OriginConverter = XcmOriginToTransactDispatchOrigin;658	type IsReserve = NativeAsset;659	type IsTeleporter = (); // Teleportation is disabled660	type LocationInverter = LocationInverter<Ancestry>;661	type Barrier = Barrier;662	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;663	type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;664	type ResponseHandler = (); // Don't handle responses for now.665	type SubscriptionService = PolkadotXcm;666667	type AssetTrap = PolkadotXcm;668	type AssetClaims = PolkadotXcm;669}670671// parameter_types! {672// 	pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;673// }674675/// No local origins on this chain are allowed to dispatch XCM sends/executions.676pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);677678/// The means for routing XCM messages which are not for local execution into the right message679/// queues.680pub type XcmRouter = (681	// Two routers - use UMP to communicate with the relay chain:682	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,683	// ..and XCMP to communicate with the sibling chains.684	XcmpQueue,685);686687impl pallet_evm_coder_substrate::Config for Runtime {688	type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;689}690691impl pallet_xcm::Config for Runtime {692	type Event = Event;693	type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;694	type XcmRouter = XcmRouter;695	type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;696	type XcmExecuteFilter = Everything;697	type XcmExecutor = XcmExecutor<XcmConfig>;698	type XcmTeleportFilter = Everything;699	type XcmReserveTransferFilter = Everything;700	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;701	type LocationInverter = LocationInverter<Ancestry>;702	type Origin = Origin;703	type Call = Call;704	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;705	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;706}707708impl cumulus_pallet_xcm::Config for Runtime {709	type Event = Event;710	type XcmExecutor = XcmExecutor<XcmConfig>;711}712713impl cumulus_pallet_xcmp_queue::Config for Runtime {714	type Event = Event;715	type XcmExecutor = XcmExecutor<XcmConfig>;716	type ChannelInfo = ParachainSystem;717	type VersionWrapper = ();718}719720impl cumulus_pallet_dmp_queue::Config for Runtime {721	type Event = Event;722	type XcmExecutor = XcmExecutor<XcmConfig>;723	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;724}725726impl pallet_aura::Config for Runtime {727	type AuthorityId = AuraId;728	type DisabledValidators = ();729	type MaxAuthorities = MaxAuthorities;730}731732parameter_types! {733	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();734	pub const CollectionCreationPrice: Balance = 100 * UNIQUE;735}736737impl pallet_common::Config for Runtime {738	type Event = Event;739	type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;740	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;741	type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;742743	type Currency = Balances;744	type CollectionCreationPrice = CollectionCreationPrice;745	type TreasuryAccountId = TreasuryAccountId;746}747748impl pallet_fungible::Config for Runtime {749	type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;750}751impl pallet_refungible::Config for Runtime {752	type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;753}754impl pallet_nonfungible::Config for Runtime {755	type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;756}757758/// Used for the pallet nft in `./nft.rs`759impl pallet_nft::Config for Runtime {760	type WeightInfo = pallet_nft::weights::SubstrateWeight<Self>;761}762763parameter_types! {764	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied765}766767/// Used for the pallet inflation768impl pallet_inflation::Config for Runtime {769	type Currency = Balances;770	type TreasuryAccountId = TreasuryAccountId;771	type InflationBlockInterval = InflationBlockInterval;772}773774// parameter_types! {775// 	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *776// 		RuntimeBlockWeights::get().max_block;777// 	pub const MaxScheduledPerBlock: u32 = 50;778// }779780type EvmSponsorshipHandler = (781	pallet_nft::NftEthSponsorshipHandler<Runtime>,782	pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,783);784type SponsorshipHandler = (785	pallet_nft::NftSponsorshipHandler<Runtime>,786	//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,787	pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,788);789790// impl pallet_unq_scheduler::Config for Runtime {791// 	type Event = Event;792// 	type Origin = Origin;793// 	type PalletsOrigin = OriginCaller;794// 	type Call = Call;795// 	type MaximumWeight = MaximumSchedulerWeight;796// 	type ScheduleOrigin = EnsureSigned<AccountId>;797// 	type MaxScheduledPerBlock = MaxScheduledPerBlock;798// 	type SponsorshipHandler = SponsorshipHandler;799// 	type WeightInfo = ();800// }801802impl pallet_evm_transaction_payment::Config for Runtime {803	type EvmSponsorshipHandler = EvmSponsorshipHandler;804	type Currency = Balances;805	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;806	type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;807}808809impl pallet_nft_charge_transaction::Config for Runtime {810	type SponsorshipHandler = SponsorshipHandler;811}812813// impl pallet_contract_helpers::Config for Runtime {814//	 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;815// }816817parameter_types! {818	// 0x842899ECF380553E8a4de75bF534cdf6fBF64049819	pub const HelpersContractAddress: H160 = H160([820		0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,821	]);822}823824impl pallet_evm_contract_helpers::Config for Runtime {825	type ContractAddress = HelpersContractAddress;826	type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;827}828829construct_runtime!(830	pub enum Runtime where831		Block = Block,832		NodeBlock = opaque::Block,833		UncheckedExtrinsic = UncheckedExtrinsic834	{835		ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,836		ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,837838		Aura: pallet_aura::{Pallet, Config<T>} = 22,839		AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,840841		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,842		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,843		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,844		TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,845		Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,846		Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,847		System: system::{Pallet, Call, Storage, Config, Event<T>} = 36,848		Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,849		// Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,850		// Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,851852		// XCM helpers.853		XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,854		PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,855		CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,856		DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,857858		// Unique Pallets859		Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,860		Nft: pallet_nft::{Pallet, Call, Storage} = 61,861		// Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,862		// free = 63863		Charging: pallet_nft_charge_transaction::{Pallet, Call, Storage } = 64,864		// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,865		Common: pallet_common::{Pallet, Storage, Event<T>} = 66,866		Fungible: pallet_fungible::{Pallet, Storage} = 67,867		Refungible: pallet_refungible::{Pallet, Storage} = 68,868		Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,869870		// Frontier871		EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,872		Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,873874		EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,875		EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,876		EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,877		EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,878	}879);880881pub struct TransactionConverter;882883impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {884	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {885		UncheckedExtrinsic::new_unsigned(886			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),887		)888	}889}890891impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {892	fn convert_transaction(893		&self,894		transaction: pallet_ethereum::Transaction,895	) -> opaque::UncheckedExtrinsic {896		let extrinsic = UncheckedExtrinsic::new_unsigned(897			pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),898		);899		let encoded = extrinsic.encode();900		opaque::UncheckedExtrinsic::decode(&mut &encoded[..])901			.expect("Encoded extrinsic is always valid")902	}903}904905/// The address format for describing accounts.906pub type Address = sp_runtime::MultiAddress<AccountId, ()>;907/// Block header type as expected by this runtime.908pub type Header = generic::Header<BlockNumber, BlakeTwo256>;909/// Block type as expected by this runtime.910pub type Block = generic::Block<Header, UncheckedExtrinsic>;911/// A Block signed with a Justification912pub type SignedBlock = generic::SignedBlock<Block>;913/// BlockId type as expected by this runtime.914pub type BlockId = generic::BlockId<Block>;915/// The SignedExtension to the basic transaction logic.916pub type SignedExtra = (917	system::CheckSpecVersion<Runtime>,918	// system::CheckTxVersion<Runtime>,919	system::CheckGenesis<Runtime>,920	system::CheckEra<Runtime>,921	system::CheckNonce<Runtime>,922	system::CheckWeight<Runtime>,923	pallet_nft_charge_transaction::ChargeTransactionPayment<Runtime>,924	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,925);926/// Unchecked extrinsic type as expected by this runtime.927pub type UncheckedExtrinsic =928	fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;929/// Extrinsic type that has already been checked.930pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;931/// Executive: handles dispatch to the various modules.932pub type Executive = frame_executive::Executive<933	Runtime,934	Block,935	frame_system::ChainContext<Runtime>,936	Runtime,937	AllPallets,938>;939940impl_opaque_keys! {941	pub struct SessionKeys {942		pub aura: Aura,943	}944}945946impl fp_self_contained::SelfContainedCall for Call {947	type SignedInfo = H160;948949	fn is_self_contained(&self) -> bool {950		match self {951			Call::Ethereum(call) => call.is_self_contained(),952			_ => false,953		}954	}955956	fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {957		match self {958			Call::Ethereum(call) => call.check_self_contained(),959			_ => None,960		}961	}962963	fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {964		match self {965			Call::Ethereum(call) => call.validate_self_contained(info),966			_ => None,967		}968	}969970	fn pre_dispatch_self_contained(971		&self,972		info: &Self::SignedInfo,973	) -> Option<Result<(), TransactionValidityError>> {974		match self {975			Call::Ethereum(call) => call.pre_dispatch_self_contained(info),976			_ => None,977		}978	}979980	fn apply_self_contained(981		self,982		info: Self::SignedInfo,983	) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {984		match self {985			call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(986				Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),987			)),988			_ => None,989		}990	}991}992993macro_rules! dispatch_nft_runtime {994	($collection:ident.$method:ident($($name:ident),*)) => {{995		use pallet_nft::dispatch::Dispatched;996997		let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::new($collection).unwrap());998		let dispatch = collection.as_dyn();9991000		dispatch.$method($($name),*)1001	}};1002}1003impl_runtime_apis! {1004	impl up_rpc::NftApi<Block, CrossAccountId, AccountId>1005		for Runtime1006	{1007		fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId> {1008			dispatch_nft_runtime!(collection.account_tokens(account))1009		}1010		fn token_exists(collection: CollectionId, token: TokenId) -> bool {1011			dispatch_nft_runtime!(collection.token_exists(token))1012		}10131014		fn token_owner(collection: CollectionId, token: TokenId) -> CrossAccountId {1015			dispatch_nft_runtime!(collection.token_owner(token))1016		}1017		fn const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {1018			dispatch_nft_runtime!(collection.const_metadata(token))1019		}1020		fn variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {1021			dispatch_nft_runtime!(collection.variable_metadata(token))1022		}10231024		fn collection_tokens(collection: CollectionId) -> u32 {1025			dispatch_nft_runtime!(collection.collection_tokens())1026		}1027		fn account_balance(collection: CollectionId, account: CrossAccountId) -> u32 {1028			dispatch_nft_runtime!(collection.account_balance(account))1029		}1030		fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> u128 {1031			dispatch_nft_runtime!(collection.balance(account, token))1032		}1033		fn allowance(1034			collection: CollectionId,1035			sender: CrossAccountId,1036			spender: CrossAccountId,1037			token: TokenId,1038		) -> u128 {1039			dispatch_nft_runtime!(collection.allowance(sender, spender, token))1040		}10411042		fn eth_contract_code(account: H160) -> Option<Vec<u8>> {1043			<pallet_nft::NftErcSupport<Runtime>>::get_code(&account)1044				.or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account))1045				.or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))1046		}1047		fn adminlist(collection: CollectionId) -> Vec<CrossAccountId> {1048			<pallet_common::Pallet<Runtime>>::adminlist(collection)1049		}1050		fn allowlist(collection: CollectionId) -> Vec<CrossAccountId> {1051			<pallet_common::Pallet<Runtime>>::allowlist(collection)1052		}1053		fn allowed(collection: CollectionId, user: CrossAccountId) -> bool {1054			<pallet_common::Pallet<Runtime>>::allowed(collection, user)1055		}1056		fn last_token_id(collection: CollectionId) -> TokenId {1057			dispatch_nft_runtime!(collection.last_token_id())1058		}1059		fn collection_by_id(collection: CollectionId) -> Option<Collection<AccountId>> {1060			<pallet_common::CollectionById<Runtime>>::get(collection)1061		}1062		fn collection_stats() -> CollectionStats {1063			<pallet_common::Pallet<Runtime>>::collection_stats()1064		}1065	}10661067	impl sp_api::Core<Block> for Runtime {1068		fn version() -> RuntimeVersion {1069			VERSION1070		}10711072		fn execute_block(block: Block) {1073			Executive::execute_block(block)1074		}10751076		fn initialize_block(header: &<Block as BlockT>::Header) {1077			Executive::initialize_block(header)1078		}1079	}10801081	impl sp_api::Metadata<Block> for Runtime {1082		fn metadata() -> OpaqueMetadata {1083			OpaqueMetadata::new(Runtime::metadata().into())1084		}1085	}10861087	impl sp_block_builder::BlockBuilder<Block> for Runtime {1088		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {1089			Executive::apply_extrinsic(extrinsic)1090		}10911092		fn finalize_block() -> <Block as BlockT>::Header {1093			Executive::finalize_block()1094		}10951096		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1097			data.create_extrinsics()1098		}10991100		fn check_inherents(1101			block: Block,1102			data: sp_inherents::InherentData,1103		) -> sp_inherents::CheckInherentsResult {1104			data.check_extrinsics(&block)1105		}11061107		// fn random_seed() -> <Block as BlockT>::Hash {1108		//     RandomnessCollectiveFlip::random_seed().01109		// }1110	}11111112	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1113		fn validate_transaction(1114			source: TransactionSource,1115			tx: <Block as BlockT>::Extrinsic,1116			hash: <Block as BlockT>::Hash,1117		) -> TransactionValidity {1118			Executive::validate_transaction(source, tx, hash)1119		}1120	}11211122	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1123		fn offchain_worker(header: &<Block as BlockT>::Header) {1124			Executive::offchain_worker(header)1125		}1126	}11271128	impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1129		fn chain_id() -> u64 {1130			<Runtime as pallet_evm::Config>::ChainId::get()1131		}11321133		fn account_basic(address: H160) -> EVMAccount {1134			EVM::account_basic(&address)1135		}11361137		fn gas_price() -> U256 {1138			<Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1139		}11401141		fn account_code_at(address: H160) -> Vec<u8> {1142			EVM::account_codes(address)1143		}11441145		fn author() -> H160 {1146			<pallet_evm::Pallet<Runtime>>::find_author()1147		}11481149		fn storage_at(address: H160, index: U256) -> H256 {1150			let mut tmp = [0u8; 32];1151			index.to_big_endian(&mut tmp);1152			EVM::account_storages(address, H256::from_slice(&tmp[..]))1153		}11541155		fn call(1156			from: H160,1157			to: H160,1158			data: Vec<u8>,1159			value: U256,1160			gas_limit: U256,1161			gas_price: Option<U256>,1162			nonce: Option<U256>,1163			estimate: bool,1164		) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1165			let config = if estimate {1166				let mut config = <Runtime as pallet_evm::Config>::config().clone();1167				config.estimate = true;1168				Some(config)1169			} else {1170				None1171			};11721173			<Runtime as pallet_evm::Config>::Runner::call(1174				from,1175				to,1176				data,1177				value,1178				gas_limit.low_u64(),1179				gas_price,1180				nonce,1181				config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1182			).map_err(|err| err.into())1183		}11841185		fn create(1186			from: H160,1187			data: Vec<u8>,1188			value: U256,1189			gas_limit: U256,1190			gas_price: Option<U256>,1191			nonce: Option<U256>,1192			estimate: bool,1193		) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1194			let config = if estimate {1195				let mut config = <Runtime as pallet_evm::Config>::config().clone();1196				config.estimate = true;1197				Some(config)1198			} else {1199				None1200			};12011202			<Runtime as pallet_evm::Config>::Runner::create(1203				from,1204				data,1205				value,1206				gas_limit.low_u64(),1207				gas_price,1208				nonce,1209				config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1210			).map_err(|err| err.into())1211		}12121213		fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1214			Ethereum::current_transaction_statuses()1215		}12161217		fn current_block() -> Option<pallet_ethereum::Block> {1218			Ethereum::current_block()1219		}12201221		fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1222			Ethereum::current_receipts()1223		}12241225		fn current_all() -> (1226			Option<pallet_ethereum::Block>,1227			Option<Vec<pallet_ethereum::Receipt>>,1228			Option<Vec<TransactionStatus>>1229		) {1230			(1231				Ethereum::current_block(),1232				Ethereum::current_receipts(),1233				Ethereum::current_transaction_statuses()1234			)1235		}12361237		fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1238			xts.into_iter().filter_map(|xt| match xt.0.function {1239				Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1240				_ => None1241			}).collect()1242		}1243	}12441245	impl sp_session::SessionKeys<Block> for Runtime {1246		fn decode_session_keys(1247			encoded: Vec<u8>,1248		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1249			SessionKeys::decode_into_raw_public_keys(&encoded)1250		}12511252		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1253			SessionKeys::generate(seed)1254		}1255	}12561257	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1258		fn slot_duration() -> sp_consensus_aura::SlotDuration {1259			sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1260		}12611262		fn authorities() -> Vec<AuraId> {1263			Aura::authorities().to_vec()1264		}1265	}12661267	impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1268		fn collect_collation_info() -> cumulus_primitives_core::CollationInfo {1269			ParachainSystem::collect_collation_info()1270		}1271	}12721273	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1274		fn account_nonce(account: AccountId) -> Index {1275			System::account_nonce(account)1276		}1277	}12781279	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1280		fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1281			TransactionPayment::query_info(uxt, len)1282		}1283		fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1284			TransactionPayment::query_fee_details(uxt, len)1285		}1286	}12871288	/*1289	impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1290		for Runtime1291	{1292		fn call(1293			origin: AccountId,1294			dest: AccountId,1295			value: Balance,1296			gas_limit: u64,1297			input_data: Vec<u8>,1298		) -> pallet_contracts_primitives::ContractExecResult {1299			Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1300		}13011302		fn instantiate(1303			origin: AccountId,1304			endowment: Balance,1305			gas_limit: u64,1306			code: pallet_contracts_primitives::Code<Hash>,1307			data: Vec<u8>,1308			salt: Vec<u8>,1309		) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1310		{1311			Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1312		}13131314		fn get_storage(1315			address: AccountId,1316			key: [u8; 32],1317		) -> pallet_contracts_primitives::GetStorageResult {1318			Contracts::get_storage(address, key)1319		}13201321		fn rent_projection(1322			address: AccountId,1323		) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1324			Contracts::rent_projection(address)1325		}1326	}1327	*/13281329	#[cfg(feature = "runtime-benchmarks")]1330	impl frame_benchmarking::Benchmark<Block> for Runtime {1331		fn benchmark_metadata(extra: bool) -> (1332			Vec<frame_benchmarking::BenchmarkList>,1333			Vec<frame_support::traits::StorageInfo>,1334		) {1335			use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};1336			use frame_support::traits::StorageInfoTrait;13371338			let mut list = Vec::<BenchmarkList>::new();13391340			list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);1341			list_benchmark!(list, extra, pallet_nft, Nft);1342			list_benchmark!(list, extra, pallet_inflation, Inflation);1343			list_benchmark!(list, extra, pallet_fungible, Fungible);1344			list_benchmark!(list, extra, pallet_refungible, Refungible);1345			list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);13461347			let storage_info = AllPalletsWithSystem::storage_info();13481349			return (list, storage_info)1350		}13511352		fn dispatch_benchmark(1353			config: frame_benchmarking::BenchmarkConfig1354		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1355			use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};13561357			let allowlist: Vec<TrackedStorageKey> = vec![1358				// Block Number1359				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),1360				// Total Issuance1361				hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1362				// Execution Phase1363				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1364				// Event Count1365				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1366				// System Events1367				hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1368			];13691370			let mut batches = Vec::<BenchmarkBatch>::new();1371			let params = (&config, &allowlist);13721373			add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1374			add_benchmark!(params, batches, pallet_nft, Nft);1375			add_benchmark!(params, batches, pallet_inflation, Inflation);1376			add_benchmark!(params, batches, pallet_fungible, Fungible);1377			add_benchmark!(params, batches, pallet_refungible, Refungible);1378			add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);13791380			if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1381			Ok(batches)1382		}1383	}1384}13851386struct CheckInherents;13871388impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1389	fn check_inherents(1390		block: &Block,1391		relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1392	) -> sp_inherents::CheckInherentsResult {1393		let relay_chain_slot = relay_state_proof1394			.read_slot()1395			.expect("Could not read the relay chain slot from the proof");13961397		let inherent_data =1398			cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1399				relay_chain_slot,1400				sp_std::time::Duration::from_secs(6),1401			)1402			.create_inherent_data()1403			.expect("Could not create the timestamp inherent data");14041405		inherent_data.check_extrinsics(block)1406	}1407}14081409cumulus_pallet_parachain_system::register_validate_block!(1410	Runtime = Runtime,1411	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1412	CheckInherents = CheckInherents,1413);
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,9 +18,13 @@
   transferExpectSuccess,
   addCollectionAdminExpectSuccess,
   adminApproveFromExpectSuccess,
+  getCreatedCollectionCount,
+  transferFromExpectSuccess,
+  transferFromExpectFail,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
+const expect = chai.expect;
 
 describe('Integration Test approve(spender, collection_id, item_id, amount):', () => {
   let alice: IKeyringPair;
@@ -78,6 +82,320 @@
   });
 });
 
+describe('Normal user can approve other users to transfer:', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+  let charlie: IKeyringPair;
+
+  before(async () => {
+    await usingApi(async () => {
+      alice = privateKey('//Alice');
+      bob = privateKey('//Bob');
+      charlie = privateKey('//Charlie');
+    });
+  });  
+
+  it('NFT', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', bob.address);
+    await approveExpectSuccess(collectionId, itemId, bob, charlie.address);
+  });
+
+  it('Fungible up to an approved amount', async () => {
+    const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'Fungible', decimalPoints: 0 }});
+    const itemId = await createItemExpectSuccess(alice, collectionId, 'Fungible', bob.address); 
+    await approveExpectSuccess(collectionId, itemId, bob, charlie.address);
+  });
+
+  it('ReFungible up to an approved amount', async () => {
+    const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'ReFungible' } });
+    const itemId = await createItemExpectSuccess(alice, collectionId, 'ReFungible', bob.address);
+    await approveExpectSuccess(collectionId, itemId, bob, charlie.address);
+  });
+});
+
+describe('Approved users can transferFrom up to approved amount:', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+  let charlie: IKeyringPair;
+
+  before(async () => {
+    await usingApi(async () => {
+      alice = privateKey('//Alice');
+      bob = privateKey('//Bob');
+      charlie = privateKey('//Charlie');
+    });
+  });  
+
+  it('NFT', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', bob.address);
+    await approveExpectSuccess(collectionId, itemId, bob, charlie.address);
+    await transferFromExpectSuccess(collectionId, itemId, charlie, bob, alice, 1, 'NFT');
+  });
+
+  it('Fungible up to an approved amount', async () => {
+    const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'Fungible', decimalPoints: 0 }});
+    const itemId = await createItemExpectSuccess(alice, collectionId, 'Fungible', bob.address); 
+    await approveExpectSuccess(collectionId, itemId, bob, charlie.address);
+    await transferFromExpectSuccess(collectionId, itemId, charlie, bob, alice, 1, 'Fungible');
+  });
+
+  it('ReFungible up to an approved amount', async () => {
+    const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'ReFungible' } });
+    const itemId = await createItemExpectSuccess(alice, collectionId, 'ReFungible', bob.address);
+    await approveExpectSuccess(collectionId, itemId, bob, charlie.address);
+    await transferFromExpectSuccess(collectionId, itemId, charlie, bob, alice, 1, 'ReFungible');
+  });
+});
+
+describe('Approved users cannot use transferFrom to repeat transfers if approved amount was already transferred:', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+  let charlie: IKeyringPair;
+
+  before(async () => {
+    await usingApi(async () => {
+      alice = privateKey('//Alice');
+      bob = privateKey('//Bob');
+      charlie = privateKey('//Charlie');
+    });
+  });  
+
+  it('NFT', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', bob.address);
+    await approveExpectSuccess(collectionId, itemId, bob, charlie.address);
+    await transferFromExpectSuccess(collectionId, itemId, charlie, bob, alice, 1, 'NFT');
+    await transferFromExpectFail(collectionId, itemId, charlie, bob, alice, 1);
+  });
+
+  it('Fungible up to an approved amount', async () => {
+    const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'Fungible', decimalPoints: 0 }});
+    const itemId = await createItemExpectSuccess(alice, collectionId, 'Fungible', bob.address); 
+    await approveExpectSuccess(collectionId, itemId, bob, charlie.address);
+    await transferFromExpectSuccess(collectionId, itemId, charlie, bob, alice, 1, 'Fungible');
+    await transferFromExpectFail(collectionId, itemId, charlie, bob, alice, 1);
+  });
+
+  it('ReFungible up to an approved amount', async () => {
+    const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'ReFungible' } });
+    const itemId = await createItemExpectSuccess(alice, collectionId, 'ReFungible', bob.address);
+    await approveExpectSuccess(collectionId, itemId, bob, charlie.address);
+    await transferFromExpectSuccess(collectionId, itemId, charlie, bob, alice, 1, 'ReFungible');
+    await transferFromExpectFail(collectionId, itemId, charlie, bob, alice, 1);
+  });
+});
+
+describe('Approved amount decreases by the transferred amount.:', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+  let charlie: IKeyringPair;
+  let dave: IKeyringPair;
+
+  before(async () => {
+    await usingApi(async () => {
+      alice = privateKey('//Alice');
+      bob = privateKey('//Bob');
+      charlie = privateKey('//Charlie');
+      dave = privateKey('//Dave');
+    });
+  });  
+
+  it('If a user B is approved to transfer 10 Fungible tokens from user A, they can transfer 2 tokens to user C, which will result in decreasing approval from 10 to 8. Then user B can transfer 8 tokens to user D.', async () => {
+    const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'Fungible', decimalPoints: 0 }});
+    const itemId = await createItemExpectSuccess(alice, collectionId, 'Fungible', alice.address); 
+    await approveExpectSuccess(collectionId, itemId, alice, bob.address, 10);
+    await transferFromExpectSuccess(collectionId, itemId, bob, alice, charlie, 2, 'Fungible');
+    await transferFromExpectSuccess(collectionId, itemId, bob, alice, dave, 8, 'Fungible');
+  });
+});
+
+describe('User may clear the approvals to approving for 0 amount:', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+  let charlie: IKeyringPair;
+
+  before(async () => {
+    await usingApi(async () => {
+      alice = privateKey('//Alice');
+      bob = privateKey('//Bob');
+      charlie = privateKey('//Charlie');
+    });
+  });
+
+  it('NFT', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT');
+    await approveExpectSuccess(collectionId, itemId, alice, bob.address, 1);
+    await approveExpectSuccess(collectionId, itemId, alice, bob.address, 0);
+    await transferFromExpectFail(collectionId, itemId, bob, bob, charlie, 1);
+  });
+
+  it('Fungible', async () => {
+    const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+    const newFungibleTokenId = await createItemExpectSuccess(alice, fungibleCollectionId, 'Fungible');
+    await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, alice, bob.address, 1);
+    await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, alice, bob.address, 0);
+    await transferFromExpectFail(fungibleCollectionId, newFungibleTokenId, bob, bob, charlie, 1);
+  });
+
+  it('ReFungible', async () => {
+    const reFungibleCollectionId =
+      await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
+    const newReFungibleTokenId = await createItemExpectSuccess(alice, reFungibleCollectionId, 'ReFungible');
+    await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, alice, bob.address, 1);
+    await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, alice, bob.address, 0);
+    await transferFromExpectFail(reFungibleCollectionId, newReFungibleTokenId, bob, bob, charlie, 1);
+  });
+});
+
+describe('User cannot approve for the amount greater than they own:', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+  let charlie: IKeyringPair;
+
+  before(async () => {
+    await usingApi(async () => {
+      alice = privateKey('//Alice');
+      bob = privateKey('//Bob');
+      charlie = privateKey('//Charlie');
+    });
+  });
+
+  it('1 for NFT', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', bob.address);
+    await approveExpectFail(collectionId, itemId, bob, charlie, 2);
+  });
+
+  it('Fungible', async () => {
+    const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+    const newFungibleTokenId = await createItemExpectSuccess(alice, fungibleCollectionId, 'Fungible');
+    await approveExpectFail(fungibleCollectionId, newFungibleTokenId, bob, charlie, 11);
+  });
+
+  it('ReFungible', async () => {
+    const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
+    const newReFungibleTokenId = await createItemExpectSuccess(alice, reFungibleCollectionId, 'ReFungible');
+    await approveExpectFail(reFungibleCollectionId, newReFungibleTokenId, bob, charlie, 101);
+  });
+});
+
+describe('Administrator and collection owner do not need approval in order to execute TransferFrom:', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+  let charlie: IKeyringPair;
+  let dave: IKeyringPair;
+
+  before(async () => {
+    await usingApi(async () => {
+      alice = privateKey('//Alice');
+      bob = privateKey('//Bob');
+      charlie = privateKey('//Charlie');
+      dave = privateKey('//Dave');
+    });
+  });  
+
+  it('NFT', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', charlie.address);
+    await transferFromExpectSuccess(collectionId, itemId, alice, charlie, dave, 1, 'NFT');
+    await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
+    await transferFromExpectSuccess(collectionId, itemId, bob, dave, alice, 1, 'NFT');
+  });
+
+  it('Fungible up to an approved amount', async () => {
+    const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'Fungible', decimalPoints: 0 }});
+    const itemId = await createItemExpectSuccess(alice, collectionId, 'Fungible', charlie.address); 
+    await transferFromExpectSuccess(collectionId, itemId, alice, charlie, dave, 1, 'Fungible');
+    await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
+    await transferFromExpectSuccess(collectionId, itemId, bob, dave, alice, 1, 'Fungible');
+  });
+
+  it('ReFungible up to an approved amount', async () => {
+    const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'ReFungible' } });
+    const itemId = await createItemExpectSuccess(alice, collectionId, 'ReFungible', charlie.address);
+    await transferFromExpectSuccess(collectionId, itemId, alice, charlie, dave, 1, 'ReFungible');
+    await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
+    await transferFromExpectSuccess(collectionId, itemId, bob, dave, alice, 1, 'ReFungible');
+  });
+});
+
+describe('Repeated approvals add up', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+  let charlie: IKeyringPair;
+  let dave: IKeyringPair;
+
+  before(async () => {
+    await usingApi(async () => {
+      alice = privateKey('//Alice');
+      bob = privateKey('//Bob');
+      charlie = privateKey('//Charlie');
+      dave = privateKey('//Dave');
+    });
+  });  
+
+  it.skip('Owned 10, approval 1: 1, approval 2: 1, resulting approved value: 2. Fungible', async () => {
+    const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'Fungible', decimalPoints: 0 }});
+    await createItemExpectSuccess(alice, collectionId, 'Fungible', alice.address);
+    await approveExpectSuccess(collectionId, 0, alice, bob.address, 1);
+    await approveExpectSuccess(collectionId, 0, alice, charlie.address, 1);
+    // const allowances1 = await getAllowance(collectionId, 0, Alice.address, Bob.address);
+    // const allowances2 = await getAllowance(collectionId, 0, Alice.address, Charlie.address);
+    // expect(allowances1 + allowances2).to.be.eq(BigInt(2));
+  });
+
+  it.skip('Owned 10, approval 1: 1, approval 2: 1, resulting approved value: 2. ReFungible', async () => {
+    const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'ReFungible' } });
+    const itemId = await createItemExpectSuccess(alice, collectionId, 'ReFungible', alice.address);
+    await approveExpectSuccess(collectionId, itemId, alice, bob.address, 1);
+    await approveExpectSuccess(collectionId, itemId, alice, charlie.address, 1);
+    // const allowances1 = await getAllowance(collectionId, itemId, Alice.address, Bob.address);
+    // const allowances2 = await getAllowance(collectionId, itemId, Alice.address, Charlie.address);
+    // expect(allowances1 + allowances2).to.be.eq(BigInt(2));
+  });
+
+  // Canceled by changing approve logic
+  it.skip('Cannot approve for more than total user`s amount (owned: 10, approval 1: 5 - should succeed, approval 2: 6 - should fail). Fungible', async () => {
+    const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'Fungible', decimalPoints: 0 }});
+    await createItemExpectSuccess(alice, collectionId, 'Fungible', dave.address);
+    await approveExpectSuccess(collectionId, 0, dave, bob.address, 5);
+    await approveExpectFail(collectionId, 0, dave, charlie, 6);
+  });
+
+  // Canceled by changing approve logic
+  it.skip('Cannot approve for more than total users amount (owned: 100, approval 1: 50 - should succeed, approval 2: 51 - should fail). ReFungible', async () => {
+    const collectionId = await createCollectionExpectSuccess({ mode:{ type: 'ReFungible' } });
+    const itemId = await createItemExpectSuccess(alice, collectionId, 'ReFungible', dave.address);
+    await approveExpectSuccess(collectionId, itemId, dave, bob.address, 50);
+    await approveExpectFail(collectionId, itemId, dave, charlie, 51);
+  });
+});
+
+describe('Integration Test approve(spender, collection_id, item_id, amount) with collection admin permissions:', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+  let charlie: IKeyringPair;
+
+  before(async () => {
+    await usingApi(async () => {
+      alice = privateKey('//Alice');
+      bob = privateKey('//Bob');
+      charlie = privateKey('//Charlie');
+    });
+  });
+
+  it('can be called by collection admin on non-owned item', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+
+    await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
+    await adminApproveFromExpectSuccess(collectionId, itemId, bob, alice.address, charlie.address);
+  });
+});
+
 describe('Negative Integration Test approve(spender, collection_id, item_id, amount):', () => {
   let alice: IKeyringPair;
   let bob: IKeyringPair;
@@ -94,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);
     });
   });
@@ -169,27 +487,5 @@
     await setCollectionLimitsExpectSuccess(alice, collectionId, {ownerCanTransfer: false});
 
     await approveExpectFail(collectionId, itemId, alice, charlie);
-  });
-});
-
-describe('Integration Test approve(spender, collection_id, item_id, amount) with collection admin permissions:', () => {
-  let alice: IKeyringPair;
-  let bob: IKeyringPair;
-  let charlie: IKeyringPair;
-
-  before(async () => {
-    await usingApi(async () => {
-      alice = privateKey('//Alice');
-      bob = privateKey('//Bob');
-      charlie = privateKey('//Charlie');
-    });
-  });
-
-  it('can be called by collection admin on non-owned item', async () => {
-    const collectionId = await createCollectionExpectSuccess();
-    const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
-
-    await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
-    await adminApproveFromExpectSuccess(collectionId, itemId, bob, alice.address, charlie.address);
   });
 });
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';
@@ -251,23 +252,20 @@
       const zeroBalance = await findUnusedAddress(api);
 
       // Mint token for alice
-      const itemId = await createItemExpectSuccess(alice, collectionId, 'ReFungible', alice.address);
+      const itemId = await createItemExpectSuccess(alice, collectionId, 'ReFungible', zeroBalance.address);
 
-      // Transfer this token from Alice to unused address and back
-      // Alice to Zero gets sponsored
-      const aliceToZero = api.tx.nft.transfer(normalizeAccountId(zeroBalance.address), collectionId, itemId, 1);
-      const events1 = await submitTransactionAsync(alice, aliceToZero);
+      const zeroToAlice = api.tx.nft.transfer(normalizeAccountId(alice.address), collectionId, itemId, 1);
+
+      // Zero to alice gets sponsored
+      const events1 = await submitTransactionAsync(zeroBalance, zeroToAlice);
       const result1 = getGenericResult(events1);
       expect(result1.success).to.be.true;
 
       // Second transfer should fail
       const sponsorBalanceBefore = (await api.query.system.account(bob.address)).data.free.toBigInt();
-      const zeroToAlice = api.tx.nft.transfer(normalizeAccountId(alice.address), collectionId, itemId, 1);
-      const badTransaction = async function () {
-        await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
-      };
-      await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');
+      await expect(submitTransactionExpectFailAsync(zeroBalance, zeroToAlice)).to.be.rejectedWith('Inability to pay some fees');
       const sponsorBalanceAfter = (await api.query.system.account(bob.address)).data.free.toBigInt();
+      expect(sponsorBalanceAfter).to.be.equal(sponsorBalanceBefore);
 
       // Try again after Zero gets some balance - now it should succeed
       const balancetx = api.tx.balances.transfer(zeroBalance.address, 1e15);
@@ -275,8 +273,6 @@
       const events2 = await submitTransactionAsync(zeroBalance, zeroToAlice);
       const result2 = getGenericResult(events2);
       expect(result2.success).to.be.true;
-
-      expect(sponsorBalanceAfter).to.be.equal(sponsorBalanceBefore);
     });
   });
 
@@ -335,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/eth/marketplace/marketplace.test.tsdiffbeforeafterboth
--- a/tests/src/eth/marketplace/marketplace.test.ts
+++ b/tests/src/eth/marketplace/marketplace.test.ts
@@ -2,7 +2,7 @@
 import {getBalanceSingle, transferBalanceExpectSuccess} from '../../substrate/get-balance';
 import privateKey from '../../substrate/privateKey';
 import {addToAllowListExpectSuccess, confirmSponsorshipExpectSuccess, createCollectionExpectSuccess, createFungibleItemExpectSuccess, createItemExpectSuccess, getTokenOwner, setCollectionSponsorExpectSuccess, transferExpectSuccess, transferFromExpectSuccess} from '../../util/helpers';
-import {collectionIdToAddress, contractHelpers, createEthAccountWithBalance, executeEthTxOnSub, GAS_ARGS, itWeb3, subToEth, subToEthLowercase} from '../util/helpers';
+import {collectionIdToAddress, contractHelpers, createEthAccountWithBalance, executeEthTxOnSub, GAS_ARGS, itWeb3, subToEth, subToEthLowercase, transferBalanceToEth} from '../util/helpers';
 import {evmToAddress} from '@polkadot/util-crypto';
 import nonFungibleAbi from '../nonFungibleAbi.json';
 import fungibleAbi from '../fungibleAbi.json';
@@ -12,35 +12,33 @@
 
 describe('Matcher contract usage', () => {
   itWeb3('With UNQ', async ({api, web3}) => {
+    const alice = privateKey('//Alice');
+    const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+    const evmCollection = new web3.eth.Contract(nonFungibleAbi as any, collectionIdToAddress(collectionId));
     const matcherOwner = await createEthAccountWithBalance(api, web3);
+    const helpers = contractHelpers(web3, matcherOwner);
+
     const matcherContract = new web3.eth.Contract(JSON.parse((await readFile(`${__dirname}/MarketPlace.abi`)).toString()), undefined, {
       from: matcherOwner,
       ...GAS_ARGS,
     });
     const matcher = await matcherContract.deploy({data: (await readFile(`${__dirname}/MarketPlace.bin`)).toString(), arguments:[matcherOwner]}).send({from: matcherOwner});
-    const helpers = contractHelpers(web3, matcherOwner);
+
+    await transferBalanceToEth(api, alice, matcher.options.address);
     await helpers.methods.toggleSponsoring(matcher.options.address, true).send({from: matcherOwner});
-    await helpers.methods.setSponsoringRateLimit(matcher.options.address, 1).send({from: matcherOwner});
 
-    const alice = privateKey('//Alice');
-    const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-    const evmCollection = new web3.eth.Contract(nonFungibleAbi as any, collectionIdToAddress(collectionId), {from: matcherOwner});
+    await transferBalanceToEth(api, alice, subToEth(alice.address));
     await setCollectionSponsorExpectSuccess(collectionId, alice.address);
     await confirmSponsorshipExpectSuccess(collectionId);
 
-    await helpers.methods.toggleAllowed(matcher.options.address, subToEth(alice.address), true).send({from: matcherOwner});
-    await addToAllowListExpectSuccess(alice, collectionId, evmToAddress(subToEth(alice.address)));
-
-    const seller = privateKey('//Bob');
+    const seller = privateKey('//Seller/' + Date.now());
+    await addToAllowListExpectSuccess(alice, collectionId, {Ethereum:subToEth(seller.address)});
     await helpers.methods.toggleAllowed(matcher.options.address, subToEth(seller.address), true).send({from: matcherOwner});
-    await addToAllowListExpectSuccess(alice, collectionId, evmToAddress(subToEth(seller.address)));
 
     const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', seller.address);
 
-    // To transfer item to matcher it first needs to be transfered to EVM account of bob
+    // To transfer item to matcher it first needs to be transfered to EVM account of seller
     await transferExpectSuccess(collectionId, tokenId, seller, {Ethereum: subToEth(seller.address)});
-
-    // Token is owned by seller initially
     expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal({Ethereum: subToEthLowercase(seller.address)});
 
     // Ask
@@ -55,14 +53,12 @@
     // Buy
     {
       const sellerBalanceBeforePurchase = await getBalanceSingle(api, seller.address);
-      // There is two functions named 'buy', so we should provide full signature
-      await executeEthTxOnSub(api, alice, matcher, m => m['buy(address,uint256)'](evmCollection.options.address, tokenId), {value: PRICE});
+      await executeEthTxOnSub(api, alice, matcher, m => m.buy(evmCollection.options.address, tokenId), {value: PRICE});
       expect(await getBalanceSingle(api, seller.address) - sellerBalanceBeforePurchase === PRICE);
     }
 
     // Token is transferred to evm account of alice
     expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal({Ethereum: subToEthLowercase(alice.address)});
-
 
     // Transfer token to substrate side of alice
     await transferFromExpectSuccess(collectionId, tokenId, alice, {Ethereum: subToEth(alice.address)}, {Substrate: alice.address});
@@ -137,37 +133,35 @@
   });
 
   itWeb3('With escrow', async ({api, web3}) => {
+    const alice = privateKey('//Alice');
+    const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+    const evmCollection = new web3.eth.Contract(nonFungibleAbi as any, collectionIdToAddress(collectionId));
     const matcherOwner = await createEthAccountWithBalance(api, web3);
+    const helpers = contractHelpers(web3, matcherOwner);
     const escrow = await createEthAccountWithBalance(api, web3);
+
     const matcherContract = new web3.eth.Contract(JSON.parse((await readFile(`${__dirname}/MarketPlace.abi`)).toString()), undefined, {
       from: matcherOwner,
       ...GAS_ARGS,
     });
     const matcher = await matcherContract.deploy({data: (await readFile(`${__dirname}/MarketPlace.bin`)).toString(), arguments: [matcherOwner]}).send({from: matcherOwner});
     await matcher.methods.setEscrow(escrow).send({from: matcherOwner});
-    const helpers = contractHelpers(web3, matcherOwner);
+
+    await transferBalanceToEth(api, alice, matcher.options.address);
     await helpers.methods.toggleSponsoring(matcher.options.address, true).send({from: matcherOwner});
-    await helpers.methods.setSponsoringRateLimit(matcher.options.address, 1).send({from: matcherOwner});
 
-    const alice = privateKey('//Alice');
-    const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-    const evmCollection = new web3.eth.Contract(nonFungibleAbi as any, collectionIdToAddress(collectionId), {from: matcherOwner});
+    await transferBalanceToEth(api, alice, subToEth(alice.address));
     await setCollectionSponsorExpectSuccess(collectionId, alice.address);
     await confirmSponsorshipExpectSuccess(collectionId);
-
-    await helpers.methods.toggleAllowed(matcher.options.address, subToEth(alice.address), true).send({from: matcherOwner});
-    await addToAllowListExpectSuccess(alice, collectionId, evmToAddress(subToEth(alice.address)));
 
-    const seller = privateKey('//Bob');
+    const seller = privateKey('//Seller/' + Date.now());
     await helpers.methods.toggleAllowed(matcher.options.address, subToEth(seller.address), true).send({from: matcherOwner});
     await addToAllowListExpectSuccess(alice, collectionId, evmToAddress(subToEth(seller.address)));
 
     const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', seller.address);
 
-    // To transfer item to matcher it first needs to be transfered to EVM account of bob
+    // To transfer item to matcher it first needs to be transfered to EVM account of seller
     await transferExpectSuccess(collectionId, tokenId, seller, {Ethereum: subToEth(seller.address)});
-
-    // Token is owned by seller initially
     expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal({Ethereum: subToEthLowercase(seller.address)});
 
     // Ask
modifiedtests/src/eth/util/helpers.tsdiffbeforeafterboth
--- a/tests/src/eth/util/helpers.ts
+++ b/tests/src/eth/util/helpers.ts
@@ -228,6 +228,18 @@
   return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});
 }
 
+/**
+ * Execute ethereum method call using substrate account
+ * @param to target contract
+ * @param mkTx - closure, receiving `contract.methods`, and returning method call,
+ * to be used as following (assuming `to` = erc20 contract):
+ * `m => m.transfer(to, amount)`
+ * 
+ * # Example
+ * ```ts
+ * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));
+ * ```
+ */
 export async function executeEthTxOnSub(api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {
   const tx = api.tx.evm.call(
     subToEth(from.address),
@@ -246,6 +258,11 @@
   return (await getBalance(api, [evmToAddress(address)]))[0];
 }
 
+/**
+ * Measure how much gas given closure consumes
+ * 
+ * @param user which user balance will be checked
+ */
 export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {
   const before = await ethBalanceViaSub(api, user);
 
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/pallet-presence.test.tsdiffbeforeafterboth
--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -39,7 +39,6 @@
   'nonfungible',
   'refungible',
   'scheduler',
-  'nftpayment',
   'charging',
 ];
 
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,11 @@
   transferExpectFailure,
   transferExpectSuccess,
   addCollectionAdminExpectSuccess,
+  getCreatedCollectionCount,
+  toSubstrateAddress,
+  getTokenOwner,
+  normalizeAccountId,
+  getBalance as getTokenBalance,
 } from './util/helpers';
 
 let alice: IKeyringPair;
@@ -132,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);
     });
   });
@@ -230,3 +235,61 @@
     );
   });
 });
+
+describe('Zero value transfer(From)', () => {
+  before(async () => {
+    await usingApi(async () => {
+      alice = privateKey('//Alice');
+      bob = privateKey('//Bob');
+    });
+  });
+
+  it('NFT', async () => {
+    await usingApi(async (api: ApiPromise) => {
+      const nftCollectionId = await createCollectionExpectSuccess();
+      const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');
+
+      const transferTx = api.tx.nft.transfer(normalizeAccountId(bob), nftCollectionId, newNftTokenId, 0);
+      await submitTransactionAsync(alice, transferTx);
+      const address = normalizeAccountId(await getTokenOwner(api, nftCollectionId, newNftTokenId));
+
+      expect(toSubstrateAddress(address)).to.be.equal(alice.address);
+    });
+  });
+
+  it('RFT', async () => {
+    await usingApi(async (api: ApiPromise) => {
+      const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
+      const newReFungibleTokenId = await createItemExpectSuccess(alice, reFungibleCollectionId, 'ReFungible');
+      const balanceBeforeAlice = await getTokenBalance(api, reFungibleCollectionId, normalizeAccountId(alice), newReFungibleTokenId);
+      const balanceBeforeBob = await getTokenBalance(api, reFungibleCollectionId, normalizeAccountId(bob), newReFungibleTokenId);
+
+      const transferTx = api.tx.nft.transfer(normalizeAccountId(bob), reFungibleCollectionId, newReFungibleTokenId, 0);
+      await submitTransactionAsync(alice, transferTx);
+
+      const balanceAfterAlice = await getTokenBalance(api, reFungibleCollectionId, normalizeAccountId(alice), newReFungibleTokenId);
+      const balanceAfterBob = await getTokenBalance(api, reFungibleCollectionId, normalizeAccountId(bob), newReFungibleTokenId);
+
+      expect((balanceBeforeAlice)).to.be.equal(balanceAfterAlice);
+      expect((balanceBeforeBob)).to.be.equal(balanceAfterBob);
+    });
+  });
+
+  it('Fungible', async () => {
+    await usingApi(async (api: ApiPromise) => {
+      const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+      const newFungibleTokenId = await createItemExpectSuccess(alice, fungibleCollectionId, 'Fungible');
+      const balanceBeforeAlice = await getTokenBalance(api, fungibleCollectionId, normalizeAccountId(alice), newFungibleTokenId);
+      const balanceBeforeBob = await getTokenBalance(api, fungibleCollectionId, normalizeAccountId(bob), newFungibleTokenId);
+
+      const transferTx = api.tx.nft.transfer(normalizeAccountId(bob), fungibleCollectionId, newFungibleTokenId, 0);
+      await submitTransactionAsync(alice, transferTx);
+
+      const balanceAfterAlice = await getTokenBalance(api, fungibleCollectionId, normalizeAccountId(alice), newFungibleTokenId);
+      const balanceAfterBob = await getTokenBalance(api, fungibleCollectionId, normalizeAccountId(bob), newFungibleTokenId);
+
+      expect((balanceBeforeAlice)).to.be.equal(balanceAfterAlice);
+      expect((balanceBeforeBob)).to.be.equal(balanceAfterBob);
+    });
+  });
+});
\ No newline at end of file
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> {