git.delta.rocks / unique-network / refs/commits / 6c1cc7ee4bff

difftreelog

Merge pull request #242 from UniqueNetwork/feature/fix_unit_tests

kozyrevdev2021-11-25parents: #3def18a #5c2c651.patch.diff
in: master
Fix unit tests

13 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4939,216 +4939,6 @@
 ]
 
 [[package]]
-name = "nft"
-version = "0.9.12"
-dependencies = [
- "cumulus-client-cli",
- "cumulus-client-collator",
- "cumulus-client-consensus-aura",
- "cumulus-client-consensus-common",
- "cumulus-client-network",
- "cumulus-client-service",
- "cumulus-primitives-core",
- "cumulus-primitives-parachain-inherent",
- "fc-consensus",
- "fc-db",
- "fc-mapping-sync",
- "fc-rpc",
- "fc-rpc-core",
- "flexi_logger",
- "fp-rpc",
- "frame-benchmarking",
- "frame-benchmarking-cli",
- "futures 0.3.17",
- "jsonrpc-core",
- "jsonrpc-pubsub",
- "log",
- "nft-data-structs",
- "nft-rpc",
- "nft-runtime",
- "pallet-ethereum",
- "pallet-transaction-payment-rpc",
- "parity-scale-codec",
- "parking_lot 0.11.2",
- "polkadot-cli",
- "polkadot-parachain",
- "polkadot-primitives",
- "polkadot-service",
- "polkadot-test-service",
- "sc-basic-authorship",
- "sc-chain-spec",
- "sc-cli",
- "sc-client-api",
- "sc-consensus",
- "sc-consensus-aura",
- "sc-executor",
- "sc-finality-grandpa",
- "sc-keystore",
- "sc-network",
- "sc-rpc",
- "sc-rpc-api",
- "sc-service",
- "sc-telemetry",
- "sc-tracing",
- "sc-transaction-pool",
- "serde",
- "serde_json",
- "sp-api",
- "sp-block-builder",
- "sp-blockchain",
- "sp-consensus",
- "sp-consensus-aura",
- "sp-core",
- "sp-finality-grandpa",
- "sp-inherents",
- "sp-keystore",
- "sp-offchain",
- "sp-runtime",
- "sp-session",
- "sp-timestamp",
- "sp-transaction-pool",
- "sp-trie",
- "structopt",
- "substrate-build-script-utils",
- "substrate-frame-rpc-system",
- "substrate-prometheus-endpoint",
-]
-
-[[package]]
-name = "nft-data-structs"
-version = "0.9.0"
-dependencies = [
- "derivative",
- "frame-support",
- "frame-system",
- "parity-scale-codec",
- "scale-info",
- "serde",
- "sp-core",
- "sp-runtime",
- "sp-std",
-]
-
-[[package]]
-name = "nft-rpc"
-version = "3.3.1"
-dependencies = [
- "fc-db",
- "fc-mapping-sync",
- "fc-rpc",
- "fc-rpc-core",
- "fp-rpc",
- "futures 0.3.17",
- "jsonrpc-core",
- "jsonrpc-pubsub",
- "nft-runtime",
- "pallet-ethereum",
- "pallet-nft",
- "pallet-transaction-payment-rpc",
- "pallet-transaction-payment-rpc-runtime-api",
- "sc-client-api",
- "sc-consensus-aura",
- "sc-consensus-epochs",
- "sc-finality-grandpa",
- "sc-finality-grandpa-rpc",
- "sc-keystore",
- "sc-network",
- "sc-rpc",
- "sc-rpc-api",
- "sc-service",
- "sc-transaction-pool",
- "sp-api",
- "sp-block-builder",
- "sp-blockchain",
- "sp-consensus",
- "sp-consensus-aura",
- "sp-core",
- "sp-offchain",
- "sp-runtime",
- "sp-session",
- "sp-storage",
- "sp-transaction-pool",
- "substrate-frame-rpc-system",
- "tokio 0.2.25",
- "uc-rpc",
- "up-rpc",
-]
-
-[[package]]
-name = "nft-runtime"
-version = "0.9.12"
-dependencies = [
- "cumulus-pallet-aura-ext",
- "cumulus-pallet-dmp-queue",
- "cumulus-pallet-parachain-system",
- "cumulus-pallet-xcm",
- "cumulus-pallet-xcmp-queue",
- "cumulus-primitives-core",
- "cumulus-primitives-timestamp",
- "cumulus-primitives-utility",
- "derivative",
- "fp-rpc",
- "fp-self-contained",
- "frame-benchmarking",
- "frame-executive",
- "frame-support",
- "frame-system",
- "frame-system-benchmarking",
- "frame-system-rpc-runtime-api",
- "hex-literal",
- "nft-data-structs",
- "orml-vesting",
- "pallet-aura",
- "pallet-balances",
- "pallet-common",
- "pallet-ethereum",
- "pallet-evm",
- "pallet-evm-coder-substrate",
- "pallet-evm-contract-helpers",
- "pallet-evm-migration",
- "pallet-evm-transaction-payment",
- "pallet-fungible",
- "pallet-inflation",
- "pallet-nft",
- "pallet-nonfungible",
- "pallet-randomness-collective-flip",
- "pallet-refungible",
- "pallet-sudo",
- "pallet-template-transaction-payment",
- "pallet-timestamp",
- "pallet-transaction-payment",
- "pallet-transaction-payment-rpc-runtime-api",
- "pallet-treasury",
- "pallet-unq-scheduler",
- "pallet-xcm",
- "parachain-info",
- "parity-scale-codec",
- "polkadot-parachain",
- "scale-info",
- "serde",
- "smallvec",
- "sp-api",
- "sp-arithmetic",
- "sp-block-builder",
- "sp-consensus-aura",
- "sp-core",
- "sp-inherents",
- "sp-io",
- "sp-offchain",
- "sp-runtime",
- "sp-session",
- "sp-std",
- "sp-transaction-pool",
- "sp-version",
- "substrate-wasm-builder",
- "up-evm-mapping",
- "up-rpc",
- "xcm",
- "xcm-builder",
- "xcm-executor",
-]
-
-[[package]]
 name = "nodrop"
 version = "0.1.14"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -5581,7 +5371,6 @@
  "evm-coder",
  "frame-support",
  "frame-system",
- "nft-data-structs",
  "pallet-evm",
  "pallet-evm-coder-substrate",
  "parity-scale-codec",
@@ -5590,6 +5379,7 @@
  "sp-core",
  "sp-runtime",
  "sp-std",
+ "up-data-structs",
  "up-evm-mapping",
 ]
 
@@ -5853,7 +5643,6 @@
  "frame-benchmarking",
  "frame-support",
  "frame-system",
- "nft-data-structs",
  "pallet-common",
  "pallet-evm-coder-substrate",
  "parity-scale-codec",
@@ -5861,6 +5650,7 @@
  "sp-core",
  "sp-runtime",
  "sp-std",
+ "up-data-structs",
 ]
 
 [[package]]
@@ -5956,7 +5746,7 @@
 
 [[package]]
 name = "pallet-inflation"
-version = "3.0.0"
+version = "0.1.0"
 dependencies = [
  "frame-benchmarking",
  "frame-support",
@@ -6057,43 +5847,6 @@
 ]
 
 [[package]]
-name = "pallet-nft"
-version = "3.0.0"
-dependencies = [
- "ethereum 0.9.0 (git+https://github.com/purestake/ethereum?branch=joshy-scale-info)",
- "evm-coder",
- "fp-evm",
- "frame-benchmarking",
- "frame-support",
- "frame-system",
- "hex-literal",
- "nft-data-structs",
- "pallet-balances",
- "pallet-common",
- "pallet-ethereum",
- "pallet-evm",
- "pallet-evm-coder-substrate",
- "pallet-fungible",
- "pallet-nonfungible",
- "pallet-randomness-collective-flip",
- "pallet-refungible",
- "pallet-timestamp",
- "pallet-transaction-payment",
- "parity-scale-codec",
- "primitive-types 0.10.1",
- "rlp",
- "scale-info",
- "serde",
- "sp-api",
- "sp-core",
- "sp-io",
- "sp-runtime",
- "sp-std",
- "up-evm-mapping",
- "up-sponsorship",
-]
-
-[[package]]
 name = "pallet-nicks"
 version = "4.0.0-dev"
 source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.12#d76f39995315ec36980908e4b99709bd14927044"
@@ -6116,7 +5869,6 @@
  "frame-benchmarking",
  "frame-support",
  "frame-system",
- "nft-data-structs",
  "pallet-common",
  "pallet-evm-coder-substrate",
  "parity-scale-codec",
@@ -6124,6 +5876,7 @@
  "sp-core",
  "sp-runtime",
  "sp-std",
+ "up-data-structs",
 ]
 
 [[package]]
@@ -6216,13 +5969,13 @@
  "frame-benchmarking",
  "frame-support",
  "frame-system",
- "nft-data-structs",
  "pallet-common",
  "parity-scale-codec",
  "scale-info",
  "sp-core",
  "sp-runtime",
  "sp-std",
+ "up-data-structs",
 ]
 
 [[package]]
@@ -6469,8 +6222,45 @@
 ]
 
 [[package]]
+name = "pallet-unique"
+version = "0.1.0"
+dependencies = [
+ "ethereum 0.9.0 (git+https://github.com/purestake/ethereum?branch=joshy-scale-info)",
+ "evm-coder",
+ "fp-evm",
+ "frame-benchmarking",
+ "frame-support",
+ "frame-system",
+ "hex-literal",
+ "pallet-balances",
+ "pallet-common",
+ "pallet-ethereum",
+ "pallet-evm",
+ "pallet-evm-coder-substrate",
+ "pallet-fungible",
+ "pallet-nonfungible",
+ "pallet-randomness-collective-flip",
+ "pallet-refungible",
+ "pallet-timestamp",
+ "pallet-transaction-payment",
+ "parity-scale-codec",
+ "primitive-types 0.10.1",
+ "rlp",
+ "scale-info",
+ "serde",
+ "sp-api",
+ "sp-core",
+ "sp-io",
+ "sp-runtime",
+ "sp-std",
+ "up-data-structs",
+ "up-evm-mapping",
+ "up-sponsorship",
+]
+
+[[package]]
 name = "pallet-unq-scheduler"
-version = "3.0.0"
+version = "0.1.0"
 dependencies = [
  "frame-benchmarking",
  "frame-support",
@@ -11714,7 +11504,6 @@
  "jsonrpc-core",
  "jsonrpc-core-client",
  "jsonrpc-derive",
- "nft-data-structs",
  "pallet-common",
  "parity-scale-codec",
  "sp-api",
@@ -11722,6 +11511,7 @@
  "sp-core",
  "sp-rpc",
  "sp-runtime",
+ "up-data-structs",
  "up-rpc",
 ]
 
@@ -11786,6 +11576,201 @@
 checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"
 
 [[package]]
+name = "unique-node"
+version = "0.9.12"
+dependencies = [
+ "cumulus-client-cli",
+ "cumulus-client-collator",
+ "cumulus-client-consensus-aura",
+ "cumulus-client-consensus-common",
+ "cumulus-client-network",
+ "cumulus-client-service",
+ "cumulus-primitives-core",
+ "cumulus-primitives-parachain-inherent",
+ "fc-consensus",
+ "fc-db",
+ "fc-mapping-sync",
+ "fc-rpc",
+ "fc-rpc-core",
+ "flexi_logger",
+ "fp-rpc",
+ "frame-benchmarking",
+ "frame-benchmarking-cli",
+ "futures 0.3.17",
+ "jsonrpc-core",
+ "jsonrpc-pubsub",
+ "log",
+ "pallet-ethereum",
+ "pallet-transaction-payment-rpc",
+ "parity-scale-codec",
+ "parking_lot 0.11.2",
+ "polkadot-cli",
+ "polkadot-parachain",
+ "polkadot-primitives",
+ "polkadot-service",
+ "polkadot-test-service",
+ "sc-basic-authorship",
+ "sc-chain-spec",
+ "sc-cli",
+ "sc-client-api",
+ "sc-consensus",
+ "sc-consensus-aura",
+ "sc-executor",
+ "sc-finality-grandpa",
+ "sc-keystore",
+ "sc-network",
+ "sc-rpc",
+ "sc-rpc-api",
+ "sc-service",
+ "sc-telemetry",
+ "sc-tracing",
+ "sc-transaction-pool",
+ "serde",
+ "serde_json",
+ "sp-api",
+ "sp-block-builder",
+ "sp-blockchain",
+ "sp-consensus",
+ "sp-consensus-aura",
+ "sp-core",
+ "sp-finality-grandpa",
+ "sp-inherents",
+ "sp-keystore",
+ "sp-offchain",
+ "sp-runtime",
+ "sp-session",
+ "sp-timestamp",
+ "sp-transaction-pool",
+ "sp-trie",
+ "structopt",
+ "substrate-build-script-utils",
+ "substrate-frame-rpc-system",
+ "substrate-prometheus-endpoint",
+ "unique-rpc",
+ "unique-runtime",
+ "up-data-structs",
+]
+
+[[package]]
+name = "unique-rpc"
+version = "0.1.0"
+dependencies = [
+ "fc-db",
+ "fc-mapping-sync",
+ "fc-rpc",
+ "fc-rpc-core",
+ "fp-rpc",
+ "futures 0.3.17",
+ "jsonrpc-core",
+ "jsonrpc-pubsub",
+ "pallet-ethereum",
+ "pallet-transaction-payment-rpc",
+ "pallet-transaction-payment-rpc-runtime-api",
+ "pallet-unique",
+ "sc-client-api",
+ "sc-consensus-aura",
+ "sc-consensus-epochs",
+ "sc-finality-grandpa",
+ "sc-finality-grandpa-rpc",
+ "sc-keystore",
+ "sc-network",
+ "sc-rpc",
+ "sc-rpc-api",
+ "sc-service",
+ "sc-transaction-pool",
+ "sp-api",
+ "sp-block-builder",
+ "sp-blockchain",
+ "sp-consensus",
+ "sp-consensus-aura",
+ "sp-core",
+ "sp-offchain",
+ "sp-runtime",
+ "sp-session",
+ "sp-storage",
+ "sp-transaction-pool",
+ "substrate-frame-rpc-system",
+ "tokio 0.2.25",
+ "uc-rpc",
+ "unique-runtime",
+ "up-rpc",
+]
+
+[[package]]
+name = "unique-runtime"
+version = "0.9.12"
+dependencies = [
+ "cumulus-pallet-aura-ext",
+ "cumulus-pallet-dmp-queue",
+ "cumulus-pallet-parachain-system",
+ "cumulus-pallet-xcm",
+ "cumulus-pallet-xcmp-queue",
+ "cumulus-primitives-core",
+ "cumulus-primitives-timestamp",
+ "cumulus-primitives-utility",
+ "derivative",
+ "fp-rpc",
+ "fp-self-contained",
+ "frame-benchmarking",
+ "frame-executive",
+ "frame-support",
+ "frame-system",
+ "frame-system-benchmarking",
+ "frame-system-rpc-runtime-api",
+ "hex-literal",
+ "orml-vesting",
+ "pallet-aura",
+ "pallet-balances",
+ "pallet-common",
+ "pallet-ethereum",
+ "pallet-evm",
+ "pallet-evm-coder-substrate",
+ "pallet-evm-contract-helpers",
+ "pallet-evm-migration",
+ "pallet-evm-transaction-payment",
+ "pallet-fungible",
+ "pallet-inflation",
+ "pallet-nonfungible",
+ "pallet-randomness-collective-flip",
+ "pallet-refungible",
+ "pallet-sudo",
+ "pallet-template-transaction-payment",
+ "pallet-timestamp",
+ "pallet-transaction-payment",
+ "pallet-transaction-payment-rpc-runtime-api",
+ "pallet-treasury",
+ "pallet-unique",
+ "pallet-unq-scheduler",
+ "pallet-xcm",
+ "parachain-info",
+ "parity-scale-codec",
+ "polkadot-parachain",
+ "scale-info",
+ "serde",
+ "smallvec",
+ "sp-api",
+ "sp-arithmetic",
+ "sp-block-builder",
+ "sp-consensus-aura",
+ "sp-core",
+ "sp-inherents",
+ "sp-io",
+ "sp-offchain",
+ "sp-runtime",
+ "sp-session",
+ "sp-std",
+ "sp-transaction-pool",
+ "sp-version",
+ "substrate-wasm-builder",
+ "up-data-structs",
+ "up-evm-mapping",
+ "up-rpc",
+ "xcm",
+ "xcm-builder",
+ "xcm-executor",
+]
+
+[[package]]
 name = "universal-hash"
 version = "0.4.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -11832,6 +11817,21 @@
 checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a"
 
 [[package]]
+name = "up-data-structs"
+version = "0.1.0"
+dependencies = [
+ "derivative",
+ "frame-support",
+ "frame-system",
+ "parity-scale-codec",
+ "scale-info",
+ "serde",
+ "sp-core",
+ "sp-runtime",
+ "sp-std",
+]
+
+[[package]]
 name = "up-evm-mapping"
 version = "0.1.0"
 dependencies = [
@@ -11843,13 +11843,13 @@
 name = "up-rpc"
 version = "0.1.0"
 dependencies = [
- "nft-data-structs",
  "pallet-common",
  "parity-scale-codec",
  "sp-api",
  "sp-core",
  "sp-runtime",
  "sp-std",
+ "up-data-structs",
 ]
 
 [[package]]
modifiedpallets/common/src/account.rsdiffbeforeafterboth
--- a/pallets/common/src/account.rs
+++ b/pallets/common/src/account.rs
@@ -7,7 +7,7 @@
 use pallet_evm::AddressMapping;
 use sp_std::vec::Vec;
 use sp_std::clone::Clone;
-use up_evm_mapping::EvmBackwardsAddressMapping;
+pub use up_evm_mapping::EvmBackwardsAddressMapping;
 
 pub trait CrossAccountId<AccountId>:
 	Encode + EncodeLike + Decode + TypeInfo + Clone + PartialEq + Ord + core::fmt::Debug + Default
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -273,8 +273,8 @@
 		TotalCollectionsLimitExceeded,
 		/// variable_data exceeded data limit.
 		TokenVariableDataLimitExceeded,
-		/// Exceeded max admin amount
-		CollectionAdminAmountExceeded,
+		/// Exceeded max admin count
+		CollectionAdminCountExceeded,
 
 		/// Collection settings not allowing items transferring
 		TransferNotAllowed,
@@ -506,10 +506,10 @@
 		if admin {
 			let amount = amount
 				.checked_add(1)
-				.ok_or(<Error<T>>::CollectionAdminAmountExceeded)?;
+				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;
 			ensure!(
 				amount <= Self::collection_admins_limit(),
-				<Error<T>>::CollectionAdminAmountExceeded,
+				<Error<T>>::CollectionAdminCountExceeded,
 			);
 
 			// =========
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -182,7 +182,7 @@
 		_token: TokenId,
 		_data: Vec<u8>,
 	) -> DispatchResultWithPostInfo {
-		fail!(<Error<T>>::FungibleItemsHaveData)
+		fail!(<Error<T>>::FungibleItemsDontHaveData)
 	}
 
 	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -35,7 +35,7 @@
 		/// Not default id passed as TokenId argument
 		FungibleItemsHaveNoId,
 		/// Tried to set data for fungible item
-		FungibleItemsHaveData,
+		FungibleItemsDontHaveData,
 	}
 
 	#[pallet::config]
@@ -48,7 +48,7 @@
 	pub struct Pallet<T>(_);
 
 	#[pallet::storage]
-	pub(super) type TotalSupply<T: Config> =
+	pub type TotalSupply<T: Config> =
 		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;
 
 	#[pallet::storage]
@@ -62,7 +62,7 @@
 	>;
 
 	#[pallet::storage]
-	pub(super) type Allowance<T: Config> = StorageNMap<
+	pub type Allowance<T: Config> = StorageNMap<
 		Key = (
 			Key<Twox64Concat, CollectionId>,
 			Key<Blake2_128, T::CrossAccountId>,
modifiedpallets/inflation/src/lib.rsdiffbeforeafterboth
--- a/pallets/inflation/src/lib.rs
+++ b/pallets/inflation/src/lib.rs
@@ -46,7 +46,8 @@
 pub type BalanceOf<T> =
 	<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
 
-pub const YEAR: u32 = 5_259_600;
+// pub const YEAR: u32 = 5_259_600; // 6-second block
+pub const YEAR: u32 = 2_629_800; // 12-second block
 pub const TOTAL_YEARS_UNTIL_FLAT: u32 = 9;
 pub const START_INFLATION_PERCENT: u32 = 10;
 pub const END_INFLATION_PERCENT: u32 = 4;
modifiedpallets/inflation/src/tests.rsdiffbeforeafterboth
--- a/pallets/inflation/src/tests.rs
+++ b/pallets/inflation/src/tests.rs
@@ -18,7 +18,7 @@
 type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
 type Block = frame_system::mocking::MockBlock<Test>;
 
-const YEAR: u64 = 5_259_600;
+const YEAR: u64 = 2_629_800;
 
 parameter_types! {
 	pub const ExistentialDeposit: u64 = 1;
@@ -112,8 +112,8 @@
 		// first inflation deposit should be equal to BlockInflation
 		Inflation::on_initialize(1);
 
-		// SBP M2 review: Verify expected block inflation for year 1
-		assert_eq!(Inflation::block_inflation(), 1901);
+		// Expected 100-block inflation for year 1 is 100 * 100_000_000 / YEAR = 3803
+		assert_eq!(Inflation::block_inflation(), 3803);
 		assert_eq!(
 			Balances::free_balance(1234) - initial_issuance,
 			Inflation::block_inflation()
@@ -158,26 +158,21 @@
 		let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
 		assert_eq!(Balances::free_balance(1234), initial_issuance);
 		Inflation::on_initialize(1);
-		let block_inflation_year_0 = Inflation::block_inflation();
 
-		// SBP M2 review: go through all the block inflations for year 1,
+		// Go through all the block inflations for year 1,
 		// total issuance will be updated accordingly
 		for block in (100..YEAR).step_by(100) {
 			Inflation::on_initialize(block);
 		}
 		assert_eq!(
-			initial_issuance + (1901 * (YEAR / 100)),
+			initial_issuance + (3803 * (YEAR / 100)),
 			<Balances as Currency<_>>::total_issuance()
 		);
 
 		Inflation::on_initialize(YEAR);
 		let block_inflation_year_1 = Inflation::block_inflation();
-		// SBP M2 review: Verify expected block inflation for year 2
-		assert_eq!(block_inflation_year_1, 1952);
-
-		// SBP M2 review: this is actually not true
-		// Assert that year 1 inflation is less than year 0
-		// assert!(block_inflation_year_0 > block_inflation_year_1);
+		// Expected 100-block inflation for year 2: 100 * 9.33% * initial issuance * 110% / YEAR = 3904
+		assert_eq!(block_inflation_year_1, 3904);
 	});
 }
 
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -58,7 +58,7 @@
 	}
 
 	#[pallet::pallet]
-	#[pallet::generate_store(pub trait Store)]
+	#[pallet::generate_store(pub(super) trait Store)]
 	pub struct Pallet<T>(_);
 
 	#[pallet::storage]
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -54,7 +54,7 @@
 	}
 
 	#[pallet::pallet]
-	#[pallet::generate_store(pub trait Store)]
+	#[pallet::generate_store(pub(super) trait Store)]
 	pub struct Pallet<T>(_);
 
 	#[pallet::storage]
modifiedpallets/scheduler/src/lib.rsdiffbeforeafterboth
before · pallets/scheduler/src/lib.rs
1// This file is part of Substrate.23// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.4// SPDX-License-Identifier: Apache-2.056// Licensed under the Apache License, Version 2.0 (the "License");7// you may not use this file except in compliance with the License.8// You may obtain a copy of the License at9//10// 	http://www.apache.org/licenses/LICENSE-2.011//12// Unless required by applicable law or agreed to in writing, software13// distributed under the License is distributed on an "AS IS" BASIS,14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15// See the License for the specific language governing permissions and16// limitations under the License.1718//! # Scheduler19//! A module for scheduling dispatches.20//!21//! - [`Config`]22//! - [`Call`]23//! - [`Module`]24//!25//! ## Overview26//!27//! This module exposes capabilities for scheduling dispatches to occur at a28//! specified block number or at a specified period. These scheduled dispatches29//! may be named or anonymous and may be canceled.30//!31//! **NOTE:** The scheduled calls will be dispatched with the default filter32//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin33//! except root which will get no filter. And not the filter contained in origin34//! use to call `fn schedule`.35//!36//! If a call is scheduled using proxy or whatever mecanism which adds filter,37//! then those filter will not be used when dispatching the schedule call.38//!39//! ## Interface40//!41//! ### Dispatchable Functions42//!43//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a44//!   specified block and with a specified priority.45//! * `cancel` - cancel a scheduled dispatch, specified by block number and46//!   index.47//! * `schedule_named` - augments the `schedule` interface with an additional48//!   `Vec<u8>` parameter that can be used for identification.49//! * `cancel_named` - the named complement to the cancel function.5051// Ensure we're `no_std` when compiling for Wasm.52#![cfg_attr(not(feature = "std"), no_std)]53#![allow(clippy::type_complexity, clippy::boxed_local, clippy::unused_unit)]5455mod benchmarking;56pub mod weights;5758use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow};59use codec::{Encode, Decode, Codec};60use sp_runtime::{61	RuntimeDebug,62	traits::{Zero, One, BadOrigin, Saturating},63};64use frame_support::{65	decl_module, decl_storage, decl_event, decl_error,66	dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},67	traits::{68		Get,69		schedule::{self, DispatchTime},70		OriginTrait, EnsureOrigin, IsType,71	},72	weights::{GetDispatchInfo, Weight},73};74use frame_system::{self as system, ensure_signed};75pub use weights::WeightInfo;76use up_sponsorship::SponsorshipHandler;77use scale_info::TypeInfo;7879/// Our pallet's configuration trait. All our types and constants go in here. If the80/// pallet is dependent on specific other pallets, then their configuration traits81/// should be added to our implied traits list.82///83/// `system::Config` should always be included in our implied traits.84/// //85pub trait Config: system::Config {86	/// The overarching event type.87	type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;8889	/// The aggregated origin which the dispatch will take.90	type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>91		+ From<Self::PalletsOrigin>92		+ IsType<<Self as system::Config>::Origin>;9394	/// The caller origin, overarching type of all pallets origins.95	type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + TypeInfo + Clone + Eq;9697	/// The aggregated call type.98	type Call: Parameter99		+ Dispatchable<Origin = <Self as Config>::Origin>100		+ GetDispatchInfo101		+ From<system::Call<Self>>;102103	/// The maximum weight that may be scheduled per block for any dispatchables of less priority104	/// than `schedule::HARD_DEADLINE`.105	type MaximumWeight: Get<Weight>;106107	/// Required origin to schedule or cancel calls.108	type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;109110	/// The maximum number of scheduled calls in the queue for a single block.111	/// Not strictly enforced, but used for weight estimation.112	type MaxScheduledPerBlock: Get<u32>;113114	/// Sponsoring function115	type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;116117	/// Weight information for extrinsics in this pallet.118	type WeightInfo: WeightInfo;119}120121// pub type SelfWeightInfo<T> = <T as system::Config>::WeightInfo;122123/// Just a simple index for naming period tasks.124pub type PeriodicIndex = u32;125/// The location of a scheduled task that can be used to remove it.126pub type TaskAddress<BlockNumber> = (BlockNumber, u32);127128#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]129#[derive(Clone, RuntimeDebug, Encode, Decode)]130struct ScheduledV1<Call, BlockNumber> {131	maybe_id: Option<Vec<u8>>,132	priority: schedule::Priority,133	call: Call,134	maybe_periodic: Option<schedule::Period<BlockNumber>>,135}136137/// Information regarding an item to be executed in the future.138#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]139#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]140pub struct ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId> {141	/// The unique identity for this task, if there is one.142	maybe_id: Option<Vec<u8>>,143	/// This task's priority.144	priority: schedule::Priority,145	/// The call to be dispatched.146	call: Call,147	/// If the call is periodic, then this points to the information concerning that.148	maybe_periodic: Option<schedule::Period<BlockNumber>>,149	/// The origin to dispatch the call.150	origin: PalletsOrigin,151	_phantom: PhantomData<AccountId>,152}153154/// The current version of Scheduled struct.155pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =156	ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId>;157158// A value placed in storage that represents the current version of the Scheduler storage.159// This value is used by the `on_runtime_upgrade` logic to determine whether we run160// storage migration logic.161#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)]162enum Releases {163	V1,164	V2,165}166167impl Default for Releases {168	fn default() -> Self {169		Releases::V1170	}171}172173#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]174pub struct CallSpec {175	module: u32,176	method: u32,177}178179decl_storage! {180	trait Store for Module<T: Config> as Scheduler {181		/// Items to be executed, indexed by the block number that they should be executed on.182		pub Agenda: map hasher(twox_64_concat) T::BlockNumber183			=> Vec<Option<Scheduled<<T as Config>::Call, T::BlockNumber, T::PalletsOrigin, T::AccountId>>>;184185		pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber186			=> Vec<Option<CallSpec>>;187188		/// Lookup from identity to the block number and index of the task.189		Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;190191		/// Storage version of the pallet.192		///193		/// New networks start with last version.194		StorageVersion build(|_| Releases::V2): Releases;195	}196}197198decl_event!(199	pub enum Event<T> where <T as system::Config>::BlockNumber {200		/// Scheduled some task. \[when, index\]201		Scheduled(BlockNumber, u32),202		/// Canceled some task. \[when, index\]203		Canceled(BlockNumber, u32),204		/// Dispatched some task. \[task, id, result\]205		Dispatched(TaskAddress<BlockNumber>, Option<Vec<u8>>, DispatchResult),206	}207);208209decl_error! {210	pub enum Error for Module<T: Config> {211		/// Failed to schedule a call212		FailedToSchedule,213		/// Cannot find the scheduled call.214		NotFound,215		/// Given target block number is in the past.216		TargetBlockNumberInPast,217		/// Reschedule failed because it does not change scheduled time.218		RescheduleNoChange,219	}220}221222decl_module! {223	/// Scheduler module declaration.224	pub struct Module<T: Config> for enum Call225	where226		origin: <T as system::Config>::Origin227	{228		type Error = Error<T>;229		fn deposit_event() = default;230231232		/// Anonymously schedule a task.233		///234		/// # <weight>235		/// - S = Number of already scheduled calls236		/// - Base Weight: 22.29 + .126 * S µs237		/// - DB Weight:238		///     - Read: Agenda239		///     - Write: Agenda240		/// - Will use base weight of 25 which should be good for up to 30 scheduled calls241		/// # </weight>242		#[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]243		fn schedule(origin,244			when: T::BlockNumber,245			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,246			priority: schedule::Priority,247			call: Box<<T as Config>::Call>,248		)249		{250			let origin = <T as Config>::Origin::from(origin);251			Self::do_schedule(DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call)?;252		}253254		/// Cancel an anonymously scheduled task.255		///256		/// # <weight>257		/// - S = Number of already scheduled calls258		/// - Base Weight: 22.15 + 2.869 * S µs259		/// - DB Weight:260		///     - Read: Agenda261		///     - Write: Agenda, Lookup262		/// - Will use base weight of 100 which should be good for up to 30 scheduled calls263		/// # </weight>264		#[weight = <T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get())]265		fn cancel(origin, when: T::BlockNumber, index: u32) {266			T::ScheduleOrigin::ensure_origin(origin.clone())?;267			let origin = <T as Config>::Origin::from(origin);268			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;269		}270271		/// Schedule a named task.272		///273		/// # <weight>274		/// - S = Number of already scheduled calls275		/// - Base Weight: 29.6 + .159 * S µs276		/// - DB Weight:277		///     - Read: Agenda, Lookup278		///     - Write: Agenda, Lookup279		/// - Will use base weight of 35 which should be good for more than 30 scheduled calls280		/// # </weight>281		#[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]282		fn schedule_named(origin,283			id: Vec<u8>,284			when: T::BlockNumber,285			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,286			priority: schedule::Priority,287			call: Box<<T as Config>::Call>,288		) {289			T::ScheduleOrigin::ensure_origin(origin.clone())?;290			let origin = <T as Config>::Origin::from(origin);291			Self::do_schedule_named(292				id, DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call293			)?;294		}295296		/// Cancel a named scheduled task.297		///298		/// # <weight>299		/// - S = Number of already scheduled calls300		/// - Base Weight: 24.91 + 2.907 * S µs301		/// - DB Weight:302		///     - Read: Agenda, Lookup303		///     - Write: Agenda, Lookup304		/// - Will use base weight of 100 which should be good for up to 30 scheduled calls305		/// # </weight>306		#[weight = <T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get())]307		fn cancel_named(origin, id: Vec<u8>) {308			T::ScheduleOrigin::ensure_origin(origin.clone())?;309			let origin = <T as Config>::Origin::from(origin);310			Self::do_cancel_named(Some(origin.caller().clone()), id)?;311		}312313		/// Anonymously schedule a task after a delay.314		///315		/// # <weight>316		/// Same as [`schedule`].317		/// # </weight>318		#[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]319		fn schedule_after(origin,320			after: T::BlockNumber,321			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,322			priority: schedule::Priority,323			call: Box<<T as Config>::Call>,324		) {325			T::ScheduleOrigin::ensure_origin(origin.clone())?;326			let origin = <T as Config>::Origin::from(origin);327			Self::do_schedule(328				DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call329			)?;330		}331332		/// Schedule a named task after a delay.333		///334		/// # <weight>335		/// Same as [`schedule_named`].336		/// # </weight>337		#[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]338		fn schedule_named_after(origin,339			id: Vec<u8>,340			after: T::BlockNumber,341			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,342			priority: schedule::Priority,343			call: Box<<T as Config>::Call>,344		) {345			T::ScheduleOrigin::ensure_origin(origin.clone())?;346			let origin = <T as Config>::Origin::from(origin);347			Self::do_schedule_named(348				id, DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call349			)?;350		}351352		/// Execute the scheduled calls353		///354		/// # <weight>355		/// - S = Number of already scheduled calls356		/// - N = Named scheduled calls357		/// - P = Periodic Calls358		/// - Base Weight: 9.243 + 23.45 * S µs359		/// - DB Weight:360		///     - Read: Agenda + Lookup * N + Agenda(Future) * P361		///     - Write: Agenda + Lookup * N  + Agenda(future) * P362		/// # </weight>363		fn on_initialize(now: T::BlockNumber) -> Weight {364			let limit = T::MaximumWeight::get();365			let mut queued = Agenda::<T>::take(now).into_iter()366				.enumerate()367				.filter_map(|(index, s)| s.map(|inner| (index as u32, inner)))368				.collect::<Vec<_>>();369			if queued.len() as u32 > T::MaxScheduledPerBlock::get() {370				log::warn!(371					target: "runtime::scheduler",372					"Warning: This block has more items queued in Scheduler than \373					expected from the runtime configuration. An update might be needed."374				);375			}376			queued.sort_by_key(|(_, s)| s.priority);377			let base_weight: Weight = T::DbWeight::get().reads_writes(1, 2); // Agenda + Agenda(next)378			let mut total_weight: Weight = 0;379			queued.into_iter()380				.enumerate()381				.scan(base_weight, |cumulative_weight, (order, (index, s))| {382					*cumulative_weight = cumulative_weight383						.saturating_add(s.call.get_dispatch_info().weight);384385					let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(386						s.origin.clone()387					).into();388389					if ensure_signed(origin).is_ok() {390						 // AccountData for inner call origin accountdata.391						*cumulative_weight = cumulative_weight392							.saturating_add(T::DbWeight::get().reads_writes(1, 1));393					}394395					if s.maybe_id.is_some() {396						// Remove/Modify Lookup397						*cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().writes(1));398					}399					if s.maybe_periodic.is_some() {400						// Read/Write Agenda for future block401						*cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));402					}403404					Some((order, index, *cumulative_weight, s))405				})406				.filter_map(|(order, index, cumulative_weight, mut s)| {407					// We allow a scheduled call if any is true:408					// - It's priority is `HARD_DEADLINE`409					// - It does not push the weight past the limit.410					// - It is the first item in the schedule411					if s.priority <= schedule::HARD_DEADLINE || cumulative_weight <= limit || order == 0 {412413						let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(414							s.origin.clone()415						).into();416						let sender = ensure_signed(origin).unwrap_or_default();417						let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &s.call).unwrap_or(sender);418						let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));419						let r = s.call.clone().dispatch(sponsor.into());420						let maybe_id = s.maybe_id.clone();421						if let Some((period, count)) = s.maybe_periodic {422							if count > 1 {423								s.maybe_periodic = Some((period, count - 1));424							} else {425								s.maybe_periodic = None;426							}427							let next = now + period;428							// If scheduled is named, place it's information in `Lookup`429							if let Some(ref id) = s.maybe_id {430								let next_index = Agenda::<T>::decode_len(now + period).unwrap_or(0);431								Lookup::<T>::insert(id, (next, next_index as u32));432							}433							Agenda::<T>::append(next, Some(s));434						} else if let Some(ref id) = s.maybe_id {435									  Lookup::<T>::remove(id);436								  }437						Self::deposit_event(RawEvent::Dispatched(438							(now, index),439							maybe_id,440							r.map(|_| ()).map_err(|e| e.error)441						));442						total_weight = cumulative_weight;443						None444					} else {445						Some(Some(s))446					}447				})448				.for_each(|unused| {449					let next = now + One::one();450					Agenda::<T>::append(next, unused);451				});452453			total_weight454		}455	}456}457458impl<T: Config> Module<T> {459	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {460		let now = frame_system::Pallet::<T>::block_number();461462		let when = match when {463			DispatchTime::At(x) => x,464			// The current block has already completed it's scheduled tasks, so465			// Schedule the task at lest one block after this current block.466			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),467		};468469		if when <= now {470			return Err(Error::<T>::TargetBlockNumberInPast.into());471		}472473		Ok(when)474	}475476	fn do_schedule(477		when: DispatchTime<T::BlockNumber>,478		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,479		priority: schedule::Priority,480		origin: T::PalletsOrigin,481		call: <T as Config>::Call,482	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {483		let when = Self::resolve_time(when)?;484485		// sanitize maybe_periodic486		let maybe_periodic = maybe_periodic487			.filter(|p| p.1 > 1 && !p.0.is_zero())488			// Remove one from the number of repetitions since we will schedule one now.489			.map(|(p, c)| (p, c - 1));490		let s = Some(Scheduled {491			maybe_id: None,492			priority,493			call,494			maybe_periodic,495			origin,496			_phantom: PhantomData::<T::AccountId>::default(),497		});498		Agenda::<T>::append(when, s);499		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;500		if index > T::MaxScheduledPerBlock::get() {501			log::warn!(502				target: "runtime::scheduler",503				"Warning: There are more items queued in the Scheduler than \504				expected from the runtime configuration. An update might be needed.",505			);506		}507		Self::deposit_event(RawEvent::Scheduled(when, index));508509		Ok((when, index))510	}511512	fn do_cancel(513		origin: Option<T::PalletsOrigin>,514		(when, index): TaskAddress<T::BlockNumber>,515	) -> Result<(), DispatchError> {516		let scheduled = Agenda::<T>::try_mutate(when, |agenda| {517			agenda.get_mut(index as usize).map_or(518				Ok(None),519				|s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {520					if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {521						if *o != s.origin {522							return Err(BadOrigin.into());523						}524					};525					Ok(s.take())526				},527			)528		})?;529		if let Some(s) = scheduled {530			if let Some(id) = s.maybe_id {531				Lookup::<T>::remove(id);532			}533			Self::deposit_event(RawEvent::Canceled(when, index));534			Ok(())535		} else {536			Err(Error::<T>::NotFound.into())537		}538	}539540	fn do_reschedule(541		(when, index): TaskAddress<T::BlockNumber>,542		new_time: DispatchTime<T::BlockNumber>,543	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {544		let new_time = Self::resolve_time(new_time)?;545546		if new_time == when {547			return Err(Error::<T>::RescheduleNoChange.into());548		}549550		Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {551			let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;552			let task = task.take().ok_or(Error::<T>::NotFound)?;553			Agenda::<T>::append(new_time, Some(task));554			Ok(())555		})?;556557		let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;558		Self::deposit_event(RawEvent::Canceled(when, index));559		Self::deposit_event(RawEvent::Scheduled(new_time, new_index));560561		Ok((new_time, new_index))562	}563564	fn do_schedule_named(565		id: Vec<u8>,566		when: DispatchTime<T::BlockNumber>,567		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,568		priority: schedule::Priority,569		origin: T::PalletsOrigin,570		call: <T as Config>::Call,571	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {572		// ensure id it is unique573		if Lookup::<T>::contains_key(&id) {574			return Err(Error::<T>::FailedToSchedule.into());575		}576577		let when = Self::resolve_time(when)?;578579		// sanitize maybe_periodic580		let maybe_periodic = maybe_periodic581			.filter(|p| p.1 > 1 && !p.0.is_zero())582			// Remove one from the number of repetitions since we will schedule one now.583			.map(|(p, c)| (p, c - 1));584585		let s = Scheduled {586			maybe_id: Some(id.clone()),587			priority,588			call,589			maybe_periodic,590			origin,591			_phantom: Default::default(),592		};593		Agenda::<T>::append(when, Some(s));594		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;595		if index > T::MaxScheduledPerBlock::get() {596			log::warn!(597				target: "runtime::scheduler",598				"Warning: There are more items queued in the Scheduler than \599				expected from the runtime configuration. An update might be needed.",600			);601		}602		let address = (when, index);603		Lookup::<T>::insert(&id, &address);604		Self::deposit_event(RawEvent::Scheduled(when, index));605606		Ok(address)607	}608609	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: Vec<u8>) -> DispatchResult {610		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {611			if let Some((when, index)) = lookup.take() {612				let i = index as usize;613				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {614					if let Some(s) = agenda.get_mut(i) {615						if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {616							if *o != s.origin {617								return Err(BadOrigin.into());618							}619						}620						*s = None;621					}622					Ok(())623				})?;624				Self::deposit_event(RawEvent::Canceled(when, index));625				Ok(())626			} else {627				Err(Error::<T>::NotFound.into())628			}629		})630	}631632	fn do_reschedule_named(633		id: Vec<u8>,634		new_time: DispatchTime<T::BlockNumber>,635	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {636		let new_time = Self::resolve_time(new_time)?;637638		Lookup::<T>::try_mutate_exists(639			id,640			|lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {641				let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;642643				if new_time == when {644					return Err(Error::<T>::RescheduleNoChange.into());645				}646647				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {648					let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;649					let task = task.take().ok_or(Error::<T>::NotFound)?;650					Agenda::<T>::append(new_time, Some(task));651652					Ok(())653				})?;654655				let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;656				Self::deposit_event(RawEvent::Canceled(when, index));657				Self::deposit_event(RawEvent::Scheduled(new_time, new_index));658659				*lookup = Some((new_time, new_index));660661				Ok((new_time, new_index))662			},663		)664	}665}666667impl<T: Config> schedule::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>668	for Module<T>669{670	type Address = TaskAddress<T::BlockNumber>;671672	fn schedule(673		when: DispatchTime<T::BlockNumber>,674		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,675		priority: schedule::Priority,676		origin: T::PalletsOrigin,677		call: <T as Config>::Call,678	) -> Result<Self::Address, DispatchError> {679		Self::do_schedule(when, maybe_periodic, priority, origin, call)680	}681682	fn cancel((when, index): Self::Address) -> Result<(), ()> {683		Self::do_cancel(None, (when, index)).map_err(|_| ())684	}685686	fn reschedule(687		address: Self::Address,688		when: DispatchTime<T::BlockNumber>,689	) -> Result<Self::Address, DispatchError> {690		Self::do_reschedule(address, when)691	}692693	fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {694		Agenda::<T>::get(when)695			.get(index as usize)696			.ok_or(())697			.map(|_| when)698	}699}700701impl<T: Config> schedule::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>702	for Module<T>703{704	type Address = TaskAddress<T::BlockNumber>;705706	fn schedule_named(707		id: Vec<u8>,708		when: DispatchTime<T::BlockNumber>,709		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,710		priority: schedule::Priority,711		origin: T::PalletsOrigin,712		call: <T as Config>::Call,713	) -> Result<Self::Address, ()> {714		Self::do_schedule_named(id, when, maybe_periodic, priority, origin, call).map_err(|_| ())715	}716717	fn cancel_named(id: Vec<u8>) -> Result<(), ()> {718		Self::do_cancel_named(None, id).map_err(|_| ())719	}720721	fn reschedule_named(722		id: Vec<u8>,723		when: DispatchTime<T::BlockNumber>,724	) -> Result<Self::Address, DispatchError> {725		Self::do_reschedule_named(id, when)726	}727728	fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {729		Lookup::<T>::get(id)730			.and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))731			.ok_or(())732	}733}734735#[cfg(test)]736#[allow(clippy::from_over_into)]737mod tests {738	use super::*;739740	use frame_support::{741		Hashable, assert_err, assert_noop, assert_ok, ord_parameter_types, parameter_types,742		traits::{Contains, OnFinalize, OnInitialize},743		weights::constants::RocksDbWeight,744	};745	use sp_core::H256;746	use sp_runtime::{747		Perbill,748		testing::Header,749		traits::{BlakeTwo256, IdentityLookup},750	};751	use frame_system::{EnsureOneOf, EnsureRoot, EnsureSignedBy};752	use substrate_test_utils::assert_eq_uvec;753	use crate as scheduler;754755	mod logger {756		use super::*;757		use std::cell::RefCell;758759		thread_local! {760			static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());761		}762		pub fn log() -> Vec<(OriginCaller, u32)> {763			LOG.with(|log| log.borrow().clone())764		}765		pub trait Config: system::Config {766			type Event: From<Event> + Into<<Self as system::Config>::Event>;767		}768		decl_event! {769			pub enum Event {770				Logged(u32, Weight),771			}772		}773		decl_module! {774			pub struct Module<T: Config> for enum Call775			where776				origin: <T as system::Config>::Origin,777				<T as system::Config>::Origin: OriginTrait<PalletsOrigin = OriginCaller>778			{779				fn deposit_event() = default;780781				#[weight = *weight]782				fn log(origin, i: u32, weight: Weight) {783					Self::deposit_event(Event::Logged(i, weight));784					LOG.with(|log| {785						log.borrow_mut().push((origin.caller().clone(), i));786					})787				}788789				#[weight = *weight]790				fn log_without_filter(origin, i: u32, weight: Weight) {791					Self::deposit_event(Event::Logged(i, weight));792					LOG.with(|log| {793						log.borrow_mut().push((origin.caller().clone(), i));794					})795				}796			}797		}798	}799800	type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;801	type Block = frame_system::mocking::MockBlock<Test>;802803	frame_support::construct_runtime!(804		pub enum Test where805			Block = Block,806			NodeBlock = Block,807			UncheckedExtrinsic = UncheckedExtrinsic,808		{809			System: frame_system::{Pallet, Call, Config, Storage, Event<T>},810			Logger: logger::{Pallet, Call, Event},811			Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},812		}813	);814815	// Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.816	pub struct BaseFilter;817	impl Contains<Call> for BaseFilter {818		fn contains(call: &Call) -> bool {819			!matches!(call, Call::Logger(logger::Call::log { .. }))820		}821	}822823	parameter_types! {824		pub const BlockHashCount: u64 = 250;825		pub BlockWeights: frame_system::limits::BlockWeights =826			frame_system::limits::BlockWeights::simple_max(2_000_000_000_000);827	}828	impl system::Config for Test {829		type BaseCallFilter = BaseFilter;830		type BlockWeights = ();831		type BlockLength = ();832		type DbWeight = RocksDbWeight;833		type Origin = Origin;834		type Call = Call;835		type Index = u64;836		type BlockNumber = u64;837		type Hash = H256;838		type Hashing = BlakeTwo256;839		type AccountId = u64;840		type Lookup = IdentityLookup<Self::AccountId>;841		type Header = Header;842		type Event = Event;843		type BlockHashCount = BlockHashCount;844		type Version = ();845		type PalletInfo = PalletInfo;846		type AccountData = ();847		type OnNewAccount = ();848		type OnKilledAccount = ();849		type SystemWeightInfo = ();850		type SS58Prefix = ();851		type OnSetCode = ();852	}853	impl logger::Config for Test {854		type Event = Event;855	}856	parameter_types! {857		pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;858		pub const MaxScheduledPerBlock: u32 = 10;859	}860	ord_parameter_types! {861		pub const One: u64 = 1;862	}863864	impl Config for Test {865		type Event = Event;866		type Origin = Origin;867		type PalletsOrigin = OriginCaller;868		type Call = Call;869		type MaximumWeight = MaximumSchedulerWeight;870		type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;871		type MaxScheduledPerBlock = MaxScheduledPerBlock;872		type WeightInfo = ();873		type SponsorshipHandler = ();874	}875876	pub fn new_test_ext() -> sp_io::TestExternalities {877		let t = system::GenesisConfig::default()878			.build_storage::<Test>()879			.unwrap();880		t.into()881	}882883	fn run_to_block(n: u64) {884		while System::block_number() < n {885			Scheduler::on_finalize(System::block_number());886			System::set_block_number(System::block_number() + 1);887			Scheduler::on_initialize(System::block_number());888		}889	}890891	fn root() -> OriginCaller {892		system::RawOrigin::Root.into()893	}894}
after · pallets/scheduler/src/lib.rs
1// This file is part of Substrate.23// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.4// SPDX-License-Identifier: Apache-2.056// Licensed under the Apache License, Version 2.0 (the "License");7// you may not use this file except in compliance with the License.8// You may obtain a copy of the License at9//10// 	http://www.apache.org/licenses/LICENSE-2.011//12// Unless required by applicable law or agreed to in writing, software13// distributed under the License is distributed on an "AS IS" BASIS,14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15// See the License for the specific language governing permissions and16// limitations under the License.1718//! # Scheduler19//! A module for scheduling dispatches.20//!21//! - [`Config`]22//! - [`Call`]23//! - [`Module`]24//!25//! ## Overview26//!27//! This module exposes capabilities for scheduling dispatches to occur at a28//! specified block number or at a specified period. These scheduled dispatches29//! may be named or anonymous and may be canceled.30//!31//! **NOTE:** The scheduled calls will be dispatched with the default filter32//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin33//! except root which will get no filter. And not the filter contained in origin34//! use to call `fn schedule`.35//!36//! If a call is scheduled using proxy or whatever mecanism which adds filter,37//! then those filter will not be used when dispatching the schedule call.38//!39//! ## Interface40//!41//! ### Dispatchable Functions42//!43//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a44//!   specified block and with a specified priority.45//! * `cancel` - cancel a scheduled dispatch, specified by block number and46//!   index.47//! * `schedule_named` - augments the `schedule` interface with an additional48//!   `Vec<u8>` parameter that can be used for identification.49//! * `cancel_named` - the named complement to the cancel function.5051// Ensure we're `no_std` when compiling for Wasm.52#![cfg_attr(not(feature = "std"), no_std)]53#![allow(clippy::type_complexity, clippy::boxed_local, clippy::unused_unit)]5455mod benchmarking;56pub mod weights;5758use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow};59use codec::{Encode, Decode, Codec};60use sp_runtime::{61	RuntimeDebug,62	traits::{Zero, One, BadOrigin, Saturating},63};64use frame_support::{65	decl_module, decl_storage, decl_event, decl_error,66	dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},67	traits::{68		Get,69		schedule::{self, DispatchTime},70		OriginTrait, EnsureOrigin, IsType,71	},72	weights::{GetDispatchInfo, Weight},73};74use frame_system::{self as system, ensure_signed};75pub use weights::WeightInfo;76use up_sponsorship::SponsorshipHandler;77use scale_info::TypeInfo;7879/// Our pallet's configuration trait. All our types and constants go in here. If the80/// pallet is dependent on specific other pallets, then their configuration traits81/// should be added to our implied traits list.82///83/// `system::Config` should always be included in our implied traits.84/// //85pub trait Config: system::Config {86	/// The overarching event type.87	type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;8889	/// The aggregated origin which the dispatch will take.90	type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>91		+ From<Self::PalletsOrigin>92		+ IsType<<Self as system::Config>::Origin>;9394	/// The caller origin, overarching type of all pallets origins.95	type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + TypeInfo + Clone + Eq;9697	/// The aggregated call type.98	type Call: Parameter99		+ Dispatchable<Origin = <Self as Config>::Origin>100		+ GetDispatchInfo101		+ From<system::Call<Self>>;102103	/// The maximum weight that may be scheduled per block for any dispatchables of less priority104	/// than `schedule::HARD_DEADLINE`.105	type MaximumWeight: Get<Weight>;106107	/// Required origin to schedule or cancel calls.108	type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;109110	/// The maximum number of scheduled calls in the queue for a single block.111	/// Not strictly enforced, but used for weight estimation.112	type MaxScheduledPerBlock: Get<u32>;113114	/// Sponsoring function115	type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;116117	/// Weight information for extrinsics in this pallet.118	type WeightInfo: WeightInfo;119}120121// pub type SelfWeightInfo<T> = <T as system::Config>::WeightInfo;122123/// Just a simple index for naming period tasks.124pub type PeriodicIndex = u32;125/// The location of a scheduled task that can be used to remove it.126pub type TaskAddress<BlockNumber> = (BlockNumber, u32);127128#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]129#[derive(Clone, RuntimeDebug, Encode, Decode)]130struct ScheduledV1<Call, BlockNumber> {131	maybe_id: Option<Vec<u8>>,132	priority: schedule::Priority,133	call: Call,134	maybe_periodic: Option<schedule::Period<BlockNumber>>,135}136137/// Information regarding an item to be executed in the future.138#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]139#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]140pub struct ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId> {141	/// The unique identity for this task, if there is one.142	maybe_id: Option<Vec<u8>>,143	/// This task's priority.144	priority: schedule::Priority,145	/// The call to be dispatched.146	call: Call,147	/// If the call is periodic, then this points to the information concerning that.148	maybe_periodic: Option<schedule::Period<BlockNumber>>,149	/// The origin to dispatch the call.150	origin: PalletsOrigin,151	_phantom: PhantomData<AccountId>,152}153154/// The current version of Scheduled struct.155pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =156	ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId>;157158// A value placed in storage that represents the current version of the Scheduler storage.159// This value is used by the `on_runtime_upgrade` logic to determine whether we run160// storage migration logic.161#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)]162enum Releases {163	V1,164	V2,165}166167impl Default for Releases {168	fn default() -> Self {169		Releases::V1170	}171}172173#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]174pub struct CallSpec {175	module: u32,176	method: u32,177}178179decl_storage! {180	trait Store for Module<T: Config> as Scheduler {181		/// Items to be executed, indexed by the block number that they should be executed on.182		pub Agenda: map hasher(twox_64_concat) T::BlockNumber183			=> Vec<Option<Scheduled<<T as Config>::Call, T::BlockNumber, T::PalletsOrigin, T::AccountId>>>;184185		pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber186			=> Vec<Option<CallSpec>>;187188		/// Lookup from identity to the block number and index of the task.189		Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;190191		/// Storage version of the pallet.192		///193		/// New networks start with last version.194		StorageVersion build(|_| Releases::V2): Releases;195	}196}197198decl_event!(199	pub enum Event<T> where <T as system::Config>::BlockNumber {200		/// Scheduled some task. \[when, index\]201		Scheduled(BlockNumber, u32),202		/// Canceled some task. \[when, index\]203		Canceled(BlockNumber, u32),204		/// Dispatched some task. \[task, id, result\]205		Dispatched(TaskAddress<BlockNumber>, Option<Vec<u8>>, DispatchResult),206	}207);208209decl_error! {210	pub enum Error for Module<T: Config> {211		/// Failed to schedule a call212		FailedToSchedule,213		/// Cannot find the scheduled call.214		NotFound,215		/// Given target block number is in the past.216		TargetBlockNumberInPast,217		/// Reschedule failed because it does not change scheduled time.218		RescheduleNoChange,219	}220}221222decl_module! {223	/// Scheduler module declaration.224	pub struct Module<T: Config> for enum Call225	where226		origin: <T as system::Config>::Origin227	{228		type Error = Error<T>;229		fn deposit_event() = default;230231232		/// Anonymously schedule a task.233		///234		/// # <weight>235		/// - S = Number of already scheduled calls236		/// - Base Weight: 22.29 + .126 * S µs237		/// - DB Weight:238		///     - Read: Agenda239		///     - Write: Agenda240		/// - Will use base weight of 25 which should be good for up to 30 scheduled calls241		/// # </weight>242		#[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]243		fn schedule(origin,244			when: T::BlockNumber,245			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,246			priority: schedule::Priority,247			call: Box<<T as Config>::Call>,248		)249		{250			let origin = <T as Config>::Origin::from(origin);251			Self::do_schedule(DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call)?;252		}253254		/// Cancel an anonymously scheduled task.255		///256		/// # <weight>257		/// - S = Number of already scheduled calls258		/// - Base Weight: 22.15 + 2.869 * S µs259		/// - DB Weight:260		///     - Read: Agenda261		///     - Write: Agenda, Lookup262		/// - Will use base weight of 100 which should be good for up to 30 scheduled calls263		/// # </weight>264		#[weight = <T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get())]265		fn cancel(origin, when: T::BlockNumber, index: u32) {266			T::ScheduleOrigin::ensure_origin(origin.clone())?;267			let origin = <T as Config>::Origin::from(origin);268			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;269		}270271		/// Schedule a named task.272		///273		/// # <weight>274		/// - S = Number of already scheduled calls275		/// - Base Weight: 29.6 + .159 * S µs276		/// - DB Weight:277		///     - Read: Agenda, Lookup278		///     - Write: Agenda, Lookup279		/// - Will use base weight of 35 which should be good for more than 30 scheduled calls280		/// # </weight>281		#[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]282		fn schedule_named(origin,283			id: Vec<u8>,284			when: T::BlockNumber,285			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,286			priority: schedule::Priority,287			call: Box<<T as Config>::Call>,288		) {289			T::ScheduleOrigin::ensure_origin(origin.clone())?;290			let origin = <T as Config>::Origin::from(origin);291			Self::do_schedule_named(292				id, DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call293			)?;294		}295296		/// Cancel a named scheduled task.297		///298		/// # <weight>299		/// - S = Number of already scheduled calls300		/// - Base Weight: 24.91 + 2.907 * S µs301		/// - DB Weight:302		///     - Read: Agenda, Lookup303		///     - Write: Agenda, Lookup304		/// - Will use base weight of 100 which should be good for up to 30 scheduled calls305		/// # </weight>306		#[weight = <T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get())]307		fn cancel_named(origin, id: Vec<u8>) {308			T::ScheduleOrigin::ensure_origin(origin.clone())?;309			let origin = <T as Config>::Origin::from(origin);310			Self::do_cancel_named(Some(origin.caller().clone()), id)?;311		}312313		/// Anonymously schedule a task after a delay.314		///315		/// # <weight>316		/// Same as [`schedule`].317		/// # </weight>318		#[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]319		fn schedule_after(origin,320			after: T::BlockNumber,321			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,322			priority: schedule::Priority,323			call: Box<<T as Config>::Call>,324		) {325			T::ScheduleOrigin::ensure_origin(origin.clone())?;326			let origin = <T as Config>::Origin::from(origin);327			Self::do_schedule(328				DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call329			)?;330		}331332		/// Schedule a named task after a delay.333		///334		/// # <weight>335		/// Same as [`schedule_named`].336		/// # </weight>337		#[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]338		fn schedule_named_after(origin,339			id: Vec<u8>,340			after: T::BlockNumber,341			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,342			priority: schedule::Priority,343			call: Box<<T as Config>::Call>,344		) {345			T::ScheduleOrigin::ensure_origin(origin.clone())?;346			let origin = <T as Config>::Origin::from(origin);347			Self::do_schedule_named(348				id, DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call349			)?;350		}351352		/// Execute the scheduled calls353		///354		/// # <weight>355		/// - S = Number of already scheduled calls356		/// - N = Named scheduled calls357		/// - P = Periodic Calls358		/// - Base Weight: 9.243 + 23.45 * S µs359		/// - DB Weight:360		///     - Read: Agenda + Lookup * N + Agenda(Future) * P361		///     - Write: Agenda + Lookup * N  + Agenda(future) * P362		/// # </weight>363		fn on_initialize(now: T::BlockNumber) -> Weight {364			let limit = T::MaximumWeight::get();365			let mut queued = Agenda::<T>::take(now).into_iter()366				.enumerate()367				.filter_map(|(index, s)| s.map(|inner| (index as u32, inner)))368				.collect::<Vec<_>>();369			if queued.len() as u32 > T::MaxScheduledPerBlock::get() {370				log::warn!(371					target: "runtime::scheduler",372					"Warning: This block has more items queued in Scheduler than \373					expected from the runtime configuration. An update might be needed."374				);375			}376			queued.sort_by_key(|(_, s)| s.priority);377			let base_weight: Weight = T::DbWeight::get().reads_writes(1, 2); // Agenda + Agenda(next)378			let mut total_weight: Weight = 0;379			queued.into_iter()380				.enumerate()381				.scan(base_weight, |cumulative_weight, (order, (index, s))| {382					*cumulative_weight = cumulative_weight383						.saturating_add(s.call.get_dispatch_info().weight);384385					let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(386						s.origin.clone()387					).into();388389					if ensure_signed(origin).is_ok() {390						 // AccountData for inner call origin accountdata.391						*cumulative_weight = cumulative_weight392							.saturating_add(T::DbWeight::get().reads_writes(1, 1));393					}394395					if s.maybe_id.is_some() {396						// Remove/Modify Lookup397						*cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().writes(1));398					}399					if s.maybe_periodic.is_some() {400						// Read/Write Agenda for future block401						*cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));402					}403404					Some((order, index, *cumulative_weight, s))405				})406				.filter_map(|(order, index, cumulative_weight, mut s)| {407					// We allow a scheduled call if any is true:408					// - It's priority is `HARD_DEADLINE`409					// - It does not push the weight past the limit.410					// - It is the first item in the schedule411					if s.priority <= schedule::HARD_DEADLINE || cumulative_weight <= limit || order == 0 {412413						let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(414							s.origin.clone()415						).into();416						let sender = ensure_signed(origin).unwrap_or_default();417						let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &s.call).unwrap_or(sender);418						let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));419						let r = s.call.clone().dispatch(sponsor.into());420						let maybe_id = s.maybe_id.clone();421						if let Some((period, count)) = s.maybe_periodic {422							if count > 1 {423								s.maybe_periodic = Some((period, count - 1));424							} else {425								s.maybe_periodic = None;426							}427							let next = now + period;428							// If scheduled is named, place it's information in `Lookup`429							if let Some(ref id) = s.maybe_id {430								let next_index = Agenda::<T>::decode_len(now + period).unwrap_or(0);431								Lookup::<T>::insert(id, (next, next_index as u32));432							}433							Agenda::<T>::append(next, Some(s));434						} else if let Some(ref id) = s.maybe_id {435									  Lookup::<T>::remove(id);436								  }437						Self::deposit_event(RawEvent::Dispatched(438							(now, index),439							maybe_id,440							r.map(|_| ()).map_err(|e| e.error)441						));442						total_weight = cumulative_weight;443						None444					} else {445						Some(Some(s))446					}447				})448				.for_each(|unused| {449					let next = now + One::one();450					Agenda::<T>::append(next, unused);451				});452453			total_weight454		}455	}456}457458impl<T: Config> Module<T> {459	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {460		let now = frame_system::Pallet::<T>::block_number();461462		let when = match when {463			DispatchTime::At(x) => x,464			// The current block has already completed it's scheduled tasks, so465			// Schedule the task at lest one block after this current block.466			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),467		};468469		if when <= now {470			return Err(Error::<T>::TargetBlockNumberInPast.into());471		}472473		Ok(when)474	}475476	fn do_schedule(477		when: DispatchTime<T::BlockNumber>,478		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,479		priority: schedule::Priority,480		origin: T::PalletsOrigin,481		call: <T as Config>::Call,482	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {483		let when = Self::resolve_time(when)?;484485		// sanitize maybe_periodic486		let maybe_periodic = maybe_periodic487			.filter(|p| p.1 > 1 && !p.0.is_zero())488			// Remove one from the number of repetitions since we will schedule one now.489			.map(|(p, c)| (p, c - 1));490		let s = Some(Scheduled {491			maybe_id: None,492			priority,493			call,494			maybe_periodic,495			origin,496			_phantom: PhantomData::<T::AccountId>::default(),497		});498		Agenda::<T>::append(when, s);499		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;500		if index > T::MaxScheduledPerBlock::get() {501			log::warn!(502				target: "runtime::scheduler",503				"Warning: There are more items queued in the Scheduler than \504				expected from the runtime configuration. An update might be needed.",505			);506		}507		Self::deposit_event(RawEvent::Scheduled(when, index));508509		Ok((when, index))510	}511512	fn do_cancel(513		origin: Option<T::PalletsOrigin>,514		(when, index): TaskAddress<T::BlockNumber>,515	) -> Result<(), DispatchError> {516		let scheduled = Agenda::<T>::try_mutate(when, |agenda| {517			agenda.get_mut(index as usize).map_or(518				Ok(None),519				|s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {520					if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {521						if *o != s.origin {522							return Err(BadOrigin.into());523						}524					};525					Ok(s.take())526				},527			)528		})?;529		if let Some(s) = scheduled {530			if let Some(id) = s.maybe_id {531				Lookup::<T>::remove(id);532			}533			Self::deposit_event(RawEvent::Canceled(when, index));534			Ok(())535		} else {536			Err(Error::<T>::NotFound.into())537		}538	}539540	fn do_reschedule(541		(when, index): TaskAddress<T::BlockNumber>,542		new_time: DispatchTime<T::BlockNumber>,543	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {544		let new_time = Self::resolve_time(new_time)?;545546		if new_time == when {547			return Err(Error::<T>::RescheduleNoChange.into());548		}549550		Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {551			let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;552			let task = task.take().ok_or(Error::<T>::NotFound)?;553			Agenda::<T>::append(new_time, Some(task));554			Ok(())555		})?;556557		let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;558		Self::deposit_event(RawEvent::Canceled(when, index));559		Self::deposit_event(RawEvent::Scheduled(new_time, new_index));560561		Ok((new_time, new_index))562	}563564	fn do_schedule_named(565		id: Vec<u8>,566		when: DispatchTime<T::BlockNumber>,567		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,568		priority: schedule::Priority,569		origin: T::PalletsOrigin,570		call: <T as Config>::Call,571	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {572		// ensure id it is unique573		if Lookup::<T>::contains_key(&id) {574			return Err(Error::<T>::FailedToSchedule.into());575		}576577		let when = Self::resolve_time(when)?;578579		// sanitize maybe_periodic580		let maybe_periodic = maybe_periodic581			.filter(|p| p.1 > 1 && !p.0.is_zero())582			// Remove one from the number of repetitions since we will schedule one now.583			.map(|(p, c)| (p, c - 1));584585		let s = Scheduled {586			maybe_id: Some(id.clone()),587			priority,588			call,589			maybe_periodic,590			origin,591			_phantom: Default::default(),592		};593		Agenda::<T>::append(when, Some(s));594		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;595		if index > T::MaxScheduledPerBlock::get() {596			log::warn!(597				target: "runtime::scheduler",598				"Warning: There are more items queued in the Scheduler than \599				expected from the runtime configuration. An update might be needed.",600			);601		}602		let address = (when, index);603		Lookup::<T>::insert(&id, &address);604		Self::deposit_event(RawEvent::Scheduled(when, index));605606		Ok(address)607	}608609	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: Vec<u8>) -> DispatchResult {610		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {611			if let Some((when, index)) = lookup.take() {612				let i = index as usize;613				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {614					if let Some(s) = agenda.get_mut(i) {615						if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {616							if *o != s.origin {617								return Err(BadOrigin.into());618							}619						}620						*s = None;621					}622					Ok(())623				})?;624				Self::deposit_event(RawEvent::Canceled(when, index));625				Ok(())626			} else {627				Err(Error::<T>::NotFound.into())628			}629		})630	}631632	fn do_reschedule_named(633		id: Vec<u8>,634		new_time: DispatchTime<T::BlockNumber>,635	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {636		let new_time = Self::resolve_time(new_time)?;637638		Lookup::<T>::try_mutate_exists(639			id,640			|lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {641				let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;642643				if new_time == when {644					return Err(Error::<T>::RescheduleNoChange.into());645				}646647				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {648					let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;649					let task = task.take().ok_or(Error::<T>::NotFound)?;650					Agenda::<T>::append(new_time, Some(task));651652					Ok(())653				})?;654655				let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;656				Self::deposit_event(RawEvent::Canceled(when, index));657				Self::deposit_event(RawEvent::Scheduled(new_time, new_index));658659				*lookup = Some((new_time, new_index));660661				Ok((new_time, new_index))662			},663		)664	}665}666667impl<T: Config> schedule::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>668	for Module<T>669{670	type Address = TaskAddress<T::BlockNumber>;671672	fn schedule(673		when: DispatchTime<T::BlockNumber>,674		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,675		priority: schedule::Priority,676		origin: T::PalletsOrigin,677		call: <T as Config>::Call,678	) -> Result<Self::Address, DispatchError> {679		Self::do_schedule(when, maybe_periodic, priority, origin, call)680	}681682	fn cancel((when, index): Self::Address) -> Result<(), ()> {683		Self::do_cancel(None, (when, index)).map_err(|_| ())684	}685686	fn reschedule(687		address: Self::Address,688		when: DispatchTime<T::BlockNumber>,689	) -> Result<Self::Address, DispatchError> {690		Self::do_reschedule(address, when)691	}692693	fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {694		Agenda::<T>::get(when)695			.get(index as usize)696			.ok_or(())697			.map(|_| when)698	}699}700701impl<T: Config> schedule::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>702	for Module<T>703{704	type Address = TaskAddress<T::BlockNumber>;705706	fn schedule_named(707		id: Vec<u8>,708		when: DispatchTime<T::BlockNumber>,709		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,710		priority: schedule::Priority,711		origin: T::PalletsOrigin,712		call: <T as Config>::Call,713	) -> Result<Self::Address, ()> {714		Self::do_schedule_named(id, when, maybe_periodic, priority, origin, call).map_err(|_| ())715	}716717	fn cancel_named(id: Vec<u8>) -> Result<(), ()> {718		Self::do_cancel_named(None, id).map_err(|_| ())719	}720721	fn reschedule_named(722		id: Vec<u8>,723		when: DispatchTime<T::BlockNumber>,724	) -> Result<Self::Address, DispatchError> {725		Self::do_reschedule_named(id, when)726	}727728	fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {729		Lookup::<T>::get(id)730			.and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))731			.ok_or(())732	}733}734735#[cfg(test)]736#[allow(clippy::from_over_into)]737mod tests {738	use super::*;739740	use frame_support::{741		ord_parameter_types, parameter_types, traits::Contains, weights::constants::RocksDbWeight,742	};743	use sp_core::H256;744	use sp_runtime::{745		Perbill,746		testing::Header,747		traits::{BlakeTwo256, IdentityLookup},748	};749	use frame_system::{EnsureOneOf, EnsureRoot, EnsureSignedBy};750	use crate as scheduler;751752	mod logger {753		use super::*;754		use std::cell::RefCell;755756		thread_local! {757			static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());758		}759		pub trait Config: system::Config {760			type Event: From<Event> + Into<<Self as system::Config>::Event>;761		}762		decl_event! {763			pub enum Event {764				Logged(u32, Weight),765			}766		}767		decl_module! {768			pub struct Module<T: Config> for enum Call769			where770				origin: <T as system::Config>::Origin,771				<T as system::Config>::Origin: OriginTrait<PalletsOrigin = OriginCaller>772			{773				fn deposit_event() = default;774775				#[weight = *weight]776				fn log(origin, i: u32, weight: Weight) {777					Self::deposit_event(Event::Logged(i, weight));778					LOG.with(|log| {779						log.borrow_mut().push((origin.caller().clone(), i));780					})781				}782783				#[weight = *weight]784				fn log_without_filter(origin, i: u32, weight: Weight) {785					Self::deposit_event(Event::Logged(i, weight));786					LOG.with(|log| {787						log.borrow_mut().push((origin.caller().clone(), i));788					})789				}790			}791		}792	}793794	type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;795	type Block = frame_system::mocking::MockBlock<Test>;796797	frame_support::construct_runtime!(798		pub enum Test where799			Block = Block,800			NodeBlock = Block,801			UncheckedExtrinsic = UncheckedExtrinsic,802		{803			System: frame_system::{Pallet, Call, Config, Storage, Event<T>},804			Logger: logger::{Pallet, Call, Event},805			Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},806		}807	);808809	// Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.810	pub struct BaseFilter;811	impl Contains<Call> for BaseFilter {812		fn contains(call: &Call) -> bool {813			!matches!(call, Call::Logger(logger::Call::log { .. }))814		}815	}816817	parameter_types! {818		pub const BlockHashCount: u64 = 250;819		pub BlockWeights: frame_system::limits::BlockWeights =820			frame_system::limits::BlockWeights::simple_max(2_000_000_000_000);821	}822	impl system::Config for Test {823		type BaseCallFilter = BaseFilter;824		type BlockWeights = ();825		type BlockLength = ();826		type DbWeight = RocksDbWeight;827		type Origin = Origin;828		type Call = Call;829		type Index = u64;830		type BlockNumber = u64;831		type Hash = H256;832		type Hashing = BlakeTwo256;833		type AccountId = u64;834		type Lookup = IdentityLookup<Self::AccountId>;835		type Header = Header;836		type Event = Event;837		type BlockHashCount = BlockHashCount;838		type Version = ();839		type PalletInfo = PalletInfo;840		type AccountData = ();841		type OnNewAccount = ();842		type OnKilledAccount = ();843		type SystemWeightInfo = ();844		type SS58Prefix = ();845		type OnSetCode = ();846	}847	impl logger::Config for Test {848		type Event = Event;849	}850	parameter_types! {851		pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;852		pub const MaxScheduledPerBlock: u32 = 10;853	}854	ord_parameter_types! {855		pub const One: u64 = 1;856	}857858	impl Config for Test {859		type Event = Event;860		type Origin = Origin;861		type PalletsOrigin = OriginCaller;862		type Call = Call;863		type MaximumWeight = MaximumSchedulerWeight;864		type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;865		type MaxScheduledPerBlock = MaxScheduledPerBlock;866		type WeightInfo = ();867		type SponsorshipHandler = ();868	}869}
modifiedpallets/unique/src/mock.rsdiffbeforeafterboth
--- a/pallets/unique/src/mock.rs
+++ b/pallets/unique/src/mock.rs
@@ -10,7 +10,7 @@
 use pallet_transaction_payment::{CurrencyAdapter};
 use frame_system as system;
 use pallet_evm::AddressMapping;
-use crate::{EvmBackwardsAddressMapping, CrossAccountId};
+use pallet_common::account::{EvmBackwardsAddressMapping, CrossAccountId};
 use codec::{Encode, Decode};
 use scale_info::TypeInfo;
 
@@ -27,6 +27,10 @@
 		System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
 		TemplateModule: pallet_template::{Pallet, Call, Storage},
 		Balances: pallet_balances::{Pallet, Call, Storage},
+		Common: pallet_common::{Pallet, Storage, Event<T>},
+		Fungible: pallet_fungible::{Pallet, Storage},
+		Refungible: pallet_refungible::{Pallet, Storage},
+		Nonfungible: pallet_nonfungible::{Pallet, Storage},
 	}
 );
 
@@ -124,13 +128,16 @@
 #[derive(Encode, Decode, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, TypeInfo)]
 pub struct TestCrossAccountId(u64, sp_core::H160);
 impl CrossAccountId<u64> for TestCrossAccountId {
+	fn as_sub(&self) -> &u64 {
+		&self.0
+	}
+	fn as_eth(&self) -> &sp_core::H160 {
+		&self.1
+	}
 	fn from_sub(sub: u64) -> Self {
 		let mut eth = [0; 20];
 		eth[12..20].copy_from_slice(&sub.to_be_bytes());
 		Self(sub, sp_core::H160(eth))
-	}
-	fn as_sub(&self) -> &u64 {
-		&self.0
 	}
 	fn from_eth(eth: sp_core::H160) -> Self {
 		let mut sub_raw = [0; 8];
@@ -138,11 +145,17 @@
 		let sub = u64::from_be_bytes(sub_raw);
 		Self(sub, eth)
 	}
-	fn as_eth(&self) -> &sp_core::H160 {
-		&self.1
+	fn conv_eq(&self, other: &Self) -> bool {
+		self.as_sub() == other.as_sub()
 	}
 }
 
+impl Default for TestCrossAccountId {
+	fn default() -> Self {
+		Self::from_sub(0)
+	}
+}
+
 pub struct TestEtheremTransactionSender;
 impl pallet_ethereum::EthereumTransactionSender for TestEtheremTransactionSender {
 	fn submit_logs_transaction(
@@ -157,15 +170,29 @@
 	type EthereumTransactionSender = TestEtheremTransactionSender;
 }
 
-impl pallet_template::Config for Test {
+impl pallet_common::Config for Test {
 	type Event = ();
-	type WeightInfo = ();
-	type CollectionCreationPrice = CollectionCreationPrice;
-	type Currency = pallet_balances::Pallet<Test>;
-	type TreasuryAccountId = TreasuryAccountId;
-	type EvmAddressMapping = TestEvmAddressMapping;
 	type EvmBackwardsAddressMapping = TestEvmBackwardsAddressMapping;
+	type EvmAddressMapping = TestEvmAddressMapping;
 	type CrossAccountId = TestCrossAccountId;
+
+	type Currency = Balances;
+	type CollectionCreationPrice = CollectionCreationPrice;
+	type TreasuryAccountId = TreasuryAccountId;
+}
+
+impl pallet_fungible::Config for Test {
+	type WeightInfo = ();
+}
+impl pallet_refungible::Config for Test {
+	type WeightInfo = ();
+}
+impl pallet_nonfungible::Config for Test {
+	type WeightInfo = ();
+}
+
+impl pallet_template::Config for Test {
+	type WeightInfo = ();
 }
 
 // Build genesis storage according to the mock runtime.
modifiedpallets/unique/src/tests.rsdiffbeforeafterboth
--- a/pallets/unique/src/tests.rs
+++ b/pallets/unique/src/tests.rs
@@ -1,10 +1,11 @@
 // Tests to be written here
 use super::*;
 use crate::mock::*;
-use crate::{AccessMode, CollectionMode, Ownership, CreateItemData};
+use crate::{AccessMode, CollectionMode};
 use up_data_structs::{
-	CreateNftData, CreateFungibleData, CreateReFungibleData, CollectionId, TokenId,
-	MAX_DECIMAL_POINTS,
+	COLLECTION_NUMBER_LIMIT, CollectionId, CreateItemData, CreateFungibleData, CreateNftData,
+	CreateReFungibleData, MAX_DECIMAL_POINTS, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission,
+	TokenId,
 };
 use frame_support::{assert_noop, assert_ok};
 use sp_std::convert::TryInto;
@@ -49,18 +50,30 @@
 	let saved_col_name: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
 	let saved_description: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
 	let saved_prefix: Vec<u8> = b"token_prefix1\0".to_vec();
-	assert_eq!(TemplateModule::collection_id(id).unwrap().owner, owner);
 	assert_eq!(
-		TemplateModule::collection_id(id).unwrap().name,
+		<pallet_common::CollectionById<Test>>::get(id)
+			.unwrap()
+			.owner,
+		owner
+	);
+	assert_eq!(
+		<pallet_common::CollectionById<Test>>::get(id).unwrap().name,
 		saved_col_name
 	);
-	assert_eq!(TemplateModule::collection_id(id).unwrap().mode, *mode);
 	assert_eq!(
-		TemplateModule::collection_id(id).unwrap().description,
+		<pallet_common::CollectionById<Test>>::get(id).unwrap().mode,
+		*mode
+	);
+	assert_eq!(
+		<pallet_common::CollectionById<Test>>::get(id)
+			.unwrap()
+			.description,
 		saved_description
 	);
 	assert_eq!(
-		TemplateModule::collection_id(id).unwrap().token_prefix,
+		<pallet_common::CollectionById<Test>>::get(id)
+			.unwrap()
+			.token_prefix,
 		saved_prefix
 	);
 	id
@@ -91,7 +104,7 @@
 fn set_version_schema() {
 	new_test_ext().execute_with(|| {
 		let origin1 = Origin::signed(1);
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		assert_ok!(TemplateModule::set_schema_version(
 			origin1,
@@ -99,7 +112,7 @@
 			SchemaVersion::Unique
 		));
 		assert_eq!(
-			TemplateModule::collection_id(collection_id)
+			<pallet_common::CollectionById<Test>>::get(collection_id)
 				.unwrap()
 				.schema_version,
 			SchemaVersion::Unique
@@ -131,11 +144,12 @@
 #[test]
 fn create_nft_item() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let data = default_nft_data();
 		create_test_item(collection_id, &data.clone().into());
-		let item = TemplateModule::nft_item_id(collection_id, 1).unwrap();
+
+		let item = <pallet_nonfungible::TokenData<Test>>::get((collection_id, 1)).unwrap();
 		assert_eq!(item.const_data, data.const_data.into_inner());
 		assert_eq!(item.variable_data, data.variable_data.into_inner());
 	});
@@ -146,7 +160,7 @@
 #[test]
 fn create_nft_multiple_items() {
 	new_test_ext().execute_with(|| {
-		create_test_collection(&CollectionMode::NFT, 1);
+		create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 
@@ -154,7 +168,7 @@
 
 		assert_ok!(TemplateModule::create_multiple_items(
 			origin1,
-			1,
+			CollectionId(1),
 			account(1),
 			items_data
 				.clone()
@@ -163,7 +177,11 @@
 				.collect()
 		));
 		for (index, data) in items_data.into_iter().enumerate() {
-			let item = TemplateModule::nft_item_id(1, (index + 1) as TokenId).unwrap();
+			let item = <pallet_nonfungible::TokenData<Test>>::get((
+				CollectionId(1),
+				TokenId((index + 1) as u32),
+			))
+			.unwrap();
 			assert_eq!(item.const_data.to_vec(), data.const_data.into_inner());
 			assert_eq!(item.variable_data.to_vec(), data.variable_data.into_inner());
 		}
@@ -173,27 +191,23 @@
 #[test]
 fn create_refungible_item() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);
+		let collection_id = create_test_collection(&CollectionMode::ReFungible, CollectionId(1));
 
 		let data = default_re_fungible_data();
 		create_test_item(collection_id, &data.clone().into());
-		let item = TemplateModule::refungible_item_id(collection_id, 1).unwrap();
+		let item = <pallet_refungible::TokenData<Test>>::get((collection_id, TokenId(1)));
+		let balance =
+			<pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(1)));
 		assert_eq!(item.const_data, data.const_data.into_inner());
 		assert_eq!(item.variable_data, data.variable_data.into_inner());
-		assert_eq!(
-			item.owner[0],
-			Ownership {
-				owner: account(1),
-				fraction: 1023
-			}
-		);
+		assert_eq!(balance, 1023);
 	});
 }
 
 #[test]
 fn create_multiple_refungible_items() {
 	new_test_ext().execute_with(|| {
-		create_test_collection(&CollectionMode::ReFungible, 1);
+		create_test_collection(&CollectionMode::ReFungible, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 
@@ -205,7 +219,7 @@
 
 		assert_ok!(TemplateModule::create_multiple_items(
 			origin1,
-			1,
+			CollectionId(1),
 			account(1),
 			items_data
 				.clone()
@@ -214,16 +228,15 @@
 				.collect()
 		));
 		for (index, data) in items_data.into_iter().enumerate() {
-			let item = TemplateModule::refungible_item_id(1, (index + 1) as TokenId).unwrap();
+			let item = <pallet_refungible::TokenData<Test>>::get((
+				CollectionId(1),
+				TokenId((index + 1) as u32),
+			));
+			let balance =
+				<pallet_refungible::Balance<Test>>::get((CollectionId(1), TokenId(1), account(1)));
 			assert_eq!(item.const_data.to_vec(), data.const_data.into_inner());
 			assert_eq!(item.variable_data.to_vec(), data.variable_data.into_inner());
-			assert_eq!(
-				item.owner[0],
-				Ownership {
-					owner: account(1),
-					fraction: 1023
-				}
-			);
+			assert_eq!(balance, 1023);
 		}
 	});
 }
@@ -231,12 +244,15 @@
 #[test]
 fn create_fungible_item() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);
+		let collection_id = create_test_collection(&CollectionMode::Fungible(3), CollectionId(1));
 
 		let data = default_fungible_data();
 		create_test_item(collection_id, &data.into());
 
-		assert_eq!(TemplateModule::fungible_item_id(collection_id, 1).value, 5);
+		assert_eq!(
+			<pallet_fungible::Balance<Test>>::get((collection_id, account(1))),
+			5
+		);
 	});
 }
 
@@ -245,7 +261,7 @@
 //     new_test_ext().execute_with(|| {
 //         default_limits();
 
-//         create_test_collection(&CollectionMode::Fungible(3), 1);
+//         create_test_collection(&CollectionMode::Fungible(3), CollectionId(1));
 
 //         let origin1 = Origin::signed(1);
 
@@ -269,7 +285,7 @@
 #[test]
 fn transfer_fungible_item() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);
+		let collection_id = create_test_collection(&CollectionMode::Fungible(3), CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 		let origin2 = Origin::signed(2);
@@ -277,155 +293,287 @@
 		let data = default_fungible_data();
 		create_test_item(collection_id, &data.into());
 
-		assert_eq!(TemplateModule::fungible_item_id(1, 1).value, 5);
-		assert_eq!(TemplateModule::balance_count(1, 1), 5);
+		assert_eq!(
+			<pallet_fungible::Balance<Test>>::get((CollectionId(1), account(1))),
+			5
+		);
 
 		// change owner scenario
-		assert_ok!(TemplateModule::transfer(origin1, account(2), 1, 1, 5));
-		assert_eq!(TemplateModule::fungible_item_id(1, 1).value, 0);
-		assert_eq!(TemplateModule::balance_count(1, 1), 0);
-		assert_eq!(TemplateModule::balance_count(1, 2), 5);
+		assert_ok!(TemplateModule::transfer(
+			origin1,
+			account(2),
+			CollectionId(1),
+			TokenId(0),
+			5
+		));
+		assert_eq!(
+			<pallet_fungible::Balance<Test>>::get((CollectionId(1), account(1))),
+			0
+		);
 
 		// split item scenario
 		assert_ok!(TemplateModule::transfer(
 			origin2.clone(),
 			account(3),
-			1,
-			1,
+			CollectionId(1),
+			TokenId(0),
 			3
 		));
-		assert_eq!(TemplateModule::balance_count(1, 2), 2);
-		assert_eq!(TemplateModule::balance_count(1, 3), 3);
 
 		// split item and new owner has account scenario
-		assert_ok!(TemplateModule::transfer(origin2, account(3), 1, 1, 1));
-		assert_eq!(TemplateModule::fungible_item_id(1, 2).value, 1);
-		assert_eq!(TemplateModule::fungible_item_id(1, 3).value, 4);
-		assert_eq!(TemplateModule::balance_count(1, 2), 1);
-		assert_eq!(TemplateModule::balance_count(1, 3), 4);
+		assert_ok!(TemplateModule::transfer(
+			origin2,
+			account(3),
+			CollectionId(1),
+			TokenId(0),
+			1
+		));
+		assert_eq!(
+			<pallet_fungible::Balance<Test>>::get((CollectionId(1), account(2))),
+			1
+		);
+		assert_eq!(
+			<pallet_fungible::Balance<Test>>::get((CollectionId(1), account(3))),
+			4
+		);
 	});
 }
 
 #[test]
 fn transfer_refungible_item() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);
+		let collection_id = create_test_collection(&CollectionMode::ReFungible, CollectionId(1));
 
+		// Create RFT 1 in 1023 pieces for account 1
 		let data = default_re_fungible_data();
 		create_test_item(collection_id, &data.clone().into());
+		let item = <pallet_refungible::TokenData<Test>>::get((collection_id, TokenId(1)));
+		assert_eq!(item.const_data, data.const_data.into_inner());
+		assert_eq!(item.variable_data, data.variable_data.into_inner());
+		assert_eq!(
+			<pallet_refungible::AccountBalance<Test>>::get((collection_id, account(1))),
+			1
+		);
+		assert_eq!(
+			<pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(1))),
+			1023
+		);
+		assert_eq!(
+			<pallet_refungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+			true
+		);
 
+		// Account 1 transfers all 1023 pieces of RFT 1 to account 2
 		let origin1 = Origin::signed(1);
 		let origin2 = Origin::signed(2);
-		{
-			let item = TemplateModule::refungible_item_id(collection_id, 1).unwrap();
-			assert_eq!(item.const_data, data.const_data.into_inner());
-			assert_eq!(item.variable_data, data.variable_data.into_inner());
-			assert_eq!(
-				item.owner[0],
-				Ownership {
-					owner: account(1),
-					fraction: 1023
-				}
-			);
-		}
-		assert_eq!(TemplateModule::balance_count(1, 1), 1023);
-		assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
-
-		// change owner scenario
-		assert_ok!(TemplateModule::transfer(origin1, account(2), 1, 1, 1023));
+		assert_ok!(TemplateModule::transfer(
+			origin1,
+			account(2),
+			CollectionId(1),
+			TokenId(1),
+			1023
+		));
 		assert_eq!(
-			TemplateModule::refungible_item_id(1, 1).unwrap().owner[0],
-			Ownership {
-				owner: account(2),
-				fraction: 1023
-			}
+			<pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(2))),
+			1023
+		);
+		assert_eq!(
+			<pallet_refungible::AccountBalance<Test>>::get((collection_id, account(1))),
+			0
+		);
+		assert_eq!(
+			<pallet_refungible::AccountBalance<Test>>::get((collection_id, account(2))),
+			1
+		);
+		assert_eq!(
+			<pallet_refungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+			false
+		);
+		assert_eq!(
+			<pallet_refungible::Owned<Test>>::get((collection_id, account(2), TokenId(1))),
+			true
 		);
-		assert_eq!(TemplateModule::balance_count(1, 1), 0);
-		assert_eq!(TemplateModule::balance_count(1, 2), 1023);
-		// assert_eq!(TemplateModule::address_tokens(1, 1), []);
-		assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
 
-		// split item scenario
+		// Account 2 transfers 500 pieces of RFT 1 to account 3
 		assert_ok!(TemplateModule::transfer(
 			origin2.clone(),
 			account(3),
-			1,
-			1,
+			CollectionId(1),
+			TokenId(1),
 			500
 		));
-		{
-			let item = TemplateModule::refungible_item_id(1, 1).unwrap();
-			assert_eq!(
-				item.owner[0],
-				Ownership {
-					owner: account(2),
-					fraction: 523
-				}
-			);
-			assert_eq!(
-				item.owner[1],
-				Ownership {
-					owner: account(3),
-					fraction: 500
-				}
-			);
-		}
-		assert_eq!(TemplateModule::balance_count(1, 2), 523);
-		assert_eq!(TemplateModule::balance_count(1, 3), 500);
-		assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
-		assert_eq!(TemplateModule::address_tokens(1, 3), [1]);
+		assert_eq!(
+			<pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(2))),
+			523
+		);
+		assert_eq!(
+			<pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(3))),
+			500
+		);
+		assert_eq!(
+			<pallet_refungible::AccountBalance<Test>>::get((collection_id, account(2))),
+			1
+		);
+		assert_eq!(
+			<pallet_refungible::AccountBalance<Test>>::get((collection_id, account(3))),
+			1
+		);
+		assert_eq!(
+			<pallet_refungible::Owned<Test>>::get((collection_id, account(2), TokenId(1))),
+			true
+		);
+		assert_eq!(
+			<pallet_refungible::Owned<Test>>::get((collection_id, account(3), TokenId(1))),
+			true
+		);
 
-		// split item and new owner has account scenario
-		assert_ok!(TemplateModule::transfer(origin2, account(3), 1, 1, 200));
-		{
-			let item = TemplateModule::refungible_item_id(1, 1).unwrap();
-			assert_eq!(
-				item.owner[0],
-				Ownership {
-					owner: account(2),
-					fraction: 323
-				}
-			);
-			assert_eq!(
-				item.owner[1],
-				Ownership {
-					owner: account(3),
-					fraction: 700
-				}
-			);
-		}
-		assert_eq!(TemplateModule::balance_count(1, 2), 323);
-		assert_eq!(TemplateModule::balance_count(1, 3), 700);
-		assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
-		assert_eq!(TemplateModule::address_tokens(1, 3), [1]);
+		// Account 2 transfers 200 more pieces of RFT 1 to account 3 with pre-existing balance
+		assert_ok!(TemplateModule::transfer(
+			origin2,
+			account(3),
+			CollectionId(1),
+			TokenId(1),
+			200
+		));
+		assert_eq!(
+			<pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(2))),
+			323
+		);
+		assert_eq!(
+			<pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(3))),
+			700
+		);
+		assert_eq!(
+			<pallet_refungible::AccountBalance<Test>>::get((collection_id, account(2))),
+			1
+		);
+		assert_eq!(
+			<pallet_refungible::AccountBalance<Test>>::get((collection_id, account(3))),
+			1
+		);
+		assert_eq!(
+			<pallet_refungible::Owned<Test>>::get((collection_id, account(2), TokenId(1))),
+			true
+		);
+		assert_eq!(
+			<pallet_refungible::Owned<Test>>::get((collection_id, account(3), TokenId(1))),
+			true
+		);
 	});
 }
 
 #[test]
 fn transfer_nft_item() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let data = default_nft_data();
 		create_test_item(collection_id, &data.into());
-		assert_eq!(TemplateModule::balance_count(1, 1), 1);
-		assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+		assert_eq!(
+			<pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+			1
+		);
+		assert_eq!(
+			<pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+			true
+		);
 
 		let origin1 = Origin::signed(1);
 		// default scenario
-		assert_ok!(TemplateModule::transfer(origin1, account(2), 1, 1, 1000));
-		assert_eq!(TemplateModule::nft_item_id(1, 1).unwrap().owner, account(2));
-		assert_eq!(TemplateModule::balance_count(1, 1), 0);
-		assert_eq!(TemplateModule::balance_count(1, 2), 1);
-		// assert_eq!(TemplateModule::address_tokens(1, 1), []);
-		assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
+		assert_ok!(TemplateModule::transfer(
+			origin1,
+			account(2),
+			CollectionId(1),
+			TokenId(1),
+			1
+		));
+		assert_eq!(
+			<pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+			0
+		);
+		assert_eq!(
+			<pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(2))),
+			1
+		);
+		assert_eq!(
+			<pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+			false
+		);
+		assert_eq!(
+			<pallet_nonfungible::Owned<Test>>::get((collection_id, account(2), TokenId(1))),
+			true
+		);
+	});
+}
+
+#[test]
+fn transfer_nft_item_wrong_value() {
+	new_test_ext().execute_with(|| {
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
+
+		let data = default_nft_data();
+		create_test_item(collection_id, &data.into());
+		assert_eq!(
+			<pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+			1
+		);
+		assert_eq!(
+			<pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+			true
+		);
+
+		let origin1 = Origin::signed(1);
+
+		assert_noop!(
+			TemplateModule::transfer(origin1, account(2), CollectionId(1), TokenId(1), 2)
+				.map_err(|e| e.error),
+			<pallet_nonfungible::Error::<Test>>::NonfungibleItemsHaveNoAmount
+		);
 	});
 }
 
 #[test]
+fn transfer_nft_item_zero_value() {
+	new_test_ext().execute_with(|| {
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
+
+		let data = default_nft_data();
+		create_test_item(collection_id, &data.into());
+		assert_eq!(
+			<pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+			1
+		);
+		assert_eq!(
+			<pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+			true
+		);
+
+		let origin1 = Origin::signed(1);
+
+		// Transferring 0 amount works on NFT...
+		assert_ok!(TemplateModule::transfer(
+			origin1,
+			account(2),
+			CollectionId(1),
+			TokenId(1),
+			0
+		));
+		// ... and results in no transfer
+		assert_eq!(
+			<pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+			1
+		);
+		assert_eq!(
+			<pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+			true
+		);
+	});
+}
+
+#[test]
 fn nft_approve_and_transfer_from() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let data = default_nft_data();
 		create_test_item(collection_id, &data.into());
@@ -433,197 +581,286 @@
 		let origin1 = Origin::signed(1);
 		let origin2 = Origin::signed(2);
 
-		assert_eq!(TemplateModule::balance_count(1, 1), 1);
-		assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+		assert_eq!(
+			<pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+			1
+		);
+		assert_eq!(
+			<pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+			true
+		);
 
-		// neg transfer
+		// neg transfer_from
 		assert_noop!(
-			TemplateModule::transfer_from(origin2.clone(), account(1), account(2), 1, 1, 1),
-			Error::<Test>::NoPermission
+			TemplateModule::transfer_from(
+				origin2.clone(),
+				account(1),
+				account(2),
+				CollectionId(1),
+				TokenId(1),
+				1
+			)
+			.map_err(|e| e.error),
+			CommonError::<Test>::TokenValueNotEnough
 		);
 
 		// do approve
-		assert_ok!(TemplateModule::approve(origin1, account(2), 1, 1, 5));
-		assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 5);
-		assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 5);
+		assert_ok!(TemplateModule::approve(
+			origin1,
+			account(2),
+			CollectionId(1),
+			TokenId(1),
+			1
+		));
+		assert_eq!(
+			<pallet_nonfungible::Allowance<Test>>::get((CollectionId(1), TokenId(1))).unwrap(),
+			account(2)
+		);
 
 		assert_ok!(TemplateModule::transfer_from(
 			origin2,
 			account(1),
 			account(3),
-			1,
-			1,
+			CollectionId(1),
+			TokenId(1),
 			1
 		));
-		assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 4);
+		assert!(
+			<pallet_nonfungible::Allowance<Test>>::get((CollectionId(1), TokenId(1))).is_none()
+		);
 	});
 }
 
 #[test]
 fn nft_approve_and_transfer_from_allow_list() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 		let origin2 = Origin::signed(2);
 
+		// Create NFT 1 for account 1
 		let data = default_nft_data();
 		create_test_item(collection_id, &data.clone().into());
-
 		assert_eq!(
-			&TemplateModule::nft_item_id(1, 1).unwrap().const_data,
+			&<pallet_nonfungible::TokenData<Test>>::get((collection_id, TokenId(1)))
+				.unwrap()
+				.const_data,
 			&data.const_data.into_inner()
 		);
-		assert_eq!(TemplateModule::balance_count(1, 1), 1);
-		assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+		assert_eq!(
+			<pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+			1
+		);
+		assert_eq!(
+			<pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+			true
+		);
 
+		// Allow allow-list users to mint and add accounts 1, 2, and 3 to allow-list
 		assert_ok!(TemplateModule::set_mint_permission(
 			origin1.clone(),
-			1,
+			CollectionId(1),
 			true
 		));
 		assert_ok!(TemplateModule::set_public_access_mode(
 			origin1.clone(),
-			1,
+			CollectionId(1),
 			AccessMode::AllowList
 		));
 		assert_ok!(TemplateModule::add_to_allow_list(
 			origin1.clone(),
-			1,
+			CollectionId(1),
 			account(1)
 		));
 		assert_ok!(TemplateModule::add_to_allow_list(
 			origin1.clone(),
-			1,
+			CollectionId(1),
 			account(2)
 		));
 		assert_ok!(TemplateModule::add_to_allow_list(
 			origin1.clone(),
-			1,
+			CollectionId(1),
 			account(3)
 		));
 
-		// do approve
+		// Account 1 approves account 2 for NFT 1
 		assert_ok!(TemplateModule::approve(
 			origin1.clone(),
 			account(2),
-			1,
-			1,
-			5
+			CollectionId(1),
+			TokenId(1),
+			1
 		));
-		assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 5);
-		assert_ok!(TemplateModule::approve(origin1, account(3), 1, 1, 5));
-		assert_eq!(TemplateModule::approved(1, (1, 1, 3)), 5);
+		assert_eq!(
+			<pallet_nonfungible::Allowance<Test>>::get((CollectionId(1), TokenId(1))).unwrap(),
+			account(2)
+		);
 
+		// Account 2 transfers NFT 1 from account 1 to account 3
 		assert_ok!(TemplateModule::transfer_from(
 			origin2,
 			account(1),
 			account(3),
-			1,
-			1,
+			CollectionId(1),
+			TokenId(1),
 			1
 		));
-		assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 4);
+		assert!(
+			<pallet_nonfungible::Allowance<Test>>::get((CollectionId(1), TokenId(1))).is_none()
+		);
 	});
 }
 
 #[test]
 fn refungible_approve_and_transfer_from() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);
+		let collection_id = create_test_collection(&CollectionMode::ReFungible, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 		let origin2 = Origin::signed(2);
 
+		// Create RFT 1 in 1023 pieces for account 1
 		let data = default_re_fungible_data();
 		create_test_item(collection_id, &data.into());
 
-		assert_eq!(TemplateModule::balance_count(1, 1), 1023);
-		assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+		assert_eq!(
+			<pallet_refungible::AccountBalance<Test>>::get((collection_id, account(1))),
+			1
+		);
+		assert_eq!(
+			<pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(1))),
+			1023
+		);
+		assert_eq!(
+			<pallet_refungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+			true
+		);
 
+		// Allow public minting, enable allow-list and add accounts 1, 2, 3 to allow-list
 		assert_ok!(TemplateModule::set_mint_permission(
 			origin1.clone(),
-			1,
+			CollectionId(1),
 			true
 		));
 		assert_ok!(TemplateModule::set_public_access_mode(
 			origin1.clone(),
-			1,
+			CollectionId(1),
 			AccessMode::AllowList
 		));
 		assert_ok!(TemplateModule::add_to_allow_list(
 			origin1.clone(),
-			1,
+			CollectionId(1),
 			account(1)
 		));
 		assert_ok!(TemplateModule::add_to_allow_list(
 			origin1.clone(),
-			1,
+			CollectionId(1),
 			account(2)
 		));
 		assert_ok!(TemplateModule::add_to_allow_list(
 			origin1.clone(),
-			1,
+			CollectionId(1),
 			account(3)
 		));
 
-		// do approve
-		assert_ok!(TemplateModule::approve(origin1, account(2), 1, 1, 1023));
-		assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 1023);
+		// Account 1 approves account 2 for 1023 pieces of RFT 1
+		assert_ok!(TemplateModule::approve(
+			origin1,
+			account(2),
+			CollectionId(1),
+			TokenId(1),
+			1023
+		));
+		assert_eq!(
+			<pallet_refungible::Allowance<Test>>::get((
+				CollectionId(1),
+				TokenId(1),
+				account(1),
+				account(2)
+			)),
+			1023
+		);
 
+		// Account 2 transfers 100 pieces of RFT 1 from account 1 to account 3
 		assert_ok!(TemplateModule::transfer_from(
 			origin2,
 			account(1),
 			account(3),
-			1,
-			1,
+			CollectionId(1),
+			TokenId(1),
 			100
 		));
-		assert_eq!(TemplateModule::balance_count(1, 1), 923);
-		assert_eq!(TemplateModule::balance_count(1, 3), 100);
-		assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
-		assert_eq!(TemplateModule::address_tokens(1, 3), [1]);
-
-		assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 923);
+		assert_eq!(
+			<pallet_refungible::AccountBalance<Test>>::get((collection_id, account(1))),
+			1
+		);
+		assert_eq!(
+			<pallet_refungible::AccountBalance<Test>>::get((collection_id, account(3))),
+			1
+		);
+		assert_eq!(
+			<pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(1))),
+			923
+		);
+		assert_eq!(
+			<pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(3))),
+			100
+		);
+		assert_eq!(
+			<pallet_refungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+			true
+		);
+		assert_eq!(
+			<pallet_refungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+			true
+		);
+		assert_eq!(
+			<pallet_refungible::Allowance<Test>>::get((
+				CollectionId(1),
+				TokenId(1),
+				account(1),
+				account(2)
+			)),
+			923
+		);
 	});
 }
 
 #[test]
 fn fungible_approve_and_transfer_from() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);
+		let collection_id = create_test_collection(&CollectionMode::Fungible(3), CollectionId(1));
 
 		let data = default_fungible_data();
 		create_test_item(collection_id, &data.into());
 
 		let origin1 = Origin::signed(1);
 		let origin2 = Origin::signed(2);
-
-		assert_eq!(TemplateModule::balance_count(1, 1), 5);
 
 		assert_ok!(TemplateModule::set_mint_permission(
 			origin1.clone(),
-			1,
+			CollectionId(1),
 			true
 		));
 		assert_ok!(TemplateModule::set_public_access_mode(
 			origin1.clone(),
-			1,
+			CollectionId(1),
 			AccessMode::AllowList
 		));
 		assert_ok!(TemplateModule::add_to_allow_list(
 			origin1.clone(),
-			1,
+			CollectionId(1),
 			account(1)
 		));
 		assert_ok!(TemplateModule::add_to_allow_list(
 			origin1.clone(),
-			1,
+			CollectionId(1),
 			account(2)
 		));
 		assert_ok!(TemplateModule::add_to_allow_list(
 			origin1.clone(),
-			1,
+			CollectionId(1),
 			account(3)
 		));
 
@@ -631,31 +868,55 @@
 		assert_ok!(TemplateModule::approve(
 			origin1.clone(),
 			account(2),
-			1,
-			1,
+			CollectionId(1),
+			TokenId(0),
 			5
 		));
-		assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 5);
-		assert_ok!(TemplateModule::approve(origin1, account(3), 1, 1, 5));
-		assert_eq!(TemplateModule::approved(1, (1, 1, 3)), 5);
-		assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 5);
+		assert_eq!(
+			<pallet_fungible::Allowance<Test>>::get((CollectionId(1), account(1), account(2))),
+			5
+		);
+		assert_ok!(TemplateModule::approve(
+			origin1,
+			account(3),
+			CollectionId(1),
+			TokenId(0),
+			5
+		));
+		assert_eq!(
+			<pallet_fungible::Allowance<Test>>::get((CollectionId(1), account(1), account(2))),
+			5
+		);
+		assert_eq!(
+			<pallet_fungible::Allowance<Test>>::get((CollectionId(1), account(1), account(3))),
+			5
+		);
 
 		assert_ok!(TemplateModule::transfer_from(
 			origin2.clone(),
 			account(1),
 			account(3),
-			1,
-			1,
+			CollectionId(1),
+			TokenId(0),
 			4
 		));
-		assert_eq!(TemplateModule::balance_count(1, 1), 1);
-		assert_eq!(TemplateModule::balance_count(1, 3), 4);
 
-		assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 1);
+		assert_eq!(
+			<pallet_fungible::Allowance<Test>>::get((CollectionId(1), account(1), account(2))),
+			1
+		);
 
 		assert_noop!(
-			TemplateModule::transfer_from(origin2, account(1), account(3), 1, 1, 4),
-			Error::<Test>::NoPermission
+			TemplateModule::transfer_from(
+				origin2,
+				account(1),
+				account(3),
+				CollectionId(1),
+				TokenId(0),
+				4
+			)
+			.map_err(|e| e.error),
+			CommonError::<Test>::TokenValueNotEnough
 		);
 	});
 }
@@ -663,7 +924,7 @@
 #[test]
 fn change_collection_owner() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 		assert_ok!(TemplateModule::change_collection_owner(
@@ -672,7 +933,9 @@
 			2
 		));
 		assert_eq!(
-			TemplateModule::collection_id(collection_id).unwrap().owner,
+			<pallet_common::CollectionById<Test>>::get(collection_id)
+				.unwrap()
+				.owner,
 			2
 		);
 	});
@@ -681,7 +944,7 @@
 #[test]
 fn destroy_collection() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 		assert_ok!(TemplateModule::destroy_collection(origin1, collection_id));
@@ -691,41 +954,74 @@
 #[test]
 fn burn_nft_item() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
-		assert_ok!(TemplateModule::add_collection_admin(
+
+		let data = default_nft_data();
+		create_test_item(collection_id, &data.into());
+
+		// check balance (collection with id = 1, user id = 1)
+		assert_eq!(
+			<pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+			1
+		);
+
+		// burn item
+		assert_ok!(TemplateModule::burn_item(
 			origin1.clone(),
 			collection_id,
-			account(2)
+			TokenId(1),
+			1
 		));
+		assert_eq!(
+			<pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+			0
+		);
+	});
+}
+
+#[test]
+fn burn_same_nft_item_twice() {
+	new_test_ext().execute_with(|| {
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
+
+		let origin1 = Origin::signed(1);
 
 		let data = default_nft_data();
 		create_test_item(collection_id, &data.into());
 
 		// check balance (collection with id = 1, user id = 1)
-		assert_eq!(TemplateModule::balance_count(1, 1), 1);
+		assert_eq!(
+			<pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+			1
+		);
 
 		// burn item
 		assert_ok!(TemplateModule::burn_item(
 			origin1.clone(),
 			collection_id,
-			1,
+			TokenId(1),
 			1
 		));
+
+		// burn item again
 		assert_noop!(
-			TemplateModule::burn_item(origin1, collection_id, 1, 1),
-			Error::<Test>::TokenNotFound
+			TemplateModule::burn_item(origin1, collection_id, TokenId(1), 1).map_err(|e| e.error),
+			CommonError::<Test>::TokenNotFound
 		);
 
-		assert_eq!(TemplateModule::balance_count(1, 1), 0);
+		assert_eq!(
+			<pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+			0
+		);
 	});
 }
 
 #[test]
 fn burn_fungible_item() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);
+		let collection_id = create_test_collection(&CollectionMode::Fungible(3), CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 		assert_ok!(TemplateModule::add_collection_admin(
@@ -738,23 +1034,62 @@
 		create_test_item(collection_id, &data.into());
 
 		// check balance (collection with id = 1, user id = 1)
-		assert_eq!(TemplateModule::balance_count(1, 1), 5);
+		assert_eq!(
+			<pallet_fungible::Balance<Test>>::get((collection_id, account(1))),
+			5
+		);
 
 		// burn item
-		assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1, 5));
+		assert_ok!(TemplateModule::burn_item(
+			origin1.clone(),
+			CollectionId(1),
+			TokenId(0),
+			5
+		));
 		assert_noop!(
-			TemplateModule::burn_item(origin1, 1, 1, 5),
-			Error::<Test>::TokenValueNotEnough
+			TemplateModule::burn_item(origin1, CollectionId(1), TokenId(0), 5).map_err(|e| e.error),
+			CommonError::<Test>::TokenValueTooLow
 		);
 
-		assert_eq!(TemplateModule::balance_count(1, 1), 0);
+		assert_eq!(
+			<pallet_fungible::Balance<Test>>::get((collection_id, account(1))),
+			0
+		);
 	});
 }
 
 #[test]
+fn burn_fungible_item_with_token_id() {
+	new_test_ext().execute_with(|| {
+		let collection_id = create_test_collection(&CollectionMode::Fungible(3), CollectionId(1));
+
+		let origin1 = Origin::signed(1);
+		assert_ok!(TemplateModule::add_collection_admin(
+			origin1.clone(),
+			collection_id,
+			account(2)
+		));
+
+		let data = default_fungible_data();
+		create_test_item(collection_id, &data.into());
+
+		// check balance (collection with id = 1, user id = 1)
+		assert_eq!(
+			<pallet_fungible::Balance<Test>>::get((collection_id, account(1))),
+			5
+		);
+
+		// Try to burn item using Token ID
+		assert_noop!(
+			TemplateModule::burn_item(origin1, CollectionId(1), TokenId(1), 5).map_err(|e| e.error),
+			<pallet_fungible::Error::<Test>>::FungibleItemsHaveNoId
+		);
+	});
+}
+#[test]
 fn burn_refungible_item() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);
+		let collection_id = create_test_collection(&CollectionMode::ReFungible, CollectionId(1));
 		let origin1 = Origin::signed(1);
 
 		assert_ok!(TemplateModule::set_mint_permission(
@@ -769,13 +1104,13 @@
 		));
 		assert_ok!(TemplateModule::add_to_allow_list(
 			origin1.clone(),
-			1,
+			collection_id,
 			account(1)
 		));
 
 		assert_ok!(TemplateModule::add_collection_admin(
 			origin1.clone(),
-			1,
+			collection_id,
 			account(2)
 		));
 
@@ -783,29 +1118,43 @@
 		create_test_item(collection_id, &data.into());
 
 		// check balance (collection with id = 1, user id = 2)
-		assert_eq!(TemplateModule::balance_count(1, 1), 1023);
+		assert_eq!(
+			<pallet_refungible::AccountBalance<Test>>::get((collection_id, account(1))),
+			1
+		);
+		assert_eq!(
+			<pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(1))),
+			1023
+		);
 
 		// burn item
-		assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1, 1023));
+		assert_ok!(TemplateModule::burn_item(
+			origin1.clone(),
+			collection_id,
+			TokenId(1),
+			1023
+		));
 		assert_noop!(
-			TemplateModule::burn_item(origin1, 1, 1, 1023),
-			Error::<Test>::TokenNotFound
+			TemplateModule::burn_item(origin1, collection_id, TokenId(1), 1023)
+				.map_err(|e| e.error),
+			CommonError::<Test>::TokenValueTooLow
 		);
 
-		assert_eq!(TemplateModule::balance_count(1, 1), 0);
+		assert_eq!(
+			<pallet_refungible::Balance<Test>>::get((collection_id, TokenId(1), account(1))),
+			0
+		);
 	});
 }
 
 #[test]
 fn add_collection_admin() {
 	new_test_ext().execute_with(|| {
-		let collection1_id = create_test_collection_for_owner(&CollectionMode::NFT, 1, 1);
-		create_test_collection_for_owner(&CollectionMode::NFT, 2, 2);
-		create_test_collection_for_owner(&CollectionMode::NFT, 3, 3);
-
+		let collection1_id =
+			create_test_collection_for_owner(&CollectionMode::NFT, 1, CollectionId(1));
 		let origin1 = Origin::signed(1);
 
-		// collection admin
+		// Add collection admins
 		assert_ok!(TemplateModule::add_collection_admin(
 			origin1.clone(),
 			collection1_id,
@@ -817,22 +1166,31 @@
 			account(3)
 		));
 
-		assert!(TemplateModule::admin_list_collection(collection1_id).contains(&account(2)),);
-		assert!(TemplateModule::admin_list_collection(collection1_id).contains(&account(3)),);
+		// Owner is not an admin by default
+		assert_eq!(
+			<pallet_common::IsAdmin<Test>>::get((CollectionId(1), account(1))),
+			false
+		);
+		assert!(<pallet_common::IsAdmin<Test>>::get((
+			CollectionId(1),
+			account(2)
+		)));
+		assert!(<pallet_common::IsAdmin<Test>>::get((
+			CollectionId(1),
+			account(3)
+		)));
 	});
 }
 
 #[test]
 fn remove_collection_admin() {
 	new_test_ext().execute_with(|| {
-		let collection1_id = create_test_collection_for_owner(&CollectionMode::NFT, 1, 1);
-		create_test_collection_for_owner(&CollectionMode::NFT, 2, 2);
-		create_test_collection_for_owner(&CollectionMode::NFT, 3, 3);
-
+		let collection1_id =
+			create_test_collection_for_owner(&CollectionMode::NFT, 1, CollectionId(1));
 		let origin1 = Origin::signed(1);
 		let origin2 = Origin::signed(2);
 
-		// collection admin
+		// Add collection admins 2 and 3
 		assert_ok!(TemplateModule::add_collection_admin(
 			origin1.clone(),
 			collection1_id,
@@ -844,31 +1202,54 @@
 			account(3)
 		));
 
-		assert!(TemplateModule::admin_list_collection(1).contains(&account(2)),);
-		assert!(TemplateModule::admin_list_collection(1).contains(&account(3)),);
+		assert!(<pallet_common::IsAdmin<Test>>::get((
+			CollectionId(1),
+			account(2)
+		)));
+		assert!(<pallet_common::IsAdmin<Test>>::get((
+			CollectionId(1),
+			account(3)
+		)));
 
-		// remove admin
+		// remove admin 3
 		assert_ok!(TemplateModule::remove_collection_admin(
 			origin2,
-			1,
+			CollectionId(1),
 			account(3)
 		));
-		assert!(!TemplateModule::admin_list_collection(1).contains(&account(3)),);
+
+		// 2 is still admin, 3 is not an admin anymore
+		assert!(<pallet_common::IsAdmin<Test>>::get((
+			CollectionId(1),
+			account(2)
+		)));
+		assert_eq!(
+			<pallet_common::IsAdmin<Test>>::get((CollectionId(1), account(3))),
+			false
+		);
 	});
 }
 
 #[test]
 fn balance_of() {
 	new_test_ext().execute_with(|| {
-		let nft_collection_id = create_test_collection(&CollectionMode::NFT, 1);
-		let fungible_collection_id = create_test_collection(&CollectionMode::Fungible(3), 2);
-		let re_fungible_collection_id = create_test_collection(&CollectionMode::ReFungible, 3);
+		let nft_collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
+		let fungible_collection_id =
+			create_test_collection(&CollectionMode::Fungible(3), CollectionId(2));
+		let re_fungible_collection_id =
+			create_test_collection(&CollectionMode::ReFungible, CollectionId(3));
 
 		// check balance before
-		assert_eq!(TemplateModule::balance_count(nft_collection_id, 1), 0);
-		assert_eq!(TemplateModule::balance_count(fungible_collection_id, 1), 0);
 		assert_eq!(
-			TemplateModule::balance_count(re_fungible_collection_id, 1),
+			<pallet_nonfungible::AccountBalance<Test>>::get((nft_collection_id, account(1))),
+			0
+		);
+		assert_eq!(
+			<pallet_fungible::Balance<Test>>::get((fungible_collection_id, account(1))),
+			0
+		);
+		assert_eq!(
+			<pallet_refungible::AccountBalance<Test>>::get((re_fungible_collection_id, account(1))),
 			0
 		);
 
@@ -882,28 +1263,30 @@
 		create_test_item(re_fungible_collection_id, &re_fungible_data.into());
 
 		// check balance (collection with id = 1, user id = 1)
-		assert_eq!(TemplateModule::balance_count(nft_collection_id, 1), 1);
-		assert_eq!(TemplateModule::balance_count(fungible_collection_id, 1), 5);
 		assert_eq!(
-			TemplateModule::balance_count(re_fungible_collection_id, 1),
-			1023
+			<pallet_nonfungible::AccountBalance<Test>>::get((nft_collection_id, account(1))),
+			1
 		);
 		assert_eq!(
-			TemplateModule::nft_item_id(nft_collection_id, 1)
-				.unwrap()
-				.owner,
-			account(1)
+			<pallet_fungible::Balance<Test>>::get((fungible_collection_id, account(1))),
+			5
 		);
 		assert_eq!(
-			TemplateModule::fungible_item_id(fungible_collection_id, 1).value,
-			5
+			<pallet_refungible::AccountBalance<Test>>::get((re_fungible_collection_id, account(1))),
+			1
 		);
+
 		assert_eq!(
-			TemplateModule::refungible_item_id(re_fungible_collection_id, 1)
-				.unwrap()
-				.owner[0]
-				.owner,
-			account(1)
+			<pallet_nonfungible::Owned<Test>>::get((nft_collection_id, account(1), TokenId(1))),
+			true
+		);
+		assert_eq!(
+			<pallet_refungible::Owned<Test>>::get((
+				re_fungible_collection_id,
+				account(1),
+				TokenId(1)
+			)),
+			true
 		);
 	});
 }
@@ -911,7 +1294,7 @@
 #[test]
 fn approve() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let data = default_nft_data();
 		create_test_item(collection_id, &data.into());
@@ -919,15 +1302,24 @@
 		let origin1 = Origin::signed(1);
 
 		// approve
-		assert_ok!(TemplateModule::approve(origin1, account(2), 1, 1, 1));
-		assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 1);
+		assert_ok!(TemplateModule::approve(
+			origin1,
+			account(2),
+			CollectionId(1),
+			TokenId(1),
+			1
+		));
+		assert_eq!(
+			<pallet_nonfungible::Allowance<Test>>::get((CollectionId(1), TokenId(1))).unwrap(),
+			account(2)
+		);
 	});
 }
 
 #[test]
 fn transfer_from() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 		let origin1 = Origin::signed(1);
 		let origin2 = Origin::signed(2);
 
@@ -938,46 +1330,59 @@
 		assert_ok!(TemplateModule::approve(
 			origin1.clone(),
 			account(2),
-			1,
-			1,
+			CollectionId(1),
+			TokenId(1),
 			1
 		));
-		assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 1);
+		assert_eq!(
+			<pallet_nonfungible::Allowance<Test>>::get((CollectionId(1), TokenId(1))).unwrap(),
+			account(2)
+		);
 
 		assert_ok!(TemplateModule::set_mint_permission(
 			origin1.clone(),
-			1,
+			CollectionId(1),
 			true
 		));
 		assert_ok!(TemplateModule::set_public_access_mode(
 			origin1.clone(),
-			1,
+			CollectionId(1),
 			AccessMode::AllowList
 		));
 		assert_ok!(TemplateModule::add_to_allow_list(
 			origin1.clone(),
-			1,
+			CollectionId(1),
 			account(1)
 		));
 		assert_ok!(TemplateModule::add_to_allow_list(
 			origin1.clone(),
-			1,
+			CollectionId(1),
 			account(2)
 		));
-		assert_ok!(TemplateModule::add_to_allow_list(origin1, 1, account(3)));
+		assert_ok!(TemplateModule::add_to_allow_list(
+			origin1,
+			CollectionId(1),
+			account(3)
+		));
 
 		assert_ok!(TemplateModule::transfer_from(
 			origin2,
 			account(1),
 			account(2),
-			1,
-			1,
+			CollectionId(1),
+			TokenId(1),
 			1
 		));
 
 		// after transfer
-		assert_eq!(TemplateModule::balance_count(1, 1), 0);
-		assert_eq!(TemplateModule::balance_count(1, 2), 1);
+		assert_eq!(
+			<pallet_nonfungible::AccountBalance<Test>>::get((CollectionId(1), account(1))),
+			0
+		);
+		assert_eq!(
+			<pallet_nonfungible::AccountBalance<Test>>::get((CollectionId(1), account(2))),
+			1
+		);
 	});
 }
 
@@ -989,7 +1394,7 @@
 #[test]
 fn owner_can_add_address_to_allow_list() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 		assert_ok!(TemplateModule::add_to_allow_list(
@@ -997,14 +1402,17 @@
 			collection_id,
 			account(2)
 		));
-		assert!(TemplateModule::allow_list(collection_id, 2));
+		assert!(<pallet_common::Allowlist<Test>>::get((
+			collection_id,
+			account(2)
+		)));
 	});
 }
 
 #[test]
 fn admin_can_add_address_to_allow_list() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 		let origin1 = Origin::signed(1);
 		let origin2 = Origin::signed(2);
 
@@ -1018,19 +1426,22 @@
 			collection_id,
 			account(3)
 		));
-		assert!(TemplateModule::allow_list(collection_id, 3));
+		assert!(<pallet_common::Allowlist<Test>>::get((
+			collection_id,
+			account(3)
+		)));
 	});
 }
 
 #[test]
 fn nonprivileged_user_cannot_add_address_to_allow_list() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin2 = Origin::signed(2);
 		assert_noop!(
 			TemplateModule::add_to_allow_list(origin2, collection_id, account(3)),
-			Error::<Test>::NoPermission
+			CommonError::<Test>::NoPermission
 		);
 	});
 }
@@ -1041,8 +1452,8 @@
 		let origin1 = Origin::signed(1);
 
 		assert_noop!(
-			TemplateModule::add_to_allow_list(origin1, 1, account(2)),
-			Error::<Test>::CollectionNotFound
+			TemplateModule::add_to_allow_list(origin1, CollectionId(1), account(2)),
+			CommonError::<Test>::CollectionNotFound
 		);
 	});
 }
@@ -1050,7 +1461,7 @@
 #[test]
 fn nobody_can_add_address_to_allow_list_of_deleted_collection() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 		assert_ok!(TemplateModule::destroy_collection(
@@ -1059,7 +1470,7 @@
 		));
 		assert_noop!(
 			TemplateModule::add_to_allow_list(origin1, collection_id, account(2)),
-			Error::<Test>::CollectionNotFound
+			CommonError::<Test>::CollectionNotFound
 		);
 	});
 }
@@ -1068,7 +1479,7 @@
 #[test]
 fn address_is_already_added_to_allow_list() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 		let origin1 = Origin::signed(1);
 
 		assert_ok!(TemplateModule::add_to_allow_list(
@@ -1081,14 +1492,17 @@
 			collection_id,
 			account(2)
 		));
-		assert!(TemplateModule::allow_list(collection_id, 2));
+		assert!(<pallet_common::Allowlist<Test>>::get((
+			collection_id,
+			account(2)
+		)));
 	});
 }
 
 #[test]
 fn owner_can_remove_address_from_allow_list() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 		assert_ok!(TemplateModule::add_to_allow_list(
@@ -1101,41 +1515,51 @@
 			collection_id,
 			account(2)
 		));
-		assert!(!TemplateModule::allow_list(collection_id, 2));
+		assert_eq!(
+			<pallet_common::Allowlist<Test>>::get((collection_id, account(2))),
+			false
+		);
 	});
 }
 
 #[test]
 fn admin_can_remove_address_from_allow_list() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 		let origin1 = Origin::signed(1);
 		let origin2 = Origin::signed(2);
 
+		// Owner adds admin
 		assert_ok!(TemplateModule::add_collection_admin(
 			origin1.clone(),
 			collection_id,
 			account(2)
 		));
 
+		// Owner adds address 3 to allow list
 		assert_ok!(TemplateModule::add_to_allow_list(
 			origin1,
 			collection_id,
 			account(3)
 		));
+
+		// Admin removes address 3 from allow list
 		assert_ok!(TemplateModule::remove_from_allow_list(
 			origin2,
 			collection_id,
 			account(3)
 		));
-		assert!(!TemplateModule::allow_list(collection_id, 3));
+		assert_eq!(
+			<pallet_common::Allowlist<Test>>::get((collection_id, account(3))),
+			false
+		);
 	});
 }
 
 #[test]
 fn nonprivileged_user_cannot_remove_address_from_allow_list() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 		let origin1 = Origin::signed(1);
 		let origin2 = Origin::signed(2);
 
@@ -1146,9 +1570,12 @@
 		));
 		assert_noop!(
 			TemplateModule::remove_from_allow_list(origin2, collection_id, account(2)),
-			Error::<Test>::NoPermission
+			CommonError::<Test>::NoPermission
 		);
-		assert!(TemplateModule::allow_list(collection_id, 2));
+		assert!(<pallet_common::Allowlist<Test>>::get((
+			collection_id,
+			account(2)
+		)));
 	});
 }
 
@@ -1158,8 +1585,8 @@
 		let origin1 = Origin::signed(1);
 
 		assert_noop!(
-			TemplateModule::remove_from_allow_list(origin1, 1, account(2)),
-			Error::<Test>::CollectionNotFound
+			TemplateModule::remove_from_allow_list(origin1, CollectionId(1), account(2)),
+			CommonError::<Test>::CollectionNotFound
 		);
 	});
 }
@@ -1167,21 +1594,37 @@
 #[test]
 fn nobody_can_remove_address_from_allow_list_of_deleted_collection() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 		let origin1 = Origin::signed(1);
 		let origin2 = Origin::signed(2);
 
+		// Add account 2 to allow list
 		assert_ok!(TemplateModule::add_to_allow_list(
 			origin1.clone(),
 			collection_id,
 			account(2)
 		));
+
+		// Account 2 is in collection allow-list
+		assert!(<pallet_common::Allowlist<Test>>::get((
+			collection_id,
+			account(2)
+		)));
+
+		// Destroy collection
 		assert_ok!(TemplateModule::destroy_collection(origin1, collection_id));
+
+		// Attempt to remove account 2 from collection allow-list => error
 		assert_noop!(
 			TemplateModule::remove_from_allow_list(origin2, collection_id, account(2)),
-			Error::<Test>::CollectionNotFound
+			CommonError::<Test>::CollectionNotFound
+		);
+
+		// Account 2 is not found in collection allow-list anyway
+		assert_eq!(
+			<pallet_common::Allowlist<Test>>::get((collection_id, account(2))),
+			false
 		);
-		assert!(!TemplateModule::allow_list(collection_id, 2));
 	});
 }
 
@@ -1189,7 +1632,7 @@
 #[test]
 fn address_is_already_removed_from_allow_list() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 		let origin1 = Origin::signed(1);
 
 		assert_ok!(TemplateModule::add_to_allow_list(
@@ -1202,12 +1645,19 @@
 			collection_id,
 			account(2)
 		));
+		assert_eq!(
+			<pallet_common::Allowlist<Test>>::get((collection_id, account(2))),
+			false
+		);
 		assert_ok!(TemplateModule::remove_from_allow_list(
 			origin1,
 			collection_id,
 			account(2)
 		));
-		assert!(!TemplateModule::allow_list(collection_id, 2));
+		assert_eq!(
+			<pallet_common::Allowlist<Test>>::get((collection_id, account(2))),
+			false
+		);
 	});
 }
 
@@ -1215,7 +1665,7 @@
 #[test]
 fn allow_list_test_1() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 
@@ -1234,8 +1684,9 @@
 		));
 
 		assert_noop!(
-			TemplateModule::transfer(origin1, account(3), 1, 1, 1),
-			Error::<Test>::AddresNotInAllowList
+			TemplateModule::transfer(origin1, account(3), CollectionId(1), TokenId(1), 1)
+				.map_err(|e| e.error),
+			CommonError::<Test>::AddressNotInAllowlist
 		);
 	});
 }
@@ -1243,7 +1694,7 @@
 #[test]
 fn allow_list_test_2() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 		let origin1 = Origin::signed(1);
 
 		let data = default_nft_data();
@@ -1256,12 +1707,12 @@
 		));
 		assert_ok!(TemplateModule::add_to_allow_list(
 			origin1.clone(),
-			1,
+			collection_id,
 			account(1)
 		));
 		assert_ok!(TemplateModule::add_to_allow_list(
 			origin1.clone(),
-			1,
+			collection_id,
 			account(2)
 		));
 
@@ -1269,21 +1720,32 @@
 		assert_ok!(TemplateModule::approve(
 			origin1.clone(),
 			account(1),
-			1,
-			1,
+			collection_id,
+			TokenId(1),
 			1
 		));
-		assert_eq!(TemplateModule::approved(1, (1, 1, 1)), 1);
+		assert_eq!(
+			<pallet_nonfungible::Allowance<Test>>::get((CollectionId(1), TokenId(1))).unwrap(),
+			account(1)
+		);
 
 		assert_ok!(TemplateModule::remove_from_allow_list(
 			origin1.clone(),
-			1,
+			collection_id,
 			account(1)
 		));
 
 		assert_noop!(
-			TemplateModule::transfer_from(origin1, account(1), account(3), 1, 1, 1),
-			Error::<Test>::AddresNotInAllowList
+			TemplateModule::transfer_from(
+				origin1,
+				account(1),
+				account(3),
+				CollectionId(1),
+				TokenId(1),
+				1
+			)
+			.map_err(|e| e.error),
+			CommonError::<Test>::AddressNotInAllowlist
 		);
 	});
 }
@@ -1292,7 +1754,7 @@
 #[test]
 fn allow_list_test_3() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 
@@ -1306,13 +1768,14 @@
 		));
 		assert_ok!(TemplateModule::add_to_allow_list(
 			origin1.clone(),
-			1,
+			collection_id,
 			account(1)
 		));
 
 		assert_noop!(
-			TemplateModule::transfer(origin1, account(3), 1, 1, 1),
-			Error::<Test>::AddresNotInAllowList
+			TemplateModule::transfer(origin1, account(3), collection_id, TokenId(1), 1)
+				.map_err(|e| e.error),
+			CommonError::<Test>::AddressNotInAllowlist
 		);
 	});
 }
@@ -1320,7 +1783,7 @@
 #[test]
 fn allow_list_test_4() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 
@@ -1347,11 +1810,14 @@
 		assert_ok!(TemplateModule::approve(
 			origin1.clone(),
 			account(1),
-			1,
-			1,
+			collection_id,
+			TokenId(1),
 			1
 		));
-		assert_eq!(TemplateModule::approved(1, (1, 1, 1)), 1);
+		assert_eq!(
+			<pallet_nonfungible::Allowance<Test>>::get((CollectionId(1), TokenId(1))).unwrap(),
+			account(1)
+		);
 
 		assert_ok!(TemplateModule::remove_from_allow_list(
 			origin1.clone(),
@@ -1360,8 +1826,16 @@
 		));
 
 		assert_noop!(
-			TemplateModule::transfer_from(origin1, account(1), account(3), 1, 1, 1),
-			Error::<Test>::AddresNotInAllowList
+			TemplateModule::transfer_from(
+				origin1,
+				account(1),
+				account(3),
+				collection_id,
+				TokenId(1),
+				1
+			)
+			.map_err(|e| e.error),
+			CommonError::<Test>::AddressNotInAllowlist
 		);
 	});
 }
@@ -1370,7 +1844,7 @@
 #[test]
 fn allow_list_test_5() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 
@@ -1383,8 +1857,9 @@
 			AccessMode::AllowList
 		));
 		assert_noop!(
-			TemplateModule::burn_item(origin1.clone(), 1, 1, 5),
-			Error::<Test>::AddresNotInAllowList
+			TemplateModule::burn_item(origin1.clone(), CollectionId(1), TokenId(1), 1)
+				.map_err(|e| e.error),
+			CommonError::<Test>::AddressNotInAllowlist
 		);
 	});
 }
@@ -1393,7 +1868,7 @@
 #[test]
 fn allow_list_test_6() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 
@@ -1408,8 +1883,9 @@
 
 		// do approve
 		assert_noop!(
-			TemplateModule::approve(origin1, account(1), 1, 1, 5),
-			Error::<Test>::AddresNotInAllowList
+			TemplateModule::approve(origin1, account(1), CollectionId(1), TokenId(1), 1)
+				.map_err(|e| e.error),
+			CommonError::<Test>::AddressNotInAllowlist
 		);
 	});
 }
@@ -1419,7 +1895,7 @@
 #[test]
 fn allow_list_test_7() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let data = default_nft_data();
 		create_test_item(collection_id, &data.into());
@@ -1442,20 +1918,28 @@
 			account(2)
 		));
 
-		assert_ok!(TemplateModule::transfer(origin1, account(2), 1, 1, 1));
+		assert_ok!(TemplateModule::transfer(
+			origin1,
+			account(2),
+			CollectionId(1),
+			TokenId(1),
+			1
+		));
 	});
 }
 
 #[test]
 fn allow_list_test_8() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
+		// Create NFT for account 1
 		let data = default_nft_data();
 		create_test_item(collection_id, &data.into());
 
 		let origin1 = Origin::signed(1);
 
+		// Toggle Allow List mode and add accounts 1 and 2
 		assert_ok!(TemplateModule::set_public_access_mode(
 			origin1.clone(),
 			collection_id,
@@ -1472,22 +1956,26 @@
 			account(2)
 		));
 
-		// do approve
+		// Sself-approve account 1 for NFT 1
 		assert_ok!(TemplateModule::approve(
 			origin1.clone(),
 			account(1),
-			1,
-			1,
-			5
+			CollectionId(1),
+			TokenId(1),
+			1
 		));
-		assert_eq!(TemplateModule::approved(1, (1, 1, 1)), 5);
+		assert_eq!(
+			<pallet_nonfungible::Allowance<Test>>::get((CollectionId(1), TokenId(1))).unwrap(),
+			account(1)
+		);
 
+		// Transfer from 1 to 2
 		assert_ok!(TemplateModule::transfer_from(
 			origin1,
 			account(1),
 			account(2),
-			1,
-			1,
+			CollectionId(1),
+			TokenId(1),
 			1
 		));
 	});
@@ -1497,7 +1985,7 @@
 #[test]
 fn allow_list_test_9() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 		let origin1 = Origin::signed(1);
 
 		assert_ok!(TemplateModule::set_public_access_mode(
@@ -1520,7 +2008,7 @@
 #[test]
 fn allow_list_test_10() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 		let origin2 = Origin::signed(2);
@@ -1555,7 +2043,7 @@
 #[test]
 fn allow_list_test_11() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 		let origin2 = Origin::signed(2);
@@ -1577,8 +2065,14 @@
 		));
 
 		assert_noop!(
-			TemplateModule::create_item(origin2, 1, account(2), default_nft_data().into()),
-			Error::<Test>::PublicMintingNotAllowed
+			TemplateModule::create_item(
+				origin2,
+				CollectionId(1),
+				account(2),
+				default_nft_data().into()
+			)
+			.map_err(|e| e.error),
+			CommonError::<Test>::PublicMintingNotAllowed
 		);
 	});
 }
@@ -1587,7 +2081,7 @@
 #[test]
 fn allow_list_test_12() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 		let origin2 = Origin::signed(2);
@@ -1604,8 +2098,14 @@
 		));
 
 		assert_noop!(
-			TemplateModule::create_item(origin2, 1, account(2), default_nft_data().into()),
-			Error::<Test>::PublicMintingNotAllowed
+			TemplateModule::create_item(
+				origin2,
+				CollectionId(1),
+				account(2),
+				default_nft_data().into()
+			)
+			.map_err(|e| e.error),
+			CommonError::<Test>::PublicMintingNotAllowed
 		);
 	});
 }
@@ -1614,7 +2114,7 @@
 #[test]
 fn allow_list_test_13() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 
@@ -1638,7 +2138,7 @@
 #[test]
 fn allow_list_test_14() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 		let origin2 = Origin::signed(2);
@@ -1662,7 +2162,7 @@
 
 		assert_ok!(TemplateModule::create_item(
 			origin2,
-			1,
+			collection_id,
 			account(2),
 			default_nft_data().into()
 		));
@@ -1673,7 +2173,7 @@
 #[test]
 fn allow_list_test_15() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 		let origin2 = Origin::signed(2);
@@ -1690,8 +2190,14 @@
 		));
 
 		assert_noop!(
-			TemplateModule::create_item(origin2, 1, account(2), default_nft_data().into()),
-			Error::<Test>::AddresNotInAllowList
+			TemplateModule::create_item(
+				origin2,
+				collection_id,
+				account(2),
+				default_nft_data().into()
+			)
+			.map_err(|e| e.error),
+			CommonError::<Test>::AddressNotInAllowlist
 		);
 	});
 }
@@ -1700,7 +2206,7 @@
 #[test]
 fn allow_list_test_16() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 		let origin2 = Origin::signed(2);
@@ -1723,7 +2229,7 @@
 
 		assert_ok!(TemplateModule::create_item(
 			origin2,
-			1,
+			collection_id,
 			account(2),
 			default_nft_data().into()
 		));
@@ -1734,18 +2240,27 @@
 #[test]
 fn total_number_collections_bound() {
 	new_test_ext().execute_with(|| {
-		create_test_collection(&CollectionMode::NFT, 1);
+		create_test_collection(&CollectionMode::NFT, CollectionId(1));
 	});
 }
 
-// Total number of collections. Negotive test
 #[test]
+fn create_max_collections() {
+	new_test_ext().execute_with(|| {
+		for i in 1..=COLLECTION_NUMBER_LIMIT {
+			create_test_collection(&CollectionMode::NFT, CollectionId(i));
+		}
+	});
+}
+
+// Total number of collections. Negative test
+#[test]
 fn total_number_collections_bound_neg() {
 	new_test_ext().execute_with(|| {
 		let origin1 = Origin::signed(1);
 
-		for i in 0..COLLECTION_NUMBER_LIMIT {
-			create_test_collection(&CollectionMode::NFT, i + 1);
+		for i in 1..=COLLECTION_NUMBER_LIMIT {
+			create_test_collection(&CollectionMode::NFT, CollectionId(i));
 		}
 
 		let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
@@ -1761,7 +2276,7 @@
 				token_prefix1,
 				CollectionMode::NFT
 			),
-			Error::<Test>::TotalCollectionsLimitExceeded
+			CommonError::<Test>::TotalCollectionsLimitExceeded
 		);
 	});
 }
@@ -1770,7 +2285,7 @@
 #[test]
 fn owned_tokens_bound() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let data = default_nft_data();
 		create_test_item(collection_id, &data.clone().into());
@@ -1782,19 +2297,20 @@
 #[test]
 fn owned_tokens_bound_neg() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 
-		for _ in 0..ACCOUNT_TOKEN_OWNERSHIP_LIMIT {
+		for _ in 1..=MAX_TOKEN_OWNERSHIP {
 			let data = default_nft_data();
 			create_test_item(collection_id, &data.clone().into());
 		}
 
 		let data = default_nft_data();
 		assert_noop!(
-			TemplateModule::create_item(origin1, 1, account(1), data.into()),
-			Error::<Test>::AccountTokenLimitExceeded
+			TemplateModule::create_item(origin1, CollectionId(1), account(1), data.into())
+				.map_err(|e| e.error),
+			CommonError::<Test>::AccountTokenLimitExceeded
 		);
 	});
 }
@@ -1803,7 +2319,7 @@
 #[test]
 fn collection_admins_bound() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 
@@ -1824,7 +2340,7 @@
 #[test]
 fn collection_admins_bound_neg() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 
@@ -1832,16 +2348,16 @@
 			assert_ok!(TemplateModule::add_collection_admin(
 				origin1.clone(),
 				collection_id,
-				account(2 + i)
+				account((2 + i).into())
 			));
 		}
 		assert_noop!(
 			TemplateModule::add_collection_admin(
 				origin1,
 				collection_id,
-				account(3 + COLLECTION_ADMINS_LIMIT)
+				account((3 + COLLECTION_ADMINS_LIMIT).into())
 			),
-			Error::<Test>::CollectionAdminsLimitExceeded
+			CommonError::<Test>::CollectionAdminCountExceeded
 		);
 	});
 }
@@ -1850,7 +2366,7 @@
 #[test]
 fn set_const_on_chain_schema() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 		assert_ok!(TemplateModule::set_const_on_chain_schema(
@@ -1860,13 +2376,13 @@
 		));
 
 		assert_eq!(
-			TemplateModule::collection_id(collection_id)
+			<pallet_common::CollectionById<Test>>::get(collection_id)
 				.unwrap()
 				.const_on_chain_schema,
 			b"test const on chain schema".to_vec()
 		);
 		assert_eq!(
-			TemplateModule::collection_id(collection_id)
+			<pallet_common::CollectionById<Test>>::get(collection_id)
 				.unwrap()
 				.variable_on_chain_schema,
 			b"".to_vec()
@@ -1877,7 +2393,7 @@
 #[test]
 fn set_variable_on_chain_schema() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 		assert_ok!(TemplateModule::set_variable_on_chain_schema(
@@ -1887,13 +2403,13 @@
 		));
 
 		assert_eq!(
-			TemplateModule::collection_id(collection_id)
+			<pallet_common::CollectionById<Test>>::get(collection_id)
 				.unwrap()
 				.const_on_chain_schema,
 			b"".to_vec()
 		);
 		assert_eq!(
-			TemplateModule::collection_id(collection_id)
+			<pallet_common::CollectionById<Test>>::get(collection_id)
 				.unwrap()
 				.variable_on_chain_schema,
 			b"test variable on chain schema".to_vec()
@@ -1904,23 +2420,23 @@
 #[test]
 fn set_variable_meta_data_on_nft_token_stores_variable_meta_data() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 
 		let data = default_nft_data();
-		create_test_item(1, &data.into());
+		create_test_item(CollectionId(1), &data.into());
 
 		let variable_data = b"test data".to_vec();
 		assert_ok!(TemplateModule::set_variable_meta_data(
 			origin1,
 			collection_id,
-			1,
+			TokenId(1),
 			variable_data.clone()
 		));
 
 		assert_eq!(
-			TemplateModule::nft_item_id(collection_id, 1)
+			<pallet_nonfungible::TokenData<Test>>::get((collection_id, 1))
 				.unwrap()
 				.variable_data,
 			variable_data
@@ -1931,25 +2447,23 @@
 #[test]
 fn set_variable_meta_data_on_re_fungible_token_stores_variable_meta_data() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);
+		let collection_id = create_test_collection(&CollectionMode::ReFungible, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 
 		let data = default_re_fungible_data();
-		create_test_item(1, &data.into());
+		create_test_item(collection_id, &data.into());
 
 		let variable_data = b"test data".to_vec();
 		assert_ok!(TemplateModule::set_variable_meta_data(
 			origin1,
 			collection_id,
-			1,
+			TokenId(1),
 			variable_data.clone()
 		));
 
 		assert_eq!(
-			TemplateModule::refungible_item_id(collection_id, 1)
-				.unwrap()
-				.variable_data,
+			<pallet_refungible::TokenData<Test>>::get((collection_id, TokenId(1))).variable_data,
 			variable_data
 		);
 	});
@@ -1958,17 +2472,23 @@
 #[test]
 fn set_variable_meta_data_on_fungible_token_fails() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);
+		let collection_id = create_test_collection(&CollectionMode::Fungible(3), CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 
 		let data = default_fungible_data();
-		create_test_item(1, &data.into());
+		create_test_item(collection_id, &data.into());
 
 		let variable_data = b"test data".to_vec();
 		assert_noop!(
-			TemplateModule::set_variable_meta_data(origin1, collection_id, 1, variable_data),
-			Error::<Test>::CantStoreMetadataInFungibleTokens
+			TemplateModule::set_variable_meta_data(
+				origin1,
+				collection_id,
+				TokenId(0),
+				variable_data
+			)
+			.map_err(|e| e.error),
+			<pallet_fungible::Error<Test>>::FungibleItemsDontHaveData
 		);
 	});
 }
@@ -1976,17 +2496,23 @@
 #[test]
 fn set_variable_meta_data_on_nft_token_fails_for_big_data() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 
 		let data = default_nft_data();
-		create_test_item(1, &data.into());
+		create_test_item(collection_id, &data.into());
 
 		let variable_data = b"test set_variable_meta_data method, bigger than limits.".to_vec();
 		assert_noop!(
-			TemplateModule::set_variable_meta_data(origin1, collection_id, 1, variable_data),
-			Error::<Test>::TokenVariableDataLimitExceeded
+			TemplateModule::set_variable_meta_data(
+				origin1,
+				collection_id,
+				TokenId(1),
+				variable_data
+			)
+			.map_err(|e| e.error),
+			CommonError::<Test>::TokenVariableDataLimitExceeded
 		);
 	});
 }
@@ -1994,17 +2520,23 @@
 #[test]
 fn set_variable_meta_data_on_re_fungible_token_fails_for_big_data() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);
+		let collection_id = create_test_collection(&CollectionMode::ReFungible, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 
 		let data = default_re_fungible_data();
-		create_test_item(1, &data.into());
+		create_test_item(collection_id, &data.into());
 
 		let variable_data = b"test set_variable_meta_data method, bigger than limits.".to_vec();
 		assert_noop!(
-			TemplateModule::set_variable_meta_data(origin1, collection_id, 1, variable_data),
-			Error::<Test>::TokenVariableDataLimitExceeded
+			TemplateModule::set_variable_meta_data(
+				origin1,
+				collection_id,
+				TokenId(1),
+				variable_data
+			)
+			.map_err(|e| e.error),
+			CommonError::<Test>::TokenVariableDataLimitExceeded
 		);
 	});
 }
@@ -2014,12 +2546,12 @@
 	new_test_ext().execute_with(|| {
 		//default_limits();
 
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 
 		let data = default_nft_data();
-		create_test_item(1, &data.into());
+		create_test_item(collection_id, &data.into());
 
 		assert_ok!(TemplateModule::set_meta_update_permission_flag(
 			origin1.clone(),
@@ -2031,12 +2563,12 @@
 		assert_ok!(TemplateModule::set_variable_meta_data(
 			origin1,
 			collection_id,
-			1,
+			TokenId(1),
 			variable_data.clone()
 		));
 
 		assert_eq!(
-			TemplateModule::nft_item_id(collection_id, 1)
+			<pallet_nonfungible::TokenData<Test>>::get((collection_id, TokenId(1)))
 				.unwrap()
 				.variable_data,
 			variable_data
@@ -2047,7 +2579,8 @@
 #[test]
 fn set_variable_meta_data_on_nft_with_item_owner_permission_flag_neg() {
 	new_test_ext().execute_with(|| {
-		let collection_id = create_test_collection_for_owner(&CollectionMode::NFT, 1, 1);
+		let collection_id =
+			create_test_collection_for_owner(&CollectionMode::NFT, 1, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 
@@ -2063,7 +2596,7 @@
 		));
 
 		let data = default_nft_data();
-		create_test_item(1, &data.into());
+		create_test_item(collection_id, &data.into());
 
 		assert_ok!(TemplateModule::set_meta_update_permission_flag(
 			origin1.clone(),
@@ -2076,10 +2609,11 @@
 			TemplateModule::set_variable_meta_data(
 				origin1,
 				collection_id,
-				1,
+				TokenId(1),
 				variable_data.clone()
-			),
-			Error::<Test>::TokenVariableDataLimitExceeded
+			)
+			.map_err(|e| e.error),
+			CommonError::<Test>::TokenVariableDataLimitExceeded
 		);
 	})
 }
@@ -2089,23 +2623,50 @@
 	new_test_ext().execute_with(|| {
 		let origin1 = Origin::signed(1);
 
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
-		assert_ok!(TemplateModule::set_transfers_enabled_flag(origin1, 1, true));
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
+		assert_ok!(TemplateModule::set_transfers_enabled_flag(
+			origin1,
+			collection_id,
+			true
+		));
 
 		let data = default_nft_data();
 		create_test_item(collection_id, &data.into());
-		assert_eq!(TemplateModule::balance_count(1, 1), 1);
-		assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+		assert_eq!(
+			<pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+			1
+		);
+		assert_eq!(
+			<pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+			true
+		);
 
 		let origin1 = Origin::signed(1);
 
 		// default scenario
-		assert_ok!(TemplateModule::transfer(origin1, account(2), 1, 1, 1000));
-		assert_eq!(TemplateModule::nft_item_id(1, 1).unwrap().owner, account(2));
-		assert_eq!(TemplateModule::balance_count(1, 1), 0);
-		assert_eq!(TemplateModule::balance_count(1, 2), 1);
-
-		assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
+		assert_ok!(TemplateModule::transfer(
+			origin1,
+			account(2),
+			collection_id,
+			TokenId(1),
+			1
+		));
+		assert_eq!(
+			<pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+			false
+		);
+		assert_eq!(
+			<pallet_nonfungible::Owned<Test>>::get((collection_id, account(2), TokenId(1))),
+			true
+		);
+		assert_eq!(
+			<pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+			0
+		);
+		assert_eq!(
+			<pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(2))),
+			1
+		);
 	});
 }
 
@@ -2114,7 +2675,8 @@
 	new_test_ext().execute_with(|| {
 		// default_limits();
 
-		let collection_id = create_test_collection_for_owner(&CollectionMode::NFT, 2, 1);
+		let collection_id =
+			create_test_collection_for_owner(&CollectionMode::NFT, 2, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 		let origin2 = Origin::signed(2);
@@ -2137,7 +2699,7 @@
 		));
 
 		let data = default_nft_data();
-		create_test_item(1, &data.into());
+		create_test_item(collection_id, &data.into());
 
 		assert_ok!(TemplateModule::set_meta_update_permission_flag(
 			origin2.clone(),
@@ -2149,12 +2711,12 @@
 		assert_ok!(TemplateModule::set_variable_meta_data(
 			origin1,
 			collection_id,
-			1,
+			TokenId(1),
 			variable_data.clone()
 		));
 
 		assert_eq!(
-			TemplateModule::nft_item_id(collection_id, 1)
+			<pallet_nonfungible::TokenData<Test>>::get((collection_id, 1))
 				.unwrap()
 				.variable_data,
 			variable_data
@@ -2167,7 +2729,8 @@
 	new_test_ext().execute_with(|| {
 		// default_limits();
 
-		let collection_id = create_test_collection_for_owner(&CollectionMode::NFT, 2, 1);
+		let collection_id =
+			create_test_collection_for_owner(&CollectionMode::NFT, 2, CollectionId(1));
 
 		let origin1 = Origin::signed(1);
 		let origin2 = Origin::signed(2);
@@ -2184,7 +2747,7 @@
 		));
 
 		let data = default_nft_data();
-		create_test_item(1, &data.into());
+		create_test_item(collection_id, &data.into());
 
 		assert_ok!(TemplateModule::set_meta_update_permission_flag(
 			origin2.clone(),
@@ -2197,10 +2760,11 @@
 			TemplateModule::set_variable_meta_data(
 				origin1,
 				collection_id,
-				1,
+				TokenId(1),
 				variable_data.clone()
-			),
-			Error::<Test>::NoPermission
+			)
+			.map_err(|e| e.error),
+			CommonError::<Test>::NoPermission
 		);
 	});
 }
@@ -2210,7 +2774,8 @@
 	new_test_ext().execute_with(|| {
 		// default_limits();
 
-		let collection_id = create_test_collection_for_owner(&CollectionMode::NFT, 2, 1);
+		let collection_id =
+			create_test_collection_for_owner(&CollectionMode::NFT, 2, CollectionId(1));
 
 		let origin2 = Origin::signed(2);
 
@@ -2225,7 +2790,7 @@
 				collection_id,
 				MetaUpdatePermission::Admin
 			),
-			Error::<Test>::MetadataFlagFrozen
+			CommonError::<Test>::MetadataFlagFrozen
 		);
 	});
 }
@@ -2235,11 +2800,12 @@
 	new_test_ext().execute_with(|| {
 		// default_limits();
 
-		let collection_id = create_test_collection_for_owner(&CollectionMode::NFT, 1, 1);
+		let collection_id =
+			create_test_collection_for_owner(&CollectionMode::NFT, 1, CollectionId(1));
 		let origin1 = Origin::signed(1);
 
 		let data = default_nft_data();
-		create_test_item(1, &data.into());
+		create_test_item(collection_id, &data.into());
 
 		assert_ok!(TemplateModule::set_meta_update_permission_flag(
 			origin1.clone(),
@@ -2252,10 +2818,11 @@
 			TemplateModule::set_variable_meta_data(
 				origin1.clone(),
 				collection_id,
-				1,
+				TokenId(1),
 				variable_data.clone()
-			),
-			Error::<Test>::MetadataUpdateDenied
+			)
+			.map_err(|e| e.error),
+			CommonError::<Test>::NoPermission
 		);
 	});
 }
@@ -2265,27 +2832,47 @@
 	new_test_ext().execute_with(|| {
 		let origin1 = Origin::signed(1);
 
-		let collection_id = create_test_collection(&CollectionMode::NFT, 1);
+		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 		assert_ok!(TemplateModule::set_transfers_enabled_flag(
-			origin1, 1, false
+			origin1,
+			collection_id,
+			false
 		));
 
 		let data = default_nft_data();
 		create_test_item(collection_id, &data.into());
-		assert_eq!(TemplateModule::balance_count(1, 1), 1);
-		assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+		assert_eq!(
+			<pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+			1
+		);
+		assert_eq!(
+			<pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+			true
+		);
 
 		let origin1 = Origin::signed(1);
 
 		// default scenario
 		assert_noop!(
-			TemplateModule::transfer(origin1, account(2), 1, 1, 1000),
-			Error::<Test>::TransferNotAllowed
+			TemplateModule::transfer(origin1, account(2), CollectionId(1), TokenId(1), 1)
+				.map_err(|e| e.error),
+			CommonError::<Test>::TransferNotAllowed
+		);
+		assert_eq!(
+			<pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(1))),
+			1
 		);
-		assert_eq!(TemplateModule::nft_item_id(1, 1).unwrap().owner, account(1));
-		assert_eq!(TemplateModule::balance_count(1, 1), 1);
-		assert_eq!(TemplateModule::balance_count(1, 2), 0);
-
-		assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+		assert_eq!(
+			<pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(2))),
+			0
+		);
+		assert_eq!(
+			<pallet_nonfungible::Owned<Test>>::get((collection_id, account(1), TokenId(1))),
+			true
+		);
+		assert_eq!(
+			<pallet_nonfungible::Owned<Test>>::get((collection_id, account(2), TokenId(1))),
+			false
+		);
 	});
 }
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -29,10 +29,14 @@
 pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;
 pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;
 pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;
-pub const MAX_TOKEN_OWNERSHIP: u32 = 10_000_000;
 
+pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {
+	10_000_000
+} else {
+	10
+};
 pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {
-	100000
+	100_000
 } else {
 	10
 };
@@ -44,7 +48,7 @@
 pub const COLLECTION_ADMINS_LIMIT: u32 = 5;
 pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;
 pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {
-	1000000
+	1_000_000
 } else {
 	10
 };