git.delta.rocks / unique-network / refs/commits / 833ab943fbb5

difftreelog

feat merge native erc20 adapter

Yaroslav Bolyukin2023-05-30parents: #103f351 #c43c309.patch.diff
in: master

78 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5871,6 +5871,7 @@
  "pallet-aura",
  "pallet-authorship",
  "pallet-balances",
+ "pallet-balances-adapter",
  "pallet-base-fee",
  "pallet-collator-selection",
  "pallet-common",
@@ -6252,6 +6253,27 @@
 ]
 
 [[package]]
+name = "pallet-balances-adapter"
+version = "0.1.0"
+dependencies = [
+ "evm-coder",
+ "frame-support",
+ "frame-system",
+ "pallet-balances",
+ "pallet-common",
+ "pallet-evm",
+ "pallet-evm-coder-substrate",
+ "pallet-evm-transaction-payment",
+ "pallet-structure",
+ "parity-scale-codec",
+ "scale-info",
+ "sp-core",
+ "sp-runtime",
+ "sp-std",
+ "up-data-structs",
+]
+
+[[package]]
 name = "pallet-base-fee"
 version = "1.0.0"
 source = "git+https://github.com/uniquenetwork/unique-frontier?branch=unique-polkadot-v0.9.42#75ad5b9a49e1942553c4068228f1546ffb1f7246"
@@ -6947,6 +6969,7 @@
  "frame-benchmarking",
  "frame-support",
  "frame-system",
+ "pallet-balances",
  "pallet-common",
  "pallet-evm",
  "pallet-evm-coder-substrate",
@@ -7411,6 +7434,7 @@
  "frame-benchmarking",
  "frame-support",
  "frame-system",
+ "pallet-balances-adapter",
  "pallet-common",
  "pallet-evm",
  "pallet-evm-coder-substrate",
@@ -9350,6 +9374,7 @@
  "pallet-aura",
  "pallet-authorship",
  "pallet-balances",
+ "pallet-balances-adapter",
  "pallet-base-fee",
  "pallet-collator-selection",
  "pallet-common",
@@ -12902,8 +12927,8 @@
  "frame-support",
  "frame-system",
  "pallet-balances",
+ "pallet-balances-adapter",
  "pallet-common",
- "pallet-configuration",
  "pallet-ethereum",
  "pallet-evm",
  "pallet-evm-coder-substrate",
@@ -12914,7 +12939,6 @@
  "pallet-timestamp",
  "pallet-transaction-payment",
  "pallet-unique",
- "pallet-xcm",
  "parity-scale-codec",
  "scale-info",
  "sp-core",
@@ -13767,6 +13791,7 @@
  "pallet-aura",
  "pallet-authorship",
  "pallet-balances",
+ "pallet-balances-adapter",
  "pallet-base-fee",
  "pallet-collator-selection",
  "pallet-common",
modifiedCargo.tomldiffbeforeafterboth
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -19,9 +19,9 @@
 panic = "unwind"
 
 [profile.production]
+codegen-units = 1
 inherits = "release"
 lto = true
-codegen-units = 1
 opt-level = 3
 
 [workspace.dependencies]
@@ -29,6 +29,7 @@
 app-promotion-rpc = { path = "primitives/app_promotion_rpc", default-features = false }
 evm-coder = { git = "https://github.com/uniquenetwork/evm-coder", tag = "v0.3.1", default-features = false }
 pallet-app-promotion = { path = "pallets/app-promotion", default-features = false }
+pallet-balances-adapter = { default-features = false, path = "pallets/balances-adapter" }
 pallet-charge-transaction = { package = "pallet-template-transaction-payment", default-features = false, git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.42" }
 pallet-collator-selection = { default-features = false, path = "pallets/collator-selection" }
 pallet-common = { default-features = false, path = "pallets/common" }
@@ -85,15 +86,15 @@
 cumulus-client-consensus-common = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
 cumulus-client-network = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
 cumulus-client-service = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
-cumulus-pallet-aura-ext = { default-features = false , git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
-cumulus-pallet-dmp-queue = { default-features = false , git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
-cumulus-pallet-parachain-system = { default-features = false , git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
-cumulus-pallet-xcm = { default-features = false , git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
-cumulus-pallet-xcmp-queue = { default-features = false , git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
-cumulus-primitives-core = { default-features = false , git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
+cumulus-pallet-aura-ext = { default-features = false, git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
+cumulus-pallet-dmp-queue = { default-features = false, git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
+cumulus-pallet-parachain-system = { default-features = false, git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
+cumulus-pallet-xcm = { default-features = false, git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
+cumulus-pallet-xcmp-queue = { default-features = false, git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
+cumulus-primitives-core = { default-features = false, git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
 cumulus-primitives-parachain-inherent = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
-cumulus-primitives-timestamp = { default-features = false , git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
-cumulus-primitives-utility = { default-features = false , git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
+cumulus-primitives-timestamp = { default-features = false, git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
+cumulus-primitives-utility = { default-features = false, git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
 cumulus-relay-chain-inprocess-interface = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
 cumulus-relay-chain-interface = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
 cumulus-relay-chain-minimal-node = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.42" }
@@ -123,9 +124,9 @@
 sc-cli = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42" }
 sc-client-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42" }
 sc-consensus = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42" }
+sc-consensus-grandpa = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42" }
 sc-consensus-manual-seal = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42" }
 sc-executor = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42" }
-sc-consensus-grandpa = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42" }
 sc-network = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42" }
 sc-network-sync = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42" }
 sc-rpc = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42" }
@@ -177,11 +178,11 @@
 try-runtime-cli = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42" }
 
 # ORML
-orml-tokens = { default-features = false , git = "https://github.com/uniquenetwork/open-runtime-module-library", branch = "polkadot-v0.9.42" }
-orml-traits = { default-features = false , git = "https://github.com/uniquenetwork/open-runtime-module-library", branch = "polkadot-v0.9.42" }
-orml-vesting = { default-features = false , git = "https://github.com/uniquenetwork/open-runtime-module-library", branch = "polkadot-v0.9.42" }
-orml-xtokens = { default-features = false , git = "https://github.com/uniquenetwork/open-runtime-module-library", branch = "polkadot-v0.9.42" }
-orml-xcm-support = { default-features = false , git = "https://github.com/uniquenetwork/open-runtime-module-library", branch = "polkadot-v0.9.42" }
+orml-tokens = { default-features = false, git = "https://github.com/uniquenetwork/open-runtime-module-library", branch = "polkadot-v0.9.42" }
+orml-traits = { default-features = false, git = "https://github.com/uniquenetwork/open-runtime-module-library", branch = "polkadot-v0.9.42" }
+orml-vesting = { default-features = false, git = "https://github.com/uniquenetwork/open-runtime-module-library", branch = "polkadot-v0.9.42" }
+orml-xcm-support = { default-features = false, git = "https://github.com/uniquenetwork/open-runtime-module-library", branch = "polkadot-v0.9.42" }
+orml-xtokens = { default-features = false, git = "https://github.com/uniquenetwork/open-runtime-module-library", branch = "polkadot-v0.9.42" }
 
 # Other
 derivative = { version = "2.2.0", features = ["use_core"] }
@@ -194,4 +195,3 @@
 num_enum = { version = "0.5.3", default-features = false }
 serde = { default-features = false, features = ['derive'], version = "1.0.136" }
 smallvec = "1.6.1"
-
modifiedMakefilediffbeforeafterboth
--- a/Makefile
+++ b/Makefile
@@ -6,6 +6,9 @@
 	@echo "  bench-evm-migration"
 	@echo "  bench-unique"
 
+NATIVE_FUNGIBLE_EVM_STUBS=./pallets/balances-adapter/src/stubs
+NATIVE_FUNGIBLE_EVM_ABI=./tests/src/eth/abi/nativeFungible.json
+
 FUNGIBLE_EVM_STUBS=./pallets/fungible/src/stubs
 FUNGIBLE_EVM_ABI=./tests/src/eth/abi/fungible.json
 
@@ -27,6 +30,10 @@
 .PHONY: regenerate_solidity
 regenerate_solidity: UniqueFungible.sol UniqueNFT.sol UniqueRefungible.sol UniqueRefungibleToken.sol ContractHelpers.sol CollectionHelpers.sol
 
+UniqueNativeFungible.sol:
+	PACKAGE=pallet-balances-adapter NAME=erc::gen_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
+	PACKAGE=pallet-balances-adapter NAME=erc::gen_impl OUTPUT=$(NATIVE_FUNGIBLE_EVM_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
+	
 UniqueFungible.sol:
 	PACKAGE=pallet-fungible NAME=erc::gen_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
 	PACKAGE=pallet-fungible NAME=erc::gen_impl OUTPUT=$(FUNGIBLE_EVM_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
@@ -51,6 +58,10 @@
 	PACKAGE=pallet-unique NAME=eth::collection_helper_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
 	PACKAGE=pallet-unique NAME=eth::collection_helper_impl OUTPUT=$(COLLECTION_HELPER_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
 
+UniqueNativeFungible: UniqueNativeFungible.sol
+	INPUT=$(NATIVE_FUNGIBLE_EVM_STUBS)/$< OUTPUT=$(NATIVE_FUNGIBLE_EVM_STUBS)/UniqueNativeFungible.raw ./.maintain/scripts/compile_stub.sh
+	INPUT=$(NATIVE_FUNGIBLE_EVM_STUBS)/$< OUTPUT=$(NATIVE_FUNGIBLE_EVM_ABI) ./.maintain/scripts/generate_abi.sh
+	
 UniqueFungible: UniqueFungible.sol
 	INPUT=$(FUNGIBLE_EVM_STUBS)/$< OUTPUT=$(FUNGIBLE_EVM_STUBS)/UniqueFungible.raw ./.maintain/scripts/compile_stub.sh
 	INPUT=$(FUNGIBLE_EVM_STUBS)/$< OUTPUT=$(FUNGIBLE_EVM_ABI) ./.maintain/scripts/generate_abi.sh
modifiednode/cli/src/chain_spec.rsdiffbeforeafterboth
--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -267,7 +267,7 @@
 pub fn development_config() -> DefaultChainSpec {
 	let mut properties = Map::new();
 	properties.insert("tokenSymbol".into(), default_runtime::TOKEN_SYMBOL.into());
-	properties.insert("tokenDecimals".into(), 18.into());
+	properties.insert("tokenDecimals".into(), default_runtime::DECIMALS.into());
 	properties.insert(
 		"ss58Format".into(),
 		default_runtime::SS58Prefix::get().into(),
@@ -341,7 +341,7 @@
 pub fn local_testnet_config() -> DefaultChainSpec {
 	let mut properties = Map::new();
 	properties.insert("tokenSymbol".into(), default_runtime::TOKEN_SYMBOL.into());
-	properties.insert("tokenDecimals".into(), 18.into());
+	properties.insert("tokenDecimals".into(), default_runtime::DECIMALS.into());
 	properties.insert(
 		"ss58Format".into(),
 		default_runtime::SS58Prefix::get().into(),
addedpallets/balances-adapter/Cargo.tomldiffbeforeafterboth
--- /dev/null
+++ b/pallets/balances-adapter/Cargo.toml
@@ -0,0 +1,45 @@
+[package]
+edition = "2021"
+license = "GPLv3"
+name = "pallet-balances-adapter"
+version = "0.1.0"
+
+[dependencies]
+# Substrate
+frame-support = { workspace = true }
+frame-system = { workspace = true }
+pallet-balances = { workspace = true }
+pallet-structure = { workspace = true }
+sp-core = { workspace = true }
+sp-runtime = { workspace = true }
+sp-std = { workspace = true }
+
+#Parity
+codec = { workspace = true, package = "parity-scale-codec" }
+scale-info = { workspace = true }
+
+# Unique
+evm-coder = { workspace = true }
+pallet-evm = { workspace = true }
+
+#Local
+pallet-common = { workspace = true }
+pallet-evm-coder-substrate = { workspace = true }
+pallet-evm-transaction-payment = { workspace = true }
+up-data-structs = { workspace = true, features = ['serde1'] }
+
+[features]
+default = ["std"]
+std = [
+	"evm-coder/std",
+	"frame-support/std",
+	"frame-system/std",
+	"pallet-balances/std",
+	"pallet-common/std",
+	"pallet-evm-coder-substrate/std",
+	"pallet-evm/std",
+	"sp-core/std",
+	"sp-std/std",
+]
+stubgen = ["evm-coder/stubgen", "pallet-common/stubgen"]
+try-runtime = ["frame-support/try-runtime"]
addedpallets/balances-adapter/src/common.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/balances-adapter/src/common.rs
@@ -0,0 +1,359 @@
+use alloc::{vec, vec::Vec};
+use core::marker::PhantomData;
+use crate::{Config, NativeFungibleHandle, Pallet};
+use frame_support::{fail, weights::Weight};
+use pallet_balances::{weights::SubstrateWeight as BalancesWeight, WeightInfo};
+use pallet_common::{CommonCollectionOperations, CommonWeightInfo};
+use up_data_structs::TokenId;
+
+pub struct CommonWeights<T: Config>(PhantomData<T>);
+
+// All implementations with `Weight::default` used in methods that return error `UnsupportedOperation`.
+impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {
+	fn create_multiple_items(_amount: &[up_data_structs::CreateItemData]) -> Weight {
+		Weight::default()
+	}
+
+	fn create_multiple_items_ex(
+		_cost: &up_data_structs::CreateItemExData<T::CrossAccountId>,
+	) -> Weight {
+		Weight::default()
+	}
+
+	fn burn_item() -> Weight {
+		Weight::default()
+	}
+
+	fn set_collection_properties(_amount: u32) -> Weight {
+		Weight::default()
+	}
+
+	fn delete_collection_properties(_amount: u32) -> Weight {
+		Weight::default()
+	}
+
+	fn set_token_properties(_amount: u32) -> Weight {
+		Weight::default()
+	}
+
+	fn delete_token_properties(_amount: u32) -> Weight {
+		Weight::default()
+	}
+
+	fn set_token_property_permissions(_amount: u32) -> Weight {
+		Weight::default()
+	}
+
+	fn transfer() -> Weight {
+		<BalancesWeight<T> as WeightInfo>::transfer_allow_death()
+	}
+
+	fn approve() -> Weight {
+		Weight::default()
+	}
+
+	fn approve_from() -> Weight {
+		Weight::default()
+	}
+
+	fn transfer_from() -> Weight {
+		<BalancesWeight<T> as WeightInfo>::transfer_allow_death()
+	}
+
+	fn burn_from() -> Weight {
+		Weight::default()
+	}
+
+	fn burn_recursively_self_raw() -> Weight {
+		Weight::default()
+	}
+
+	fn burn_recursively_breadth_raw(_amount: u32) -> Weight {
+		Weight::default()
+	}
+
+	fn token_owner() -> Weight {
+		Weight::default()
+	}
+
+	fn set_allowance_for_all() -> Weight {
+		Weight::default()
+	}
+
+	fn force_repair_item() -> Weight {
+		Weight::default()
+	}
+}
+
+/// Implementation of `CommonCollectionOperations` for `FungibleHandle`. It wraps FungibleHandle Pallet
+/// methods and adds weight info.
+impl<T: Config> CommonCollectionOperations<T> for NativeFungibleHandle<T> {
+	fn create_item(
+		&self,
+		_sender: <T>::CrossAccountId,
+		_to: <T>::CrossAccountId,
+		_data: up_data_structs::CreateItemData,
+		_nesting_budget: &dyn up_data_structs::budget::Budget,
+	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
+		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+	}
+
+	fn create_multiple_items(
+		&self,
+		_sender: <T>::CrossAccountId,
+		_to: <T>::CrossAccountId,
+		_data: Vec<up_data_structs::CreateItemData>,
+		_nesting_budget: &dyn up_data_structs::budget::Budget,
+	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
+		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+	}
+
+	fn create_multiple_items_ex(
+		&self,
+		_sender: <T>::CrossAccountId,
+		_data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,
+		_nesting_budget: &dyn up_data_structs::budget::Budget,
+	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
+		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+	}
+
+	fn burn_item(
+		&self,
+		_sender: <T>::CrossAccountId,
+		_token: TokenId,
+		_amount: u128,
+	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
+		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+	}
+
+	fn burn_item_recursively(
+		&self,
+		_sender: <T>::CrossAccountId,
+		_token: TokenId,
+		_self_budget: &dyn up_data_structs::budget::Budget,
+		_breadth_budget: &dyn up_data_structs::budget::Budget,
+	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
+		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+	}
+
+	fn set_collection_properties(
+		&self,
+		_sender: <T>::CrossAccountId,
+		_properties: Vec<up_data_structs::Property>,
+	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
+		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+	}
+
+	fn delete_collection_properties(
+		&self,
+		_sender: &<T>::CrossAccountId,
+		_property_keys: Vec<up_data_structs::PropertyKey>,
+	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
+		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+	}
+
+	fn set_token_properties(
+		&self,
+		_sender: <T>::CrossAccountId,
+		_token_id: TokenId,
+		_properties: Vec<up_data_structs::Property>,
+		_budget: &dyn up_data_structs::budget::Budget,
+	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
+		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+	}
+
+	fn delete_token_properties(
+		&self,
+		_sender: <T>::CrossAccountId,
+		_token_id: TokenId,
+		_property_keys: Vec<up_data_structs::PropertyKey>,
+		_budget: &dyn up_data_structs::budget::Budget,
+	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
+		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+	}
+
+	fn set_token_property_permissions(
+		&self,
+		_sender: &<T>::CrossAccountId,
+		_property_permissions: Vec<up_data_structs::PropertyKeyPermission>,
+	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
+		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+	}
+
+	fn transfer(
+		&self,
+		sender: <T>::CrossAccountId,
+		to: <T>::CrossAccountId,
+		_token: TokenId,
+		amount: u128,
+		budget: &dyn up_data_structs::budget::Budget,
+	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
+		<Pallet<T>>::transfer(self, &sender, &to, amount, budget)
+	}
+
+	fn approve(
+		&self,
+		_sender: <T>::CrossAccountId,
+		_spender: <T>::CrossAccountId,
+		_token: TokenId,
+		_amount: u128,
+	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
+		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+	}
+
+	fn approve_from(
+		&self,
+		_sender: <T>::CrossAccountId,
+		_from: <T>::CrossAccountId,
+		_to: <T>::CrossAccountId,
+		_token: TokenId,
+		_amount: u128,
+	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
+		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+	}
+
+	fn transfer_from(
+		&self,
+		sender: <T>::CrossAccountId,
+		from: <T>::CrossAccountId,
+		to: <T>::CrossAccountId,
+		_token: TokenId,
+		amount: u128,
+		budget: &dyn up_data_structs::budget::Budget,
+	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
+		<Pallet<T>>::transfer_from(self, &sender, &from, &to, amount, budget)
+	}
+
+	fn burn_from(
+		&self,
+		_sender: <T>::CrossAccountId,
+		_from: <T>::CrossAccountId,
+		_token: TokenId,
+		_amount: u128,
+		_budget: &dyn up_data_structs::budget::Budget,
+	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
+		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+	}
+
+	fn check_nesting(
+		&self,
+		_sender: <T>::CrossAccountId,
+		_from: (up_data_structs::CollectionId, TokenId),
+		_under: TokenId,
+		_budget: &dyn up_data_structs::budget::Budget,
+	) -> frame_support::sp_runtime::DispatchResult {
+		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+	}
+
+	fn nest(&self, _under: TokenId, _to_nest: (up_data_structs::CollectionId, TokenId)) {}
+
+	fn unnest(&self, _under: TokenId, _to_nest: (up_data_structs::CollectionId, TokenId)) {}
+
+	fn account_tokens(&self, account: <T>::CrossAccountId) -> Vec<TokenId> {
+		let balance = <Pallet<T>>::total_balance(&account);
+		if balance != 0 {
+			vec![TokenId::default()]
+		} else {
+			vec![]
+		}
+	}
+
+	fn collection_tokens(&self) -> Vec<TokenId> {
+		vec![TokenId::default()]
+	}
+
+	fn token_exists(&self, token: TokenId) -> bool {
+		token == TokenId::default()
+	}
+
+	fn last_token_id(&self) -> TokenId {
+		TokenId::default()
+	}
+
+	fn token_owner(
+		&self,
+		_token: TokenId,
+	) -> Result<<T>::CrossAccountId, up_data_structs::TokenOwnerError> {
+		Err(up_data_structs::TokenOwnerError::MultipleOwners)
+	}
+
+	fn token_owners(&self, _token: TokenId) -> Vec<<T>::CrossAccountId> {
+		vec![]
+	}
+
+	fn token_property(
+		&self,
+		_token_id: TokenId,
+		_key: &up_data_structs::PropertyKey,
+	) -> Option<up_data_structs::PropertyValue> {
+		None
+	}
+
+	fn token_properties(
+		&self,
+		_token: TokenId,
+		_keys: Option<Vec<up_data_structs::PropertyKey>>,
+	) -> Vec<up_data_structs::Property> {
+		vec![]
+	}
+
+	fn total_supply(&self) -> u32 {
+		1
+	}
+
+	fn account_balance(&self, account: T::CrossAccountId) -> u32 {
+		let balance = <Pallet<T>>::balance_of(&account);
+		(balance != 0).into()
+	}
+
+	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {
+		if token != TokenId::default() {
+			return 0;
+		}
+		<Pallet<T>>::balance_of(&account)
+	}
+
+	fn total_pieces(&self, token: TokenId) -> Option<u128> {
+		if token != TokenId::default() {
+			return None;
+		}
+		Some(<Pallet<T>>::total_issuance())
+	}
+
+	fn allowance(
+		&self,
+		_sender: <T>::CrossAccountId,
+		_spender: <T>::CrossAccountId,
+		_token: TokenId,
+	) -> u128 {
+		0
+	}
+
+	fn refungible_extensions(&self) -> Option<&dyn pallet_common::RefungibleExtensions<T>> {
+		None
+	}
+
+	fn set_allowance_for_all(
+		&self,
+		_owner: <T>::CrossAccountId,
+		_operator: <T>::CrossAccountId,
+		_approve: bool,
+	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
+		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+	}
+
+	fn allowance_for_all(
+		&self,
+		_owner: <T>::CrossAccountId,
+		_operator: <T>::CrossAccountId,
+	) -> bool {
+		false
+	}
+
+	fn repair_item(
+		&self,
+		_token: TokenId,
+	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
+		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+	}
+}
addedpallets/balances-adapter/src/erc.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/balances-adapter/src/erc.rs
@@ -0,0 +1,165 @@
+use crate::{Config, NativeFungibleHandle, Pallet, SelfWeightOf};
+use evm_coder::{abi::AbiType, generate_stubgen, solidity_interface, types::*};
+use pallet_balances::WeightInfo;
+use pallet_common::{
+	erc::{CommonEvmHandler, CrossAccountId, PrecompileHandle, PrecompileResult},
+	eth::CrossAddress,
+};
+use pallet_evm_coder_substrate::{
+	call, dispatch_to_evm,
+	execution::{PreDispatch, Result},
+	frontier_contract, WithRecorder,
+};
+use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
+use sp_core::{U256, Get};
+
+frontier_contract! {
+	macro_rules! NativeFungibleHandle_result {...}
+	impl<T: Config> Contract for NativeFungibleHandle<T> {...}
+}
+
+#[solidity_interface(name = ERC20, enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x942e8b22)]
+impl<T: Config> NativeFungibleHandle<T> {
+	fn allowance(&self, _owner: Address, _spender: Address) -> Result<U256> {
+		Ok(U256::zero())
+	}
+
+	fn approve(&mut self, _caller: Caller, _spender: Address, _amount: U256) -> Result<bool> {
+		Err("Approve not supported".into())
+	}
+
+	fn balance_of(&self, owner: Address) -> Result<U256> {
+		self.consume_store_reads(1)?;
+		let owner = T::CrossAccountId::from_eth(owner);
+		let balance = <Pallet<T>>::balance_of(&owner);
+		Ok(balance.into())
+	}
+
+	fn decimals(&self) -> Result<u8> {
+		Ok(T::Decimals::get())
+	}
+
+	fn name(&self) -> Result<String> {
+		Ok(T::Name::get())
+	}
+
+	fn symbol(&self) -> Result<String> {
+		Ok(T::Symbol::get())
+	}
+
+	fn total_supply(&self) -> Result<U256> {
+		self.consume_store_reads(1)?;
+		Ok(<Pallet<T>>::total_issuance().into())
+	}
+
+	#[weight(<SelfWeightOf<T>>::transfer_allow_death())]
+	fn transfer(&mut self, caller: Caller, to: Address, amount: U256) -> Result<bool> {
+		let caller = T::CrossAccountId::from_eth(caller);
+		let to = T::CrossAccountId::from_eth(to);
+		let amount = amount.try_into().map_err(|_| "amount overflow")?;
+		let budget = self
+			.recorder()
+			.weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+		<Pallet<T>>::transfer(self, &caller, &to, amount, &budget)
+			.map_err(|e| dispatch_to_evm::<T>(e.error))?;
+		Ok(true)
+	}
+
+	#[weight(<SelfWeightOf<T>>::transfer_allow_death())]
+	fn transfer_from(
+		&mut self,
+		caller: Caller,
+		from: Address,
+		to: Address,
+		amount: U256,
+	) -> Result<bool> {
+		let caller = T::CrossAccountId::from_eth(caller);
+		let from = T::CrossAccountId::from_eth(from);
+		let to = T::CrossAccountId::from_eth(to);
+		let amount = amount.try_into().map_err(|_| "amount overflow")?;
+		let budget = self
+			.recorder()
+			.weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+		<Pallet<T>>::transfer_from(self, &caller, &from, &to, amount, &budget)
+			.map_err(|e| dispatch_to_evm::<T>(e.error))?;
+		Ok(true)
+	}
+}
+
+#[solidity_interface(name = ERC20UniqueExtensions, enum(derive(PreDispatch)), enum_attr(weight))]
+impl<T: Config> NativeFungibleHandle<T>
+where
+	T::AccountId: From<[u8; 32]>,
+{
+	fn balance_of_cross(&self, owner: CrossAddress) -> Result<U256> {
+		self.consume_store_reads(1)?;
+		let owner = owner.into_sub_cross_account::<T>()?;
+		let balance = <Pallet<T>>::balance_of(&owner);
+		Ok(balance.into())
+	}
+
+	#[weight(<SelfWeightOf<T>>::transfer_allow_death())]
+	fn transfer_cross(&mut self, caller: Caller, to: CrossAddress, amount: U256) -> Result<bool> {
+		let caller = T::CrossAccountId::from_eth(caller);
+		let to = to.into_sub_cross_account::<T>()?;
+		let amount = amount.try_into().map_err(|_| "amount overflow")?;
+		let budget = self
+			.recorder()
+			.weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+		<Pallet<T>>::transfer(self, &caller, &to, amount, &budget)
+			.map_err(|e| dispatch_to_evm::<T>(e.error))?;
+
+		Ok(true)
+	}
+
+	#[weight(<SelfWeightOf<T>>::transfer_allow_death())]
+	fn transfer_from_cross(
+		&mut self,
+		caller: Caller,
+		from: CrossAddress,
+		to: CrossAddress,
+		amount: U256,
+	) -> Result<bool> {
+		let caller = T::CrossAccountId::from_eth(caller);
+		let from = from.into_sub_cross_account::<T>()?;
+		let to = to.into_sub_cross_account::<T>()?;
+		let amount = amount.try_into().map_err(|_| "amount overflow")?;
+
+		if from != caller {
+			return Err("no permission".into());
+		}
+
+		let budget = self
+			.recorder()
+			.weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+		<Pallet<T>>::transfer_from(self, &caller, &from, &to, amount, &budget)
+			.map_err(|e| dispatch_to_evm::<T>(e.error))?;
+
+		Ok(true)
+	}
+}
+
+#[solidity_interface(
+	name = UniqueNativeFungible,
+	is(ERC20, ERC20UniqueExtensions),
+	enum(derive(PreDispatch))
+)]
+impl<T: Config> NativeFungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}
+
+generate_stubgen!(gen_impl, UniqueNativeFungibleCall<()>, true);
+generate_stubgen!(gen_iface, UniqueNativeFungibleCall<()>, false);
+
+impl<T: Config> CommonEvmHandler for NativeFungibleHandle<T>
+where
+	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,
+{
+	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNativeFungible.raw");
+
+	fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {
+		call::<T, UniqueNativeFungibleCall<T>, _, _>(handle, self)
+	}
+}
addedpallets/balances-adapter/src/lib.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/balances-adapter/src/lib.rs
@@ -0,0 +1,206 @@
+#![cfg_attr(not(feature = "std"), no_std)]
+
+extern crate alloc;
+use core::ops::Deref;
+
+use frame_support::sp_runtime::DispatchResult;
+use pallet_evm_coder_substrate::{WithRecorder, SubstrateRecorder};
+pub use pallet::*;
+
+pub mod common;
+pub mod erc;
+
+pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;
+
+/// Handle for native fungible collection
+pub struct NativeFungibleHandle<T: Config>(SubstrateRecorder<T>);
+impl<T: Config> NativeFungibleHandle<T> {
+	/// Creates a handle
+	pub fn new() -> NativeFungibleHandle<T> {
+		Self(SubstrateRecorder::new(u64::MAX))
+	}
+
+	/// Creates a handle
+	pub fn new_with_gas_limit(gas_limit: u64) -> NativeFungibleHandle<T> {
+		Self(SubstrateRecorder::new(gas_limit))
+	}
+
+	/// Check if the collection is internal
+	pub fn check_is_internal(&self) -> DispatchResult {
+		Ok(())
+	}
+}
+
+impl<T: Config> WithRecorder<T> for NativeFungibleHandle<T> {
+	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {
+		&self.0
+	}
+	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {
+		self.0
+	}
+}
+
+impl<T: Config> Deref for NativeFungibleHandle<T> {
+	type Target = SubstrateRecorder<T>;
+
+	fn deref(&self) -> &Self::Target {
+		&self.0
+	}
+}
+#[frame_support::pallet]
+pub mod pallet {
+	use super::*;
+	use alloc::string::String;
+	use frame_support::{
+		dispatch::PostDispatchInfo,
+		ensure,
+		pallet_prelude::{DispatchResultWithPostInfo, Pays},
+		traits::{
+			Get,
+			fungible::{Inspect, Mutate},
+			tokens::Preservation,
+		},
+	};
+	use pallet_balances::WeightInfo;
+	use pallet_common::{erc::CrossAccountId, Error as CommonError, Pallet as PalletCommon};
+	use pallet_structure::Pallet as PalletStructure;
+	use sp_core::U256;
+	use sp_runtime::DispatchError;
+	use up_data_structs::{budget::Budget, mapping::TokenAddressMapping};
+
+	#[pallet::config]
+	pub trait Config:
+		frame_system::Config
+		+ pallet_evm_coder_substrate::Config
+		+ pallet_common::Config
+		+ pallet_structure::Config
+	{
+		/// Inspect from `pallet_balances`
+		type Inspect: frame_support::traits::tokens::fungible::Inspect<
+			Self::AccountId,
+			Balance = Self::CurrencyBalance,
+		>;
+
+		/// Mutate from `pallet_balances`
+		type Mutate: frame_support::traits::tokens::fungible::Mutate<
+			Self::AccountId,
+			Balance = Self::CurrencyBalance,
+		>;
+
+		/// Balance type of chain
+		type CurrencyBalance: Into<U256> + TryFrom<U256> + TryFrom<u128> + Into<u128>;
+
+		/// Decimals of balance
+		type Decimals: Get<u8>;
+		/// Collection name
+		type Name: Get<String>;
+		/// Collection symbol
+		type Symbol: Get<String>;
+
+		/// Weight information
+		type WeightInfo: WeightInfo;
+	}
+	#[pallet::pallet]
+	pub struct Pallet<T>(_);
+
+	impl<T: Config> Pallet<T> {
+		pub fn balance_of(account: &T::CrossAccountId) -> u128 {
+			T::Inspect::balance(account.as_sub()).into()
+		}
+
+		pub fn total_balance(account: &T::CrossAccountId) -> u128 {
+			T::Inspect::total_balance(account.as_sub()).into()
+		}
+
+		pub fn total_issuance() -> u128 {
+			T::Inspect::total_issuance().into()
+		}
+
+		/// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.
+		/// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.
+		///
+		/// - `spender`: CrossAccountId who has the allowance rights.
+		/// - `from`: The owner of the tokens who sets the allowance.
+		/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.
+		fn check_allowed(
+			spender: &T::CrossAccountId,
+			from: &T::CrossAccountId,
+			nesting_budget: &dyn Budget,
+		) -> Result<u128, DispatchError> {
+			if let Some((collection_id, token_id)) =
+				T::CrossTokenAddressMapping::address_to_token(from)
+			{
+				ensure!(
+					<PalletStructure<T>>::check_indirectly_owned(
+						spender.clone(),
+						collection_id,
+						token_id,
+						None,
+						nesting_budget
+					)?,
+					<CommonError<T>>::ApprovedValueTooLow,
+				);
+			} else if !spender.conv_eq(from) {
+				return Ok(0);
+			}
+
+			Ok(Self::balance_of(from))
+		}
+
+		/// Transfers the specified amount of tokens. Will check that
+		/// the transfer is allowed for the token.
+		///
+		/// - `collection`: Collection that contains the token.
+		/// - `from`: Owner of tokens to transfer.
+		/// - `to`: Recepient of transfered tokens.
+		/// - `amount`: Amount of tokens to transfer.
+		/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.
+		pub fn transfer(
+			_collection: &NativeFungibleHandle<T>,
+			from: &T::CrossAccountId,
+			to: &T::CrossAccountId,
+			amount: u128,
+			_nesting_budget: &dyn Budget,
+		) -> DispatchResultWithPostInfo {
+			<PalletCommon<T>>::ensure_correct_receiver(to)?;
+
+			if from != to && amount != 0 {
+				let amount = amount
+					.try_into()
+					.map_err(|_| sp_runtime::ArithmeticError::Overflow)?;
+				T::Mutate::transfer(from.as_sub(), to.as_sub(), amount, Preservation::Expendable)?;
+			};
+
+			Ok(PostDispatchInfo {
+				actual_weight: Some(<SelfWeightOf<T>>::transfer_allow_death()),
+				pays_fee: Pays::Yes,
+			})
+		}
+
+		/// Transfer NFT token from one account to another.
+		///
+		/// Same as the [`Self::transfer`] but spender doesn't needs to be the owner of the token.
+		/// The owner should set allowance for the spender to transfer token.
+		///
+		/// - `collection`: Collection that contains the token.
+		/// - `spender`: Account that spend the money.
+		/// - `from`: Owner of tokens to transfer.
+		/// - `to`: Recepient of transfered tokens.
+		/// - `amount`: Amount of tokens to transfer.
+		/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.
+		pub fn transfer_from(
+			collection: &NativeFungibleHandle<T>,
+			spender: &T::CrossAccountId,
+			from: &T::CrossAccountId,
+			to: &T::CrossAccountId,
+			amount: u128,
+			nesting_budget: &dyn Budget,
+		) -> DispatchResultWithPostInfo {
+			let allowance = Self::check_allowed(spender, from, nesting_budget)?;
+			if allowance < amount {
+				return Err(<CommonError<T>>::ApprovedValueTooLow.into());
+			}
+			Self::transfer(collection, from, to, amount, nesting_budget)
+		}
+	}
+}
addedpallets/balances-adapter/src/stubs/UniqueNativeFungible.rawdiffbeforeafterboth

binary blob — no preview

addedpallets/balances-adapter/src/stubs/UniqueNativeFungible.soldiffbeforeafterboth
--- /dev/null
+++ b/pallets/balances-adapter/src/stubs/UniqueNativeFungible.sol
@@ -0,0 +1,158 @@
+// SPDX-License-Identifier: OTHER
+// This code is automatically generated
+
+pragma solidity >=0.8.0 <0.9.0;
+
+/// @dev common stubs holder
+contract Dummy {
+	uint8 dummy;
+	string stub_error = "this contract is implemented in native";
+}
+
+contract ERC165 is Dummy {
+	function supportsInterface(bytes4 interfaceID) external view returns (bool) {
+		require(false, stub_error);
+		interfaceID;
+		return true;
+	}
+}
+
+/// @dev the ERC-165 identifier for this interface is 0x1313556c
+contract ERC20UniqueExtensions is Dummy, ERC165 {
+	/// @dev EVM selector for this function is: 0xec069398,
+	///  or in textual repr: balanceOfCross((address,uint256))
+	function balanceOfCross(CrossAddress memory owner) public view returns (uint256) {
+		require(false, stub_error);
+		owner;
+		dummy;
+		return 0;
+	}
+
+	/// @dev EVM selector for this function is: 0x2ada85ff,
+	///  or in textual repr: transferCross((address,uint256),uint256)
+	function transferCross(CrossAddress memory to, uint256 amount) public returns (bool) {
+		require(false, stub_error);
+		to;
+		amount;
+		dummy = 0;
+		return false;
+	}
+
+	/// @dev EVM selector for this function is: 0xd5cf430b,
+	///  or in textual repr: transferFromCross((address,uint256),(address,uint256),uint256)
+	function transferFromCross(
+		CrossAddress memory from,
+		CrossAddress memory to,
+		uint256 amount
+	) public returns (bool) {
+		require(false, stub_error);
+		from;
+		to;
+		amount;
+		dummy = 0;
+		return false;
+	}
+}
+
+/// Cross account struct
+struct CrossAddress {
+	address eth;
+	uint256 sub;
+}
+
+/// @dev inlined interface
+contract ERC20Events {
+	event Transfer(address indexed from, address indexed to, uint256 value);
+	event Approval(address indexed owner, address indexed spender, uint256 value);
+}
+
+/// @dev the ERC-165 identifier for this interface is 0x942e8b22
+contract ERC20 is Dummy, ERC165, ERC20Events {
+	/// @dev EVM selector for this function is: 0xdd62ed3e,
+	///  or in textual repr: allowance(address,address)
+	function allowance(address owner, address spender) public view returns (uint256) {
+		require(false, stub_error);
+		owner;
+		spender;
+		dummy;
+		return 0;
+	}
+
+	/// @dev EVM selector for this function is: 0x095ea7b3,
+	///  or in textual repr: approve(address,uint256)
+	function approve(address spender, uint256 amount) public returns (bool) {
+		require(false, stub_error);
+		spender;
+		amount;
+		dummy = 0;
+		return false;
+	}
+
+	/// @dev EVM selector for this function is: 0x70a08231,
+	///  or in textual repr: balanceOf(address)
+	function balanceOf(address owner) public view returns (uint256) {
+		require(false, stub_error);
+		owner;
+		dummy;
+		return 0;
+	}
+
+	/// @dev EVM selector for this function is: 0x313ce567,
+	///  or in textual repr: decimals()
+	function decimals() public view returns (uint8) {
+		require(false, stub_error);
+		dummy;
+		return 0;
+	}
+
+	/// @dev EVM selector for this function is: 0x06fdde03,
+	///  or in textual repr: name()
+	function name() public view returns (string memory) {
+		require(false, stub_error);
+		dummy;
+		return "";
+	}
+
+	/// @dev EVM selector for this function is: 0x95d89b41,
+	///  or in textual repr: symbol()
+	function symbol() public view returns (string memory) {
+		require(false, stub_error);
+		dummy;
+		return "";
+	}
+
+	/// @dev EVM selector for this function is: 0x18160ddd,
+	///  or in textual repr: totalSupply()
+	function totalSupply() public view returns (uint256) {
+		require(false, stub_error);
+		dummy;
+		return 0;
+	}
+
+	/// @dev EVM selector for this function is: 0xa9059cbb,
+	///  or in textual repr: transfer(address,uint256)
+	function transfer(address to, uint256 amount) public returns (bool) {
+		require(false, stub_error);
+		to;
+		amount;
+		dummy = 0;
+		return false;
+	}
+
+	/// @dev EVM selector for this function is: 0x23b872dd,
+	///  or in textual repr: transferFrom(address,address,uint256)
+	function transferFrom(
+		address from,
+		address to,
+		uint256 amount
+	) public returns (bool) {
+		require(false, stub_error);
+		from;
+		to;
+		amount;
+		dummy = 0;
+		return false;
+	}
+}
+
+contract UniqueNativeFungible is Dummy, ERC165, ERC20, ERC20UniqueExtensions {}
modifiedpallets/common/src/dispatch.rsdiffbeforeafterboth
--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -11,7 +11,7 @@
 use sp_runtime::DispatchError;
 use up_data_structs::{CollectionId, CreateCollectionData, CollectionFlags};
 
-use crate::{pallet::Config, CommonCollectionOperations, CollectionHandle};
+use crate::{pallet::Config, CommonCollectionOperations};
 
 // TODO: move to benchmarking
 /// Price of [`dispatch_tx`] call with noop `call` argument
@@ -34,16 +34,11 @@
 	collection: CollectionId,
 	call: C,
 ) -> DispatchResultWithPostInfo {
-	let handle =
-		CollectionHandle::try_get(collection).map_err(|error| DispatchErrorWithPostInfo {
-			post_info: PostDispatchInfo {
-				actual_weight: Some(dispatch_weight::<T>()),
-				pays_fee: Pays::Yes,
-			},
-			error,
-		})?;
-	handle
-		.check_is_internal()
+	let dispatched = T::CollectionDispatch::dispatch(collection)
+		.and_then(|dispatched| {
+			dispatched.check_is_internal()?;
+			Ok(dispatched)
+		})
 		.map_err(|error| DispatchErrorWithPostInfo {
 			post_info: PostDispatchInfo {
 				actual_weight: Some(dispatch_weight::<T>()),
@@ -51,7 +46,6 @@
 			},
 			error,
 		})?;
-	let dispatched = T::CollectionDispatch::dispatch(handle);
 	let mut result = call(dispatched.as_dyn());
 	match &mut result {
 		Ok(PostDispatchInfo {
@@ -72,6 +66,9 @@
 
 /// Interface for working with different collections through the dispatcher.
 pub trait CollectionDispatch<T: Config> {
+	/// Check if the collection is internal.
+	fn check_is_internal(&self) -> DispatchResult;
+
 	/// Create a collection. The collection will be created according to the value of [`data.mode`](CreateCollectionData::mode).
 	///
 	/// * `sender` - The user who will become the owner of the collection.
@@ -87,15 +84,14 @@
 	///
 	/// * `sender` - The owner of the collection.
 	/// * `handle` - Collection handle.
-	fn destroy(sender: T::CrossAccountId, handle: CollectionHandle<T>) -> DispatchResult;
+	fn destroy(sender: T::CrossAccountId, collection_id: CollectionId) -> DispatchResult;
 
 	/// Get a specialized collection from the handle.
 	///
 	/// * `handle` - Collection handle.
-	fn dispatch(handle: CollectionHandle<T>) -> Self;
-
-	/// Get the collection handle for the corresponding implementation.
-	fn into_inner(self) -> CollectionHandle<T>;
+	fn dispatch(collection_id: CollectionId) -> Result<Self, DispatchError>
+	where
+		Self: Sized;
 
 	/// Get the implementation of [`CommonCollectionOperations`].
 	fn as_dyn(&self) -> &dyn CommonCollectionOperations<T>;
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -72,7 +72,6 @@
 	dispatch::Pays,
 	transactional, fail,
 };
-use pallet_evm::GasWeightMapping;
 use up_data_structs::{
 	AccessMode, COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, CollectionFlags,
 	RpcCollectionFlags, CollectionId, CreateItemData, MAX_TOKEN_PREFIX_LENGTH,
@@ -105,7 +104,7 @@
 /// Collection handle contains information about collection data and id.
 /// Also provides functionality to count consumed gas.
 ///
-/// CollectionHandle is used as a generic wrapper for collections of all types.
+/// CollectionHandle is used as a generic wrapper for collections of all types (except native fungible).
 /// It allows to perform common operations and queries on any collection type,
 /// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].
 #[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]
@@ -129,11 +128,7 @@
 impl<T: Config> CollectionHandle<T> {
 	/// Same as [CollectionHandle::new] but with an explicit gas limit.
 	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {
-		<CollectionById<T>>::get(id).map(|collection| Self {
-			id,
-			collection,
-			recorder: SubstrateRecorder::new(gas_limit),
-		})
+		Self::new_with_recorder(id, SubstrateRecorder::new(gas_limit))
 	}
 
 	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].
@@ -161,14 +156,7 @@
 		&self,
 		reads: u64,
 	) -> pallet_evm_coder_substrate::execution::Result<()> {
-		self.recorder
-			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(
-				<T as frame_system::Config>::DbWeight::get()
-					.read
-					.saturating_mul(reads),
-				// TODO: measure proof
-				0,
-			)))
+		self.recorder().consume_store_reads(reads)
 	}
 
 	/// Consume gas for writing.
@@ -176,14 +164,7 @@
 		&self,
 		writes: u64,
 	) -> pallet_evm_coder_substrate::execution::Result<()> {
-		self.recorder
-			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(
-				<T as frame_system::Config>::DbWeight::get()
-					.write
-					.saturating_mul(writes),
-				// TODO: measure proof
-				0,
-			)))
+		self.recorder().consume_store_writes(writes)
 	}
 
 	/// Consume gas for reading and writing.
@@ -192,15 +173,8 @@
 		reads: u64,
 		writes: u64,
 	) -> pallet_evm_coder_substrate::execution::Result<()> {
-		let weight = <T as frame_system::Config>::DbWeight::get();
-		let reads = weight.read.saturating_mul(reads);
-		let writes = weight.read.saturating_mul(writes);
-		self.recorder
-			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(
-				reads.saturating_add(writes),
-				// TODO: measure proof
-				0,
-			)))
+		self.recorder()
+			.consume_store_reads_and_writes(reads, writes)
 	}
 
 	/// Save collection to storage.
@@ -469,6 +443,8 @@
 	}
 
 	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
+	/// Collection id for native fungible collction.
+	pub const NATIVE_FUNGIBLE_COLLECTION_ID: CollectionId = CollectionId(0);
 
 	#[pallet::pallet]
 	#[pallet::storage_version(STORAGE_VERSION)]
modifiedpallets/evm-coder-substrate/src/lib.rsdiffbeforeafterboth
--- a/pallets/evm-coder-substrate/src/lib.rs
+++ b/pallets/evm-coder-substrate/src/lib.rs
@@ -37,7 +37,7 @@
 	ExitError, ExitRevert, ExitSucceed, GasWeightMapping, PrecompileFailure, PrecompileOutput,
 	PrecompileResult, PrecompileHandle,
 };
-use sp_core::H160;
+use sp_core::{Get, H160};
 // #[cfg(feature = "runtime-benchmarks")]
 // pub mod benchmarking;
 pub mod execution;
@@ -204,6 +204,40 @@
 			Err(Error::Error(e)) => Err(e.into()),
 		})
 	}
+
+	/// Consume gas for reading.
+	pub fn consume_store_reads(&self, reads: u64) -> execution::Result<()> {
+		self.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(
+			<T as frame_system::Config>::DbWeight::get()
+				.read
+				.saturating_mul(reads),
+			// TODO: measure proof
+			0,
+		)))
+	}
+
+	/// Consume gas for writing.
+	pub fn consume_store_writes(&self, writes: u64) -> execution::Result<()> {
+		self.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(
+			<T as frame_system::Config>::DbWeight::get()
+				.write
+				.saturating_mul(writes),
+			// TODO: measure proof
+			0,
+		)))
+	}
+
+	/// Consume gas for reading and writing.
+	pub fn consume_store_reads_and_writes(&self, reads: u64, writes: u64) -> execution::Result<()> {
+		let weight = <T as frame_system::Config>::DbWeight::get();
+		let reads = weight.read.saturating_mul(reads);
+		let writes = weight.read.saturating_mul(writes);
+		self.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(
+			reads.saturating_add(writes),
+			// TODO: measure proof
+			0,
+		)))
+	}
 }
 
 pub fn dispatch_to_evm<T: Config>(err: DispatchError) -> execution::Error {
modifiedpallets/fungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -109,7 +109,8 @@
 			.recorder
 			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
-		<Pallet<T>>::transfer(self, &caller, &to, amount, &budget).map_err(|_| "transfer error")?;
+		<Pallet<T>>::transfer(self, &caller, &to, amount, &budget)
+			.map_err(|e| dispatch_to_evm::<T>(e.error))?;
 		Ok(true)
 	}
 
modifiedpallets/nonfungible/Cargo.tomldiffbeforeafterboth
--- a/pallets/nonfungible/Cargo.toml
+++ b/pallets/nonfungible/Cargo.toml
@@ -12,6 +12,7 @@
 frame-benchmarking = { workspace = true, optional = true }
 frame-support = { workspace = true }
 frame-system = { workspace = true }
+pallet-balances = { workspace = true }
 pallet-common = { workspace = true }
 pallet-evm = { workspace = true }
 pallet-evm-coder-substrate = { workspace = true }
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -166,7 +166,11 @@
 
 	#[pallet::config]
 	pub trait Config:
-		frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config
+		frame_system::Config
+		+ pallet_common::Config
+		+ pallet_structure::Config
+		+ pallet_evm::Config
+		+ pallet_balances::Config
 	{
 		type WeightInfo: WeightInfo;
 	}
@@ -1325,11 +1329,15 @@
 	}
 
 	fn nest(under: (CollectionId, TokenId), to_nest: (CollectionId, TokenId)) {
-		<TokenChildren<T>>::insert((under.0, under.1, (to_nest.0, to_nest.1)), true);
+		if to_nest.0 != pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {
+			<TokenChildren<T>>::insert((under.0, under.1, to_nest), true);
+		}
 	}
 
 	fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {
-		<TokenChildren<T>>::remove((under.0, under.1, to_unnest));
+		if to_unnest.0 != pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {
+			<TokenChildren<T>>::remove((under.0, under.1, to_unnest));
+		}
 	}
 
 	fn collection_has_tokens(collection_id: CollectionId) -> bool {
modifiedpallets/structure/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/structure/src/benchmarking.rs
+++ b/pallets/structure/src/benchmarking.rs
@@ -42,7 +42,7 @@
 			},
 			CollectionFlags::default(),
 		)?;
-		let dispatch = T::CollectionDispatch::dispatch(CollectionHandle::try_get(CollectionId(1))?);
+		let dispatch = T::CollectionDispatch::dispatch(CollectionId(1))?;
 		let dispatch = dispatch.as_dyn();
 
 		dispatch.create_item(caller_cross.clone(), caller_cross.clone(), CreateItemData::NFT(CreateNftData::default()), &Unlimited)?;
modifiedpallets/structure/src/lib.rsdiffbeforeafterboth
--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -60,7 +60,7 @@
 use frame_support::dispatch::{DispatchError, DispatchResult, DispatchResultWithPostInfo};
 use frame_support::fail;
 pub use pallet::*;
-use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};
+use pallet_common::{dispatch::CollectionDispatch};
 use up_data_structs::{
 	CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget, TokenOwnerError,
 };
@@ -155,11 +155,10 @@
 		token: TokenId,
 	) -> Result<Parent<T::CrossAccountId>, DispatchError> {
 		// TODO: Reduce cost by not reading collection config
-		let handle = match CollectionHandle::try_get(collection) {
+		let handle = match T::CollectionDispatch::dispatch(collection) {
 			Ok(v) => v,
 			Err(_) => return Ok(Parent::TokenNotFound),
 		};
-		let handle = T::CollectionDispatch::dispatch(handle);
 		let handle = handle.as_dyn();
 
 		Ok(match handle.token_owner(token) {
@@ -279,8 +278,7 @@
 		self_budget: &dyn Budget,
 		breadth_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo {
-		let handle = <CollectionHandle<T>>::try_get(collection)?;
-		let dispatch = T::CollectionDispatch::dispatch(handle);
+		let dispatch = T::CollectionDispatch::dispatch(collection)?;
 		let dispatch = dispatch.as_dyn();
 		dispatch.burn_item_recursively(from.clone(), token, self_budget, breadth_budget)
 	}
@@ -405,9 +403,7 @@
 			return Ok(())
 		};
 
-		let handle = <CollectionHandle<T>>::try_get(collection)?;
-
-		let dispatch = T::CollectionDispatch::dispatch(handle);
+		let dispatch = T::CollectionDispatch::dispatch(collection)?;
 		let dispatch = dispatch.as_dyn();
 
 		action(dispatch, token)
modifiedpallets/unique/Cargo.tomldiffbeforeafterboth
--- a/pallets/unique/Cargo.toml
+++ b/pallets/unique/Cargo.toml
@@ -24,6 +24,7 @@
 	'frame-benchmarking/std',
 	'frame-support/std',
 	'frame-system/std',
+	'pallet-balances-adapter/std',
 	'pallet-common/std',
 	'pallet-evm-coder-substrate/std',
 	'pallet-evm/std',
@@ -46,6 +47,7 @@
 frame-benchmarking = { workspace = true, optional = true }
 frame-support = { workspace = true }
 frame-system = { workspace = true }
+pallet-balances-adapter = { workspace = true }
 pallet-common = { workspace = true }
 pallet-evm = { workspace = true }
 pallet-evm-coder-substrate = { workspace = true }
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -440,6 +440,10 @@
 			collection_id: CollectionId,
 			address: T::CrossAccountId,
 		) -> DispatchResult {
+			if collection_id == pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {
+				fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+			}
+
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let collection = <CollectionHandle<T>>::try_get(collection_id)?;
 			collection.check_is_internal()?;
@@ -467,6 +471,10 @@
 			collection_id: CollectionId,
 			address: T::CrossAccountId,
 		) -> DispatchResult {
+			if collection_id == pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {
+				fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+			}
+
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let collection = <CollectionHandle<T>>::try_get(collection_id)?;
 			collection.check_is_internal()?;
@@ -493,6 +501,9 @@
 			collection_id: CollectionId,
 			new_owner: T::AccountId,
 		) -> DispatchResult {
+			if collection_id == pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {
+				fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+			}
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let new_owner = T::CrossAccountId::from_sub(new_owner);
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
@@ -522,6 +533,9 @@
 			collection_id: CollectionId,
 			new_admin_id: T::CrossAccountId,
 		) -> DispatchResult {
+			if collection_id == pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {
+				fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+			}
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let collection = <CollectionHandle<T>>::try_get(collection_id)?;
 			<PalletCommon<T>>::toggle_admin(&collection, &sender, &new_admin_id, true)
@@ -548,6 +562,9 @@
 			collection_id: CollectionId,
 			account_id: T::CrossAccountId,
 		) -> DispatchResult {
+			if collection_id == pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {
+				fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+			}
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let collection = <CollectionHandle<T>>::try_get(collection_id)?;
 			<PalletCommon<T>>::toggle_admin(&collection, &sender, &account_id, false)
@@ -573,6 +590,9 @@
 			collection_id: CollectionId,
 			new_sponsor: T::AccountId,
 		) -> DispatchResult {
+			if collection_id == pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {
+				fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+			}
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
 			target_collection.set_sponsor(&sender, new_sponsor.clone())
@@ -597,6 +617,9 @@
 			origin: OriginFor<T>,
 			collection_id: CollectionId,
 		) -> DispatchResult {
+			if collection_id == pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {
+				fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+			}
 			let sender = ensure_signed(origin)?;
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
 			target_collection.confirm_sponsorship(&sender)
@@ -617,6 +640,9 @@
 			origin: OriginFor<T>,
 			collection_id: CollectionId,
 		) -> DispatchResult {
+			if collection_id == pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {
+				fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+			}
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
 			target_collection.remove_sponsor(&sender)
@@ -894,6 +920,9 @@
 			collection_id: CollectionId,
 			value: bool,
 		) -> DispatchResult {
+			if collection_id == pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {
+				fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+			}
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
 			target_collection.check_is_internal()?;
@@ -1146,6 +1175,9 @@
 			collection_id: CollectionId,
 			new_limit: CollectionLimits,
 		) -> DispatchResult {
+			if collection_id == pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {
+				fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+			}
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
 			<PalletCommon<T>>::update_limits(&sender, &mut target_collection, new_limit)
@@ -1170,6 +1202,9 @@
 			collection_id: CollectionId,
 			new_permission: CollectionPermissions,
 		) -> DispatchResult {
+			if collection_id == pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {
+				fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+			}
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
 			<PalletCommon<T>>::update_permissions(&sender, &mut target_collection, new_permission)
@@ -1238,6 +1273,9 @@
 			origin: OriginFor<T>,
 			collection_id: CollectionId,
 		) -> DispatchResult {
+			if collection_id == pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {
+				fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+			}
 			ensure_root(origin)?;
 			<PalletCommon<T>>::repair_collection(collection_id)
 		}
@@ -1296,10 +1334,7 @@
 			sender: T::CrossAccountId,
 			collection_id: CollectionId,
 		) -> DispatchResult {
-			let collection = <CollectionHandle<T>>::try_get(collection_id)?;
-			collection.check_is_internal()?;
-
-			T::CollectionDispatch::destroy(sender, collection)?;
+			T::CollectionDispatch::destroy(sender, collection_id)?;
 
 			// TODO: basket cleanup should be moved elsewhere
 			// Maybe runtime dispatch.rs should perform it?
modifiedruntime/common/config/pallets/mod.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/mod.rs
+++ b/runtime/common/config/pallets/mod.rs
@@ -14,6 +14,7 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
+use alloc::string::{String, ToString};
 use frame_support::parameter_types;
 use sp_runtime::traits::AccountIdConversion;
 use crate::{
@@ -23,9 +24,10 @@
 		weights::CommonWeights,
 		RelayChainBlockNumberProvider,
 	},
-	Runtime, RuntimeEvent, RuntimeCall, RuntimeOrigin, Balances,
+	Runtime, RuntimeEvent, RuntimeCall, RuntimeOrigin, RUNTIME_NAME, TOKEN_SYMBOL, DECIMALS,
+	Balances,
 };
-use frame_support::traits::{ConstU32, ConstU64};
+use frame_support::traits::{ConstU32, ConstU64, Currency};
 use up_common::{
 	types::{AccountId, Balance, BlockNumber},
 	constants::*,
@@ -51,8 +53,8 @@
 pub mod preimage;
 
 parameter_types! {
+	pub const CollectionCreationPrice: Balance = 2 * UNIQUE;
 	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account_truncating();
-	pub const CollectionCreationPrice: Balance = 2 * UNIQUE;
 }
 
 impl pallet_common::Config for Runtime {
@@ -85,6 +87,21 @@
 }
 
 parameter_types! {
+	pub const Decimals: u8 = DECIMALS;
+	pub Name: String = RUNTIME_NAME.to_string();
+	pub Symbol: String = TOKEN_SYMBOL.to_string();
+}
+impl pallet_balances_adapter::Config for Runtime {
+	type Inspect = Balances;
+	type Mutate = Balances;
+	type CurrencyBalance = <Balances as Currency<Self::AccountId>>::Balance;
+	type Decimals = Decimals;
+	type Name = Name;
+	type Symbol = Symbol;
+	type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;
+}
+
+parameter_types! {
 	pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied
 }
 
modifiedruntime/common/construct_runtime.rsdiffbeforeafterboth
--- a/runtime/common/construct_runtime.rs
+++ b/runtime/common/construct_runtime.rs
@@ -106,6 +106,8 @@
 
 				Maintenance: pallet_maintenance = 154,
 
+				BalancesAdapter: pallet_balances_adapter = 155,
+
 				#[cfg(feature = "pallet-test-utils")]
 				TestUtils: pallet_test_utils = 255,
 			}
modifiedruntime/common/dispatch.rsdiffbeforeafterboth
--- a/runtime/common/dispatch.rs
+++ b/runtime/common/dispatch.rs
@@ -14,7 +14,7 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-use frame_support::{dispatch::DispatchResult, ensure};
+use frame_support::{dispatch::DispatchResult, ensure, fail};
 use pallet_evm::{PrecompileHandle, PrecompileResult};
 use sp_core::H160;
 use sp_runtime::DispatchError;
@@ -25,6 +25,7 @@
 };
 pub use pallet_common::dispatch::CollectionDispatch;
 use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};
+use pallet_balances_adapter::{NativeFungibleHandle};
 use pallet_nonfungible::{Pallet as PalletNonfungible, NonfungibleHandle};
 use pallet_refungible::{
 	Pallet as PalletRefungible, RefungibleHandle, erc_token::RefungibleTokenHandle,
@@ -39,20 +40,35 @@
 
 pub enum CollectionDispatchT<T>
 where
-	T: pallet_fungible::Config + pallet_nonfungible::Config + pallet_refungible::Config,
+	T: pallet_fungible::Config
+		+ pallet_nonfungible::Config
+		+ pallet_refungible::Config
+		+ pallet_balances_adapter::Config,
 {
 	Fungible(FungibleHandle<T>),
 	Nonfungible(NonfungibleHandle<T>),
 	Refungible(RefungibleHandle<T>),
+	NativeFungible(NativeFungibleHandle<T>),
 }
+
 impl<T> CollectionDispatch<T> for CollectionDispatchT<T>
 where
 	T: pallet_common::Config
 		+ pallet_unique::Config
 		+ pallet_fungible::Config
 		+ pallet_nonfungible::Config
-		+ pallet_refungible::Config,
+		+ pallet_refungible::Config
+		+ pallet_balances_adapter::Config,
 {
+	fn check_is_internal(&self) -> DispatchResult {
+		match self {
+			Self::Fungible(h) => h.check_is_internal(),
+			Self::Nonfungible(h) => h.check_is_internal(),
+			Self::Refungible(h) => h.check_is_internal(),
+			Self::NativeFungible(h) => h.check_is_internal(),
+		}
+	}
+
 	fn create(
 		sender: T::CrossAccountId,
 		payer: T::CrossAccountId,
@@ -83,7 +99,13 @@
 		Ok(id)
 	}
 
-	fn destroy(sender: T::CrossAccountId, collection: CollectionHandle<T>) -> DispatchResult {
+	fn destroy(sender: T::CrossAccountId, collection_id: CollectionId) -> DispatchResult {
+		if collection_id == pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {
+			fail!(<pallet_common::Error<T>>::UnsupportedOperation);
+		}
+
+		let collection = <CollectionHandle<T>>::try_get(collection_id)?;
+
 		match collection.mode {
 			CollectionMode::ReFungible => {
 				PalletRefungible::destroy_collection(RefungibleHandle::cast(collection), &sender)?
@@ -98,20 +120,19 @@
 		Ok(())
 	}
 
-	fn dispatch(handle: CollectionHandle<T>) -> Self {
-		match handle.mode {
+	fn dispatch(collection_id: CollectionId) -> Result<Self, DispatchError> {
+		if collection_id == pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {
+			return Ok(Self::NativeFungible(
+				NativeFungibleHandle::new_with_gas_limit(u64::MAX),
+			));
+		}
+
+		let handle = <CollectionHandle<T>>::try_get(collection_id)?;
+		Ok(match handle.mode {
 			CollectionMode::Fungible(_) => Self::Fungible(FungibleHandle::cast(handle)),
 			CollectionMode::NFT => Self::Nonfungible(NonfungibleHandle::cast(handle)),
 			CollectionMode::ReFungible => Self::Refungible(RefungibleHandle::cast(handle)),
-		}
-	}
-
-	fn into_inner(self) -> CollectionHandle<T> {
-		match self {
-			Self::Fungible(f) => f.into_inner(),
-			Self::Nonfungible(f) => f.into_inner(),
-			Self::Refungible(f) => f.into_inner(),
-		}
+		})
 	}
 
 	fn as_dyn(&self) -> &dyn CommonCollectionOperations<T> {
@@ -119,6 +140,7 @@
 			Self::Fungible(h) => h,
 			Self::Nonfungible(h) => h,
 			Self::Refungible(h) => h,
+			Self::NativeFungible(h) => h,
 		}
 	}
 }
@@ -129,7 +151,8 @@
 		+ pallet_unique::Config
 		+ pallet_fungible::Config
 		+ pallet_nonfungible::Config
-		+ pallet_refungible::Config,
+		+ pallet_refungible::Config
+		+ pallet_balances_adapter::Config,
 	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,
 {
 	fn is_reserved(target: &H160) -> bool {
@@ -166,14 +189,19 @@
 	}
 	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {
 		if let Some(collection_id) = map_eth_to_id(&handle.code_address()) {
-			let collection =
-				<CollectionHandle<T>>::new_with_gas_limit(collection_id, handle.remaining_gas())?;
-			let dispatched = Self::dispatch(collection);
+			if collection_id == pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {
+				<NativeFungibleHandle<T>>::new_with_gas_limit(handle.remaining_gas()).call(handle)
+			} else {
+				let collection = <CollectionHandle<T>>::new_with_gas_limit(
+					collection_id,
+					handle.remaining_gas(),
+				)?;
 
-			match dispatched {
-				Self::Fungible(h) => h.call(handle),
-				Self::Nonfungible(h) => h.call(handle),
-				Self::Refungible(h) => h.call(handle),
+				match collection.mode {
+					CollectionMode::Fungible(_) => FungibleHandle::cast(collection).call(handle),
+					CollectionMode::NFT => NonfungibleHandle::cast(collection).call(handle),
+					CollectionMode::ReFungible => RefungibleHandle::cast(collection).call(handle),
+				}
 			}
 		} else if let Some((collection_id, token_id)) =
 			<T as pallet_common::Config>::EvmTokenAddressMapping::address_to_token(
modifiedruntime/common/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -17,7 +17,7 @@
 #[macro_export]
 macro_rules! dispatch_unique_runtime {
 	($collection:ident.$method:ident($($name:ident),*) $($rest:tt)*) => {{
-		let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);
+		let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch($collection)?;
 		let dispatch = collection.as_dyn();
 
 		Ok::<_, DispatchError>(dispatch.$method($($name),*) $($rest)*)
modifiedruntime/common/weights/mod.rsdiffbeforeafterboth
--- a/runtime/common/weights/mod.rs
+++ b/runtime/common/weights/mod.rs
@@ -18,6 +18,9 @@
 use frame_support::{weights::Weight};
 use pallet_common::{CommonWeightInfo, dispatch::dispatch_weight, RefungibleExtensionsWeightInfo};
 
+use pallet_balances_adapter::{
+	Config as NativeFungibleConfig, common::CommonWeights as NativeFungibleWeights,
+};
 use pallet_fungible::{Config as FungibleConfig, common::CommonWeights as FungibleWeights};
 use pallet_nonfungible::{Config as NonfungibleConfig, common::CommonWeights as NonfungibleWeights};
 
@@ -32,6 +35,7 @@
 macro_rules! max_weight_of {
 	($method:ident ( $($args:tt)* )) => {{
 		let max_weight = <FungibleWeights<T>>::$method($($args)*)
+			.max(<NativeFungibleWeights<T>>::$method($($args)*))
 			.max(<NonfungibleWeights<T>>::$method($($args)*));
 
 		#[cfg(feature = "refungible")]
@@ -42,16 +46,22 @@
 }
 
 #[cfg(not(feature = "refungible"))]
-pub trait CommonWeightConfigs: FungibleConfig + NonfungibleConfig {}
+pub trait CommonWeightConfigs: FungibleConfig + NativeFungibleConfig + NonfungibleConfig {}
 
 #[cfg(not(feature = "refungible"))]
-impl<T: FungibleConfig + NonfungibleConfig> CommonWeightConfigs for T {}
+impl<T: FungibleConfig + NativeFungibleConfig + NonfungibleConfig> CommonWeightConfigs for T {}
 
 #[cfg(feature = "refungible")]
-pub trait CommonWeightConfigs: FungibleConfig + NonfungibleConfig + RefungibleConfig {}
+pub trait CommonWeightConfigs:
+	FungibleConfig + NativeFungibleConfig + NonfungibleConfig + RefungibleConfig
+{
+}
 
 #[cfg(feature = "refungible")]
-impl<T: FungibleConfig + NonfungibleConfig + RefungibleConfig> CommonWeightConfigs for T {}
+impl<T: FungibleConfig + NativeFungibleConfig + NonfungibleConfig + RefungibleConfig>
+	CommonWeightConfigs for T
+{
+}
 
 pub struct CommonWeights<T>(PhantomData<T>);
 
modifiedruntime/opal/Cargo.tomldiffbeforeafterboth
--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -18,9 +18,10 @@
 [features]
 default = ['opal-runtime', 'std']
 limit-testing = ['pallet-unique/limit-testing', 'up-data-structs/limit-testing']
-opal-runtime = ['app-promotion', 'collator-selection', 'foreign-assets', 'preimage', 'pallet-test-utils', 'refungible']
+opal-runtime = ['app-promotion', 'collator-selection', 'foreign-assets', 'pallet-test-utils', 'preimage', 'refungible']
 pov-estimate = []
 runtime-benchmarks = [
+	"pallet-preimage/runtime-benchmarks",
 	'cumulus-pallet-parachain-system/runtime-benchmarks',
 	'frame-benchmarking',
 	'frame-support/runtime-benchmarks',
@@ -41,7 +42,6 @@
 	'pallet-inflation/runtime-benchmarks',
 	'pallet-maintenance/runtime-benchmarks',
 	'pallet-nonfungible/runtime-benchmarks',
-	"pallet-preimage/runtime-benchmarks",
 	'pallet-refungible/runtime-benchmarks',
 	'pallet-structure/runtime-benchmarks',
 	'pallet-timestamp/runtime-benchmarks',
@@ -70,8 +70,8 @@
 	# 'pallet-contracts-primitives/std',
 	# 'pallet-contracts-rpc-runtime-api/std',
 	# 'pallet-contract-helpers/std',
-	"pallet-preimage/std",
 	"pallet-authorship/std",
+	"pallet-preimage/std",
 	"pallet-session/std",
 	"sp-consensus-aura/std",
 	'app-promotion-rpc/std',
@@ -79,6 +79,7 @@
 	'fp-rpc/std',
 	'fp-self-contained/std',
 	'pallet-app-promotion/std',
+	'pallet-balances-adapter/std',
 	'pallet-base-fee/std',
 	'pallet-charge-transaction/std',
 	'pallet-collator-selection/std',
@@ -128,8 +129,8 @@
 	"orml-tokens/std",
 	"orml-traits/std",
 	"orml-vesting/std",
-	"orml-xtokens/std",
 	"orml-xcm-support/std",
+	"orml-xtokens/std",
 	"pallet-foreign-assets/std",
 
 	'pallet-maintenance/std',
@@ -139,8 +140,8 @@
 	"pallet-authorship/try-runtime",
 	"pallet-collator-selection/try-runtime",
 	"pallet-identity/try-runtime",
+	"pallet-preimage/try-runtime",
 	"pallet-session/try-runtime",
-	"pallet-preimage/try-runtime",
 	'cumulus-pallet-aura-ext/try-runtime',
 	'cumulus-pallet-dmp-queue/try-runtime',
 	'cumulus-pallet-parachain-system/try-runtime',
@@ -158,6 +159,7 @@
 	'pallet-app-promotion/try-runtime',
 	'pallet-aura/try-runtime',
 	'pallet-balances/try-runtime',
+	'pallet-balances-adapter/try-runtime',
 	'pallet-base-fee/try-runtime',
 	'pallet-charge-transaction/try-runtime',
 	'pallet-common/try-runtime',
@@ -189,8 +191,8 @@
 app-promotion = []
 collator-selection = []
 foreign-assets = []
-preimage = []
 pallet-test-utils = []
+preimage = []
 refungible = []
 scheduler = []
 
@@ -216,8 +218,8 @@
 orml-tokens = { workspace = true }
 orml-traits = { workspace = true }
 orml-vesting = { workspace = true }
+orml-xcm-support = { workspace = true }
 orml-xtokens = { workspace = true }
-orml-xcm-support = { workspace = true }
 pallet-aura = { workspace = true }
 pallet-authorship = { workspace = true }
 pallet-balances = { features = ["insecure_zero_ed"], workspace = true }
@@ -258,6 +260,7 @@
 log = { workspace = true }
 num_enum = { workspace = true }
 pallet-app-promotion = { workspace = true }
+pallet-balances-adapter = { workspace = true }
 pallet-base-fee = { workspace = true }
 pallet-charge-transaction = { workspace = true }
 pallet-collator-selection = { workspace = true }
@@ -291,11 +294,11 @@
 ################################################################################
 # Optional dependencies
 
-frame-system-benchmarking = { workspace = true, optional = true}
 frame-benchmarking = { workspace = true, optional = true }
+frame-system-benchmarking = { workspace = true, optional = true }
 frame-try-runtime = { workspace = true, optional = true }
+hex-literal = { workspace = true, optional = true }
 serde = { workspace = true, optional = true }
-hex-literal = { workspace = true, optional = true }
 
 ################################################################################
 # Test dependencies
modifiedruntime/opal/src/lib.rsdiffbeforeafterboth
--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -45,6 +45,7 @@
 
 pub const RUNTIME_NAME: &str = "opal";
 pub const TOKEN_SYMBOL: &str = "OPL";
+pub const DECIMALS: u8 = 18;
 
 /// This runtime version.
 pub const VERSION: RuntimeVersion = RuntimeVersion {
modifiedruntime/quartz/Cargo.tomldiffbeforeafterboth
--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -22,6 +22,7 @@
 pov-estimate = []
 quartz-runtime = ['app-promotion', 'collator-selection', 'foreign-assets', 'preimage', 'refungible']
 runtime-benchmarks = [
+	"pallet-preimage/runtime-benchmarks",
 	'cumulus-pallet-parachain-system/runtime-benchmarks',
 	'frame-benchmarking',
 	'frame-support/runtime-benchmarks',
@@ -42,7 +43,6 @@
 	'pallet-inflation/runtime-benchmarks',
 	'pallet-maintenance/runtime-benchmarks',
 	'pallet-nonfungible/runtime-benchmarks',
-	"pallet-preimage/runtime-benchmarks",
 	'pallet-refungible/runtime-benchmarks',
 	'pallet-structure/runtime-benchmarks',
 	'pallet-timestamp/runtime-benchmarks',
@@ -66,13 +66,14 @@
 	'frame-try-runtime/std',
 	'pallet-aura/std',
 	'pallet-balances/std',
+	'pallet-balances-adapter/std',
 	# 'pallet-contracts/std',
 	# 'pallet-contracts-primitives/std',
 	# 'pallet-contracts-rpc-runtime-api/std',
 	# 'pallet-contract-helpers/std',
-	"pallet-preimage/std",
 	"pallet-authorship/std",
 	"pallet-identity/std",
+	"pallet-preimage/std",
 	"pallet-session/std",
 	"sp-consensus-aura/std",
 	'app-promotion-rpc/std',
@@ -127,8 +128,8 @@
 	"orml-tokens/std",
 	"orml-traits/std",
 	"orml-vesting/std",
+	"orml-xcm-support/std",
 	"orml-xtokens/std",
-	"orml-xcm-support/std",
 	"pallet-foreign-assets/std",
 	"pallet-maintenance/std",
 ]
@@ -136,8 +137,8 @@
 	"pallet-authorship/try-runtime",
 	"pallet-collator-selection/try-runtime",
 	"pallet-identity/try-runtime",
+	"pallet-preimage/try-runtime",
 	"pallet-session/try-runtime",
-	"pallet-preimage/try-runtime",
 	'cumulus-pallet-aura-ext/try-runtime',
 	'cumulus-pallet-dmp-queue/try-runtime',
 	'cumulus-pallet-parachain-system/try-runtime',
@@ -154,6 +155,7 @@
 	'pallet-app-promotion/try-runtime',
 	'pallet-aura/try-runtime',
 	'pallet-balances/try-runtime',
+	'pallet-balances-adapter/try-runtime',
 	'pallet-charge-transaction/try-runtime',
 	'pallet-common/try-runtime',
 	'pallet-configuration/try-runtime',
@@ -208,8 +210,8 @@
 orml-tokens = { workspace = true }
 orml-traits = { workspace = true }
 orml-vesting = { workspace = true }
+orml-xcm-support = { workspace = true }
 orml-xtokens = { workspace = true }
-orml-xcm-support = { workspace = true }
 pallet-aura = { workspace = true }
 pallet-authorship = { workspace = true }
 pallet-balances = { features = ["insecure_zero_ed"], workspace = true }
@@ -246,6 +248,7 @@
 fp-evm = { workspace = true }
 log = { workspace = true }
 pallet-app-promotion = { workspace = true }
+pallet-balances-adapter = { workspace = true }
 pallet-collator-selection = { workspace = true }
 pallet-common = { workspace = true }
 pallet-configuration = { workspace = true }
@@ -283,11 +286,11 @@
 ################################################################################
 # Optional dependencies
 
+frame-benchmarking = { workspace = true, optional = true }
 frame-system-benchmarking = { workspace = true, optional = true }
-frame-benchmarking = { workspace = true, optional = true }
 frame-try-runtime = { workspace = true, optional = true }
+hex-literal = { workspace = true, optional = true }
 serde = { workspace = true, optional = true }
-hex-literal = { workspace = true, optional = true }
 
 
 ################################################################################
modifiedruntime/quartz/src/lib.rsdiffbeforeafterboth
--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -48,6 +48,7 @@
 #[cfg(not(feature = "become-sapphire"))]
 pub const RUNTIME_NAME: &str = "quartz";
 pub const TOKEN_SYMBOL: &str = "QTZ";
+pub const DECIMALS: u8 = 18;
 
 /// This runtime version.
 pub const VERSION: RuntimeVersion = RuntimeVersion {
modifiedruntime/tests/Cargo.tomldiffbeforeafterboth
--- a/runtime/tests/Cargo.toml
+++ b/runtime/tests/Cargo.toml
@@ -26,6 +26,7 @@
 pallet-ethereum = { workspace = true }
 pallet-evm = { workspace = true }
 
+pallet-balances-adapter = { workspace = true }
 pallet-common = { workspace = true }
 pallet-fungible = { workspace = true }
 pallet-nonfungible = { workspace = true }
@@ -41,5 +42,3 @@
 evm-coder = { workspace = true }
 up-sponsorship = { workspace = true }
 xcm = { workspace = true }
-pallet-xcm = { workspace = true }
-pallet-configuration = { workspace = true }
modifiedruntime/tests/src/lib.rsdiffbeforeafterboth
--- a/runtime/tests/src/lib.rs
+++ b/runtime/tests/src/lib.rs
@@ -19,7 +19,7 @@
 use sp_core::{H160, H256, U256};
 use frame_support::{
 	parameter_types,
-	traits::{Everything, ConstU32, ConstU64},
+	traits::{Everything, ConstU32, ConstU64, Currency},
 	weights::IdentityFee,
 	pallet_prelude::Weight,
 };
@@ -266,6 +266,19 @@
 impl pallet_nonfungible::Config for Test {
 	type WeightInfo = ();
 }
+parameter_types! {
+	pub const Decimals: u8 = 18;
+	pub Name: String = "Test".to_string();
+	pub Symbol: String = "TST".to_string();
+}
+impl pallet_balances_adapter::Config for Test {
+	type Currency = Balances;
+	type CurrencyBalance = <Balances as Currency<Self::AccountId>>::Balance;
+	type Decimals = Decimals;
+	type Name = Name;
+	type Symbol = Symbol;
+	type WeightInfo = ();
+}
 
 parameter_types! {
 	// 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f
modifiedruntime/unique/Cargo.tomldiffbeforeafterboth
--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -20,6 +20,7 @@
 limit-testing = ['pallet-unique/limit-testing', 'up-data-structs/limit-testing']
 pov-estimate = []
 runtime-benchmarks = [
+	"pallet-preimage/runtime-benchmarks",
 	'frame-benchmarking',
 	'frame-support/runtime-benchmarks',
 	'frame-system-benchmarking',
@@ -39,7 +40,6 @@
 	'pallet-inflation/runtime-benchmarks',
 	'pallet-maintenance/runtime-benchmarks',
 	'pallet-nonfungible/runtime-benchmarks',
-	"pallet-preimage/runtime-benchmarks",
 	'pallet-refungible/runtime-benchmarks',
 	'pallet-structure/runtime-benchmarks',
 	'pallet-timestamp/runtime-benchmarks',
@@ -68,9 +68,9 @@
 	# 'pallet-contracts-primitives/std',
 	# 'pallet-contracts-rpc-runtime-api/std',
 	# 'pallet-contract-helpers/std',
-	"pallet-preimage/std",
 	"pallet-authorship/std",
 	"pallet-identity/std",
+	"pallet-preimage/std",
 	"pallet-session/std",
 	"sp-consensus-aura/std",
 	'app-promotion-rpc/std',
@@ -78,6 +78,7 @@
 	'fp-rpc/std',
 	'fp-self-contained/std',
 	'pallet-app-promotion/std',
+	'pallet-balances-adapter/std',
 	'pallet-base-fee/std',
 	'pallet-charge-transaction/std',
 	'pallet-collator-selection/std',
@@ -124,8 +125,8 @@
 	"orml-tokens/std",
 	"orml-traits/std",
 	"orml-vesting/std",
+	"orml-xcm-support/std",
 	"orml-xtokens/std",
-	"orml-xcm-support/std",
 	"pallet-foreign-assets/std",
 	"pallet-maintenance/std",
 ]
@@ -134,8 +135,8 @@
 	"pallet-authorship/try-runtime",
 	"pallet-collator-selection/try-runtime",
 	"pallet-identity/try-runtime",
+	"pallet-preimage/try-runtime",
 	"pallet-session/try-runtime",
-	"pallet-preimage/try-runtime",
 	'cumulus-pallet-aura-ext/try-runtime',
 	'cumulus-pallet-dmp-queue/try-runtime',
 	'cumulus-pallet-parachain-system/try-runtime',
@@ -152,6 +153,7 @@
 	'pallet-app-promotion/try-runtime',
 	'pallet-aura/try-runtime',
 	'pallet-balances/try-runtime',
+	'pallet-balances-adapter/try-runtime',
 	'pallet-charge-transaction/try-runtime',
 	'pallet-common/try-runtime',
 	'pallet-configuration/try-runtime',
@@ -207,8 +209,8 @@
 orml-tokens = { workspace = true }
 orml-traits = { workspace = true }
 orml-vesting = { workspace = true }
+orml-xcm-support = { workspace = true }
 orml-xtokens = { workspace = true }
-orml-xcm-support = { workspace = true }
 pallet-aura = { workspace = true }
 pallet-authorship = { workspace = true }
 pallet-balances = { features = ["insecure_zero_ed"], workspace = true }
@@ -244,6 +246,7 @@
 derivative = { workspace = true }
 log = { workspace = true }
 pallet-app-promotion = { workspace = true }
+pallet-balances-adapter = { workspace = true }
 pallet-collator-selection = { workspace = true }
 pallet-common = { workspace = true }
 pallet-configuration = { workspace = true }
@@ -282,11 +285,11 @@
 ################################################################################
 # Optional dependencies
 
+frame-benchmarking = { workspace = true, optional = true }
 frame-system-benchmarking = { workspace = true, optional = true }
-frame-benchmarking = { workspace = true, optional = true }
 frame-try-runtime = { workspace = true, optional = true }
+hex-literal = { workspace = true, optional = true }
 serde = { workspace = true, optional = true }
-hex-literal = { workspace = true, optional = true }
 
 ################################################################################
 # Test dependencies
modifiedruntime/unique/src/lib.rsdiffbeforeafterboth
--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -45,6 +45,7 @@
 
 pub const RUNTIME_NAME: &str = "unique";
 pub const TOKEN_SYMBOL: &str = "UNQ";
+pub const DECIMALS: u8 = 18;
 
 /// This runtime version.
 pub const VERSION: RuntimeVersion = RuntimeVersion {
modifiedtests/.eslintrc.jsondiffbeforeafterboth
--- a/tests/.eslintrc.json
+++ b/tests/.eslintrc.json
@@ -86,6 +86,14 @@
         "array-bracket-spacing": "warn",
         "template-curly-spacing": "warn",
         "space-in-parens": "warn",
+        "arrow-body-style": ["warn", "as-needed"],
+        "no-restricted-syntax": [
+            "warn",
+            {
+                "message": "toHuman results in horrible, hard to debug conversions with no stability guarantees, use Codec/at least .toJson instead",
+                "selector": "MemberExpression > Identifier[name=\"toHuman\"]"
+            }
+        ],
         "@typescript-eslint/naming-convention": [
             "warn",
             {
modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -39,12 +39,14 @@
     "testParallelFull": "yarn testParallel && yarn testSequential",
     "testParallel": "yarn _testParallel './src/**/*.test.ts'",
     "testSequential": "yarn _test './src/**/*.seqtest.ts'",
-    "testStructure": "yarn setup && yarn _test ./**/nesting/*.*test.ts",
-    "testEth": "yarn setup && yarn _test './**/eth/**/*.*test.ts'",
-    "testEthNesting": "yarn setup && yarn _test './**/eth/nesting/**/*.*test.ts'",
-    "testEthFractionalizer": "yarn setup && yarn _test './**/eth/fractionalizer/**/*.*test.ts'",
-    "testEthMarketplace": "yarn setup && yarn _test './**/eth/marketplace/**/*.*test.ts'",
-    "testEvent": "yarn setup && yarn _test ./src/check-event/*.*test.ts",
+    "testStructure": "yarn _test ./**/nesting/*.*test.ts",
+    "testEth": "yarn _test './**/eth/**/*.*test.ts'",
+    "testEthNesting": "yarn _test './**/eth/nesting/**/*.*test.ts'",
+    "testEthFractionalizer": "yarn _test './**/eth/fractionalizer/**/*.*test.ts'",
+    "testEthMarketplace": "yarn _test './**/eth/marketplace/**/*.*test.ts'",
+    "testSub": "yarn _test './**/sub/**/*.*test.ts'",
+    "testSubNesting": "yarn _test './**/sub/nesting/**/*.*test.ts'",
+    "testEvent": "yarn _test ./src/check-event/*.*test.ts",
     "testEthPayable": "yarn _test './**/eth/payable.test.ts'",
     "testEvmCoder": "yarn _test './**/eth/evmCoder.test.ts'",
     "testNesting": "yarn _test ./**/nest.test.ts",
modifiedtests/src/addCollectionAdmin.test.tsdiffbeforeafterboth
--- a/tests/src/addCollectionAdmin.test.ts
+++ b/tests/src/addCollectionAdmin.test.ts
@@ -16,6 +16,7 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import {itSub, usingPlaygrounds, expect} from './util';
+import {NON_EXISTENT_COLLECTION_ID} from './util/playgrounds/types';
 
 describe('Integration Test addCollectionAdmin(collection_id, new_admin_id):', () => {
   let donor: IKeyringPair;
@@ -82,7 +83,7 @@
 
   itSub("Can't add collection admin of not existing collection.", async ({helper}) => {
     const [alice, bob] = await helper.arrange.createAccounts([10n, 10n, 10n], donor);
-    const collectionId = (1 << 32) - 1;
+    const collectionId = NON_EXISTENT_COLLECTION_ID;
 
     await expect(helper.collection.addAdmin(alice, collectionId, {Substrate: bob.address})).to.be.rejectedWith(/common\.CollectionNotFound/);
 
modifiedtests/src/allowLists.test.tsdiffbeforeafterboth
--- a/tests/src/allowLists.test.ts
+++ b/tests/src/allowLists.test.ts
@@ -16,7 +16,7 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import {usingPlaygrounds, expect, itSub} from './util';
-import {ICollectionPermissions} from './util/playgrounds/types';
+import {ICollectionPermissions, NON_EXISTENT_COLLECTION_ID} from './util/playgrounds/types';
 
 describe('Integration Test ext. Allow list tests', () => {
   let alice: IKeyringPair;
@@ -60,7 +60,7 @@
 
   describe('Negative', () => {
     itSub('Nobody can add address to allow list of non-existing collection', async ({helper}) => {
-      const collectionId = (1<<32) - 1;
+      const collectionId = NON_EXISTENT_COLLECTION_ID;
       await expect(helper.nft.addToAllowList(bob, collectionId, {Substrate: charlie.address}))
         .to.be.rejectedWith(/common\.CollectionNotFound/);
     });
@@ -140,7 +140,7 @@
     });
 
     itSub('Nobody can remove address from allow list of non-existing collection', async ({helper}) => {
-      const collectionId = (1<<32) - 1;
+      const collectionId = NON_EXISTENT_COLLECTION_ID;
       await expect(helper.collection.removeFromAllowList(bob, collectionId, {Substrate: charlie.address}))
         .to.be.rejectedWith(/common\.CollectionNotFound/);
     });
modifiedtests/src/benchmarks/utils/common.tsdiffbeforeafterboth
--- a/tests/src/benchmarks/utils/common.ts
+++ b/tests/src/benchmarks/utils/common.ts
@@ -91,4 +91,4 @@
     await collection.setTokenPropertyPermissions(donor, permissions);
 
   return collection;
-}
\ No newline at end of file
+}
modifiedtests/src/change-collection-owner.test.tsdiffbeforeafterboth
--- a/tests/src/change-collection-owner.test.ts
+++ b/tests/src/change-collection-owner.test.ts
@@ -16,6 +16,7 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import {usingPlaygrounds, expect, itSub} from './util';
+import {NON_EXISTENT_COLLECTION_ID} from './util/playgrounds/types';
 
 describe('Integration Test changeCollectionOwner(collection_id, new_owner):', () => {
   let alice: IKeyringPair;
@@ -127,7 +128,7 @@
   });
 
   itSub('Can\'t change owner of a non-existing collection.', async ({helper}) => {
-    const collectionId = (1 << 32) - 1;
+    const collectionId = NON_EXISTENT_COLLECTION_ID;
     const changeOwnerTx = () => helper.collection.changeOwner(bob, collectionId, bob.address);
     await expect(changeOwnerTx()).to.be.rejectedWith(/common\.CollectionNotFound/);
   });
modifiedtests/src/confirmSponsorship.test.tsdiffbeforeafterboth
--- a/tests/src/confirmSponsorship.test.ts
+++ b/tests/src/confirmSponsorship.test.ts
@@ -16,6 +16,7 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import {usingPlaygrounds, expect, itSub, Pallets} from './util';
+import {NON_EXISTENT_COLLECTION_ID} from './util/playgrounds/types';
 
 async function setSponsorHelper(collection: any, signer: IKeyringPair, sponsorAddress: string) {
   await collection.setSponsor(signer, sponsorAddress);
@@ -198,7 +199,7 @@
   });
 
   itSub('(!negative test!) Confirm sponsorship for a collection that never existed', async ({helper}) => {
-    const collectionId = (1 << 32) - 1;
+    const collectionId = NON_EXISTENT_COLLECTION_ID;
     const confirmSponsorshipTx = () => helper.collection.confirmSponsorship(bob, collectionId);
     await expect(confirmSponsorshipTx()).to.be.rejectedWith(/common\.CollectionNotFound/);
   });
modifiedtests/src/creditFeesToTreasury.seqtest.tsdiffbeforeafterboth
--- a/tests/src/creditFeesToTreasury.seqtest.ts
+++ b/tests/src/creditFeesToTreasury.seqtest.ts
@@ -88,7 +88,7 @@
     expect(treasuryIncrease).to.be.equal(fee);
   });
 
-  itSub.only('Treasury balance increased by failed tx fee', async ({helper}) => {
+  itSub('Treasury balance increased by failed tx fee', async ({helper}) => {
     const api = helper.getApi();
     await helper.wait.newBlocks(1);
 
addedtests/src/eth/abi/nativeFungible.jsondiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/abi/nativeFungible.json
@@ -0,0 +1,201 @@
+[
+  {
+    "anonymous": false,
+    "inputs": [
+      {
+        "indexed": true,
+        "internalType": "address",
+        "name": "owner",
+        "type": "address"
+      },
+      {
+        "indexed": true,
+        "internalType": "address",
+        "name": "spender",
+        "type": "address"
+      },
+      {
+        "indexed": false,
+        "internalType": "uint256",
+        "name": "value",
+        "type": "uint256"
+      }
+    ],
+    "name": "Approval",
+    "type": "event"
+  },
+  {
+    "anonymous": false,
+    "inputs": [
+      {
+        "indexed": true,
+        "internalType": "address",
+        "name": "from",
+        "type": "address"
+      },
+      {
+        "indexed": true,
+        "internalType": "address",
+        "name": "to",
+        "type": "address"
+      },
+      {
+        "indexed": false,
+        "internalType": "uint256",
+        "name": "value",
+        "type": "uint256"
+      }
+    ],
+    "name": "Transfer",
+    "type": "event"
+  },
+  {
+    "inputs": [
+      { "internalType": "address", "name": "owner", "type": "address" },
+      { "internalType": "address", "name": "spender", "type": "address" }
+    ],
+    "name": "allowance",
+    "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      { "internalType": "address", "name": "spender", "type": "address" },
+      { "internalType": "uint256", "name": "amount", "type": "uint256" }
+    ],
+    "name": "approve",
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      { "internalType": "address", "name": "owner", "type": "address" }
+    ],
+    "name": "balanceOf",
+    "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      {
+        "components": [
+          { "internalType": "address", "name": "eth", "type": "address" },
+          { "internalType": "uint256", "name": "sub", "type": "uint256" }
+        ],
+        "internalType": "struct CrossAddress",
+        "name": "owner",
+        "type": "tuple"
+      }
+    ],
+    "name": "balanceOfCross",
+    "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [],
+    "name": "decimals",
+    "outputs": [{ "internalType": "uint8", "name": "", "type": "uint8" }],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [],
+    "name": "name",
+    "outputs": [{ "internalType": "string", "name": "", "type": "string" }],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      { "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
+    ],
+    "name": "supportsInterface",
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [],
+    "name": "symbol",
+    "outputs": [{ "internalType": "string", "name": "", "type": "string" }],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [],
+    "name": "totalSupply",
+    "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      { "internalType": "address", "name": "to", "type": "address" },
+      { "internalType": "uint256", "name": "amount", "type": "uint256" }
+    ],
+    "name": "transfer",
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      {
+        "components": [
+          { "internalType": "address", "name": "eth", "type": "address" },
+          { "internalType": "uint256", "name": "sub", "type": "uint256" }
+        ],
+        "internalType": "struct CrossAddress",
+        "name": "to",
+        "type": "tuple"
+      },
+      { "internalType": "uint256", "name": "amount", "type": "uint256" }
+    ],
+    "name": "transferCross",
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      { "internalType": "address", "name": "from", "type": "address" },
+      { "internalType": "address", "name": "to", "type": "address" },
+      { "internalType": "uint256", "name": "amount", "type": "uint256" }
+    ],
+    "name": "transferFrom",
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      {
+        "components": [
+          { "internalType": "address", "name": "eth", "type": "address" },
+          { "internalType": "uint256", "name": "sub", "type": "uint256" }
+        ],
+        "internalType": "struct CrossAddress",
+        "name": "from",
+        "type": "tuple"
+      },
+      {
+        "components": [
+          { "internalType": "address", "name": "eth", "type": "address" },
+          { "internalType": "uint256", "name": "sub", "type": "uint256" }
+        ],
+        "internalType": "struct CrossAddress",
+        "name": "to",
+        "type": "tuple"
+      },
+      { "internalType": "uint256", "name": "amount", "type": "uint256" }
+    ],
+    "name": "transferFromCross",
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  }
+]
addedtests/src/eth/api/UniqueNativeFungible.soldiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/api/UniqueNativeFungible.sol
@@ -0,0 +1,89 @@
+// SPDX-License-Identifier: OTHER
+// This code is automatically generated
+
+pragma solidity >=0.8.0 <0.9.0;
+
+/// @dev common stubs holder
+interface Dummy {
+
+}
+
+interface ERC165 is Dummy {
+	function supportsInterface(bytes4 interfaceID) external view returns (bool);
+}
+
+/// @dev the ERC-165 identifier for this interface is 0x1313556c
+interface ERC20UniqueExtensions is Dummy, ERC165 {
+	/// @dev EVM selector for this function is: 0xec069398,
+	///  or in textual repr: balanceOfCross((address,uint256))
+	function balanceOfCross(CrossAddress memory owner) external view returns (uint256);
+
+	/// @dev EVM selector for this function is: 0x2ada85ff,
+	///  or in textual repr: transferCross((address,uint256),uint256)
+	function transferCross(CrossAddress memory to, uint256 amount) external returns (bool);
+
+	/// @dev EVM selector for this function is: 0xd5cf430b,
+	///  or in textual repr: transferFromCross((address,uint256),(address,uint256),uint256)
+	function transferFromCross(
+		CrossAddress memory from,
+		CrossAddress memory to,
+		uint256 amount
+	) external returns (bool);
+}
+
+/// Cross account struct
+struct CrossAddress {
+	address eth;
+	uint256 sub;
+}
+
+/// @dev inlined interface
+interface ERC20Events {
+	event Transfer(address indexed from, address indexed to, uint256 value);
+	event Approval(address indexed owner, address indexed spender, uint256 value);
+}
+
+/// @dev the ERC-165 identifier for this interface is 0x942e8b22
+interface ERC20 is Dummy, ERC165, ERC20Events {
+	/// @dev EVM selector for this function is: 0xdd62ed3e,
+	///  or in textual repr: allowance(address,address)
+	function allowance(address owner, address spender) external view returns (uint256);
+
+	/// @dev EVM selector for this function is: 0x095ea7b3,
+	///  or in textual repr: approve(address,uint256)
+	function approve(address spender, uint256 amount) external returns (bool);
+
+	/// @dev EVM selector for this function is: 0x70a08231,
+	///  or in textual repr: balanceOf(address)
+	function balanceOf(address owner) external view returns (uint256);
+
+	/// @dev EVM selector for this function is: 0x313ce567,
+	///  or in textual repr: decimals()
+	function decimals() external view returns (uint8);
+
+	/// @dev EVM selector for this function is: 0x06fdde03,
+	///  or in textual repr: name()
+	function name() external view returns (string memory);
+
+	/// @dev EVM selector for this function is: 0x95d89b41,
+	///  or in textual repr: symbol()
+	function symbol() external view returns (string memory);
+
+	/// @dev EVM selector for this function is: 0x18160ddd,
+	///  or in textual repr: totalSupply()
+	function totalSupply() external view returns (uint256);
+
+	/// @dev EVM selector for this function is: 0xa9059cbb,
+	///  or in textual repr: transfer(address,uint256)
+	function transfer(address to, uint256 amount) external returns (bool);
+
+	/// @dev EVM selector for this function is: 0x23b872dd,
+	///  or in textual repr: transferFrom(address,address,uint256)
+	function transferFrom(
+		address from,
+		address to,
+		uint256 amount
+	) external returns (bool);
+}
+
+interface UniqueNativeFungible is Dummy, ERC165, ERC20, ERC20UniqueExtensions {}
modifiedtests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth
--- a/tests/src/eth/collectionSponsoring.test.ts
+++ b/tests/src/eth/collectionSponsoring.test.ts
@@ -18,7 +18,7 @@
 import {Pallets, requirePalletsOrSkip, usingPlaygrounds} from '../util/index';
 import {itEth, expect} from './util';
 
-describe.only('evm nft collection sponsoring', () => {
+describe('evm nft collection sponsoring', () => {
   let donor: IKeyringPair;
   let alice: IKeyringPair;
   let nominal: bigint;
@@ -319,7 +319,7 @@
   });
 });
 
-describe.only('evm RFT collection sponsoring', () => {
+describe('evm RFT collection sponsoring', () => {
   let donor: IKeyringPair;
   let alice: IKeyringPair;
   let nominal: bigint;
modifiedtests/src/eth/createFTCollection.seqtest.tsdiffbeforeafterboth
--- a/tests/src/eth/createFTCollection.seqtest.ts
+++ b/tests/src/eth/createFTCollection.seqtest.ts
@@ -20,7 +20,7 @@
 
 const DECIMALS = 18;
 
-describe.only('Create FT collection from EVM', () => {
+describe('Create FT collection from EVM', () => {
   let donor: IKeyringPair;
 
   before(async function() {
modifiedtests/src/eth/createFTCollection.test.tsdiffbeforeafterboth
--- a/tests/src/eth/createFTCollection.test.ts
+++ b/tests/src/eth/createFTCollection.test.ts
@@ -22,7 +22,7 @@
 
 const DECIMALS = 18;
 
-describe.only('Create FT collection from EVM', () => {
+describe('Create FT collection from EVM', () => {
   let donor: IKeyringPair;
 
   before(async function() {
@@ -129,7 +129,7 @@
   });
 });
 
-describe.only('(!negative tests!) Create FT collection from EVM', () => {
+describe('(!negative tests!) Create FT collection from EVM', () => {
   let donor: IKeyringPair;
   let nominal: bigint;
 
modifiedtests/src/eth/createNFTCollection.test.tsdiffbeforeafterboth
--- a/tests/src/eth/createNFTCollection.test.ts
+++ b/tests/src/eth/createNFTCollection.test.ts
@@ -21,7 +21,7 @@
 import {COLLECTION_HELPER} from '../util';
 
 
-describe.only('Create NFT collection from EVM', () => {
+describe('Create NFT collection from EVM', () => {
   let donor: IKeyringPair;
 
   before(async function () {
@@ -143,7 +143,7 @@
   });
 });
 
-describe.only('(!negative tests!) Create NFT collection from EVM', () => {
+describe('(!negative tests!) Create NFT collection from EVM', () => {
   let donor: IKeyringPair;
   let nominal: bigint;
 
modifiedtests/src/eth/createRFTCollection.test.tsdiffbeforeafterboth
--- a/tests/src/eth/createRFTCollection.test.ts
+++ b/tests/src/eth/createRFTCollection.test.ts
@@ -21,7 +21,7 @@
 import {CollectionLimitField} from './util/playgrounds/types';
 
 
-describe.only('Create RFT collection from EVM', () => {
+describe('Create RFT collection from EVM', () => {
   let donor: IKeyringPair;
 
   before(async function() {
@@ -154,7 +154,7 @@
   });
 });
 
-describe.only('(!negative tests!) Create RFT collection from EVM', () => {
+describe('(!negative tests!) Create RFT collection from EVM', () => {
   let donor: IKeyringPair;
   let nominal: bigint;
 
modifiedtests/src/eth/fractionalizer/fractionalizer.test.tsdiffbeforeafterboth
--- a/tests/src/eth/fractionalizer/fractionalizer.test.ts
+++ b/tests/src/eth/fractionalizer/fractionalizer.test.ts
@@ -80,7 +80,7 @@
 };
 
 
-describe.only('Fractionalizer contract usage', () => {
+describe('Fractionalizer contract usage', () => {
   let donor: IKeyringPair;
 
   before(async function() {
addedtests/src/eth/nativeFungible.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/nativeFungible.test.ts
@@ -0,0 +1,173 @@
+// Copyright 2019-2023 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {IKeyringPair} from '@polkadot/types/types';
+import {expect, itEth, usingEthPlaygrounds} from './util';
+import {UniqueHelper} from '../util/playgrounds/unique';
+
+describe('NativeFungible: ERC20 calls', () => {
+  let donor: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = await privateKey({url: import.meta.url});
+    });
+  });
+
+  itEth('approve()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const spender = helper.eth.createAccount();
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    await expect(contract.methods.approve(spender, 100).call({from: owner})).to.be.rejectedWith('Approve not supported');
+  });
+
+  itEth('balanceOf()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor, 123n);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const balance = await contract.methods.balanceOf(owner).call({from: owner});
+    expect(balance).to.be.eq('123000000000000000000');
+  });
+
+  itEth('decimals()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const realDecimals = (await helper.chain.getChainProperties().tokenDecimals)[0].toString();
+    const decimals = await contract.methods.decimals().call({from: owner});
+    expect(decimals).to.be.eq(realDecimals);
+  });
+
+  itEth('name()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const realName = await UniqueHelper.detectNetwork(helper.getApi());
+    const name = await contract.methods.name().call({from: owner});
+    expect(name).to.be.eq(realName);
+  });
+
+  itEth('symbol()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const realName = (await helper.chain.getChainProperties().tokenSymbol)[0];
+    const name = await contract.methods.symbol().call({from: owner});
+    expect(name).to.be.eq(realName);
+  });
+
+  itEth('totalSupply()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const totalSupplyEth = BigInt(await contract.methods.totalSupply().call({from: owner}));
+    const totalSupplySub = await helper.balance.getTotalIssuance();
+    expect(totalSupplyEth).to.be.eq(totalSupplySub);
+  });
+
+  itEth('transfer()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = await helper.eth.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const balanceOwnerBefore = await helper.balance.getEthereum(owner);
+    const balanceReceiverBefore = await helper.balance.getEthereum(receiver);
+
+    await contract.methods.transfer(receiver, 50).send({from: owner});
+
+    const balanceOwnerAfter = await helper.balance.getEthereum(owner);
+    const balanceReceiverAfter = await helper.balance.getEthereum(receiver);
+
+    expect(balanceOwnerBefore - 50n > balanceOwnerAfter).to.be.true;
+    expect(balanceReceiverBefore + 50n).to.be.equal(balanceReceiverAfter);
+  });
+
+  itEth('transferFrom()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = await helper.eth.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const balanceOwnerBefore = await helper.balance.getEthereum(owner);
+    const balanceReceiverBefore = await helper.balance.getEthereum(receiver);
+
+    await contract.methods.transferFrom(owner, receiver, 50).send({from: owner});
+
+    const balanceOwnerAfter = await helper.balance.getEthereum(owner);
+    const balanceReceiverAfter = await helper.balance.getEthereum(receiver);
+
+    expect(balanceOwnerBefore - 50n > balanceOwnerAfter).to.be.true;
+    expect(balanceReceiverBefore === balanceReceiverAfter - 50n).to.be.true;
+
+    await expect(contract.methods.transferFrom(receiver, receiver, 50).call({from: owner})).to.be.rejectedWith('ApprovedValueTooLow');
+  });
+});
+
+describe('NativeFungible: ERC20UniqueExtensions calls', () => {
+  let donor: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = await privateKey({url: import.meta.url});
+    });
+  });
+
+  itEth('transferCross()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = await helper.ethCrossAccount.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+
+    const balanceOwnerBefore = await helper.balance.getEthereum(owner);
+    const balanceReceiverBefore = await helper.balance.getEthereum(receiver.eth);
+
+    await contract.methods.transferCross(receiver, 50).send({from: owner});
+
+    const balanceOwnerAfter = await helper.balance.getEthereum(owner);
+    const balanceReceiverAfter = await helper.balance.getEthereum(receiver.eth);
+
+    expect(balanceOwnerBefore - 50n > balanceOwnerAfter).to.be.true;
+    expect(balanceReceiverBefore === balanceReceiverAfter - 50n).to.be.true;
+  });
+
+  itEth('transferFromCross()', async ({helper}) => {
+    const owner = await helper.ethCrossAccount.createAccountWithBalance(donor);
+    const receiver = await helper.ethCrossAccount.createAccountWithBalance(donor);
+    const collectionAddress = helper.ethAddress.fromCollectionId(0);
+    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner.eth);
+
+    const balanceOwnerBefore = await helper.balance.getEthereum(owner.eth);
+    const balanceReceiverBefore = await helper.balance.getEthereum(receiver.eth);
+
+    await contract.methods.transferFromCross(owner, receiver, 50).send({from: owner.eth});
+
+    const balanceOwnerAfter = await helper.balance.getEthereum(owner.eth);
+    const balanceReceiverAfter = await helper.balance.getEthereum(receiver.eth);
+
+    expect(balanceOwnerBefore - 50n > balanceOwnerAfter).to.be.true;
+    expect(balanceReceiverBefore === balanceReceiverAfter - 50n).to.be.true;
+
+    await expect(contract.methods.transferFromCross(receiver, receiver, 50).call({from: owner.eth})).to.be.rejectedWith('no permission');
+  });
+});
\ No newline at end of file
addedtests/src/eth/nativeRpc/estimateGas.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/nativeRpc/estimateGas.test.ts
@@ -0,0 +1,62 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {expect, itEth, usingEthPlaygrounds} from '../util';
+import {IKeyringPair} from '@polkadot/types/types';
+
+
+describe('Ethereum native RPC calls', () => {
+  let donor: IKeyringPair;
+  const NATIVE_TOKEN_ADDRESS = '0x17c4e6453cc49aaaaeaca894e6d9683e00000000';
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = await privateKey({url: import.meta.url});
+    });
+  });
+
+  itEth.skip('estimate gas', async ({helper}) => {
+    const BALANCE = 100n;
+    const BALANCE_TO_TRANSFER = 90n;
+
+    const owner = await helper.eth.createAccountWithBalance(donor, BALANCE);
+    const recepient = helper.eth.createAccount();
+
+    const web3 = helper.getWeb3();
+    // data: transfer(recepient, 90);
+    const data = web3.eth.abi.encodeFunctionCall({
+      name: 'transfer',
+      type: 'function',
+      inputs: [{
+        type: 'address',
+        name: 'to',
+      },{
+        type: 'uint256',
+        name: 'amount',
+      }],
+    }, [recepient, (BALANCE_TO_TRANSFER * (10n ** 18n)).toString()]);
+
+    const estimateGas = await web3.eth.estimateGas({
+      to: NATIVE_TOKEN_ADDRESS,
+      value: '0x0',
+      data,
+      from: owner,
+      maxFeePerGas: '0x14c9338c61d',
+    });
+
+    expect(estimateGas).to.be.greaterThan(40000).and.to.be.lessThan(60000);
+  });
+});
modifiedtests/src/eth/nesting/nest.test.tsdiffbeforeafterboth
--- a/tests/src/eth/nesting/nest.test.ts
+++ b/tests/src/eth/nesting/nest.test.ts
@@ -187,4 +187,84 @@
         .call()).to.be.rejectedWith('SourceCollectionIsNotAllowedToNest');
     });
   });
+
+  describe('Fungible', () => {
+    async function createFungibleCollection(helper: EthUniqueHelper, owner: string, mode: 'ft' | 'native ft') {
+      if (mode === 'ft') {
+        const {collectionAddress} = await helper.eth.createFungibleCollection(owner, '', 18, '', '');
+        const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+        await contract.methods.mint(owner, 100n).send({from: owner});
+        return {collectionAddress, contract};
+      }
+
+      // native ft
+      const collectionAddress = helper.ethAddress.fromCollectionId(0);
+      const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+      return {collectionAddress, contract};
+    }
+
+    [
+      {mode: 'ft' as const},
+      {mode: 'native ft' as const},
+    ].map(testCase => {
+      itEth(`Allow nest [${testCase.mode}]`, async ({helper}) => {
+        const owner = await helper.eth.createAccountWithBalance(donor);
+        const {collectionId: targetCollectionId, contract: targetContract} = await createNestingCollection(helper, owner);
+        const {contract: ftContract} = await createFungibleCollection(helper, owner, testCase.mode);
+
+        const mintingTargetTokenIdResult = await targetContract.methods.mint(owner).send({from: owner});
+        const targetTokenId = mintingTargetTokenIdResult.events.Transfer.returnValues.tokenId;
+        const targetTokenAddress = helper.ethAddress.fromTokenId(targetCollectionId, targetTokenId);
+
+        await ftContract.methods.transfer(targetTokenAddress, 10n).send({from: owner});
+        expect(await ftContract.methods.balanceOf(targetTokenAddress).call({from: owner})).to.be.equal('10');
+      });
+    });
+
+    [
+      {mode: 'ft' as const},
+      {mode: 'native ft' as const},
+    ].map(testCase => {
+      itEth(`Allow partial/full unnest [${testCase.mode}]`, async ({helper}) => {
+        const owner = await helper.eth.createAccountWithBalance(donor);
+        const {collectionId: targetCollectionId, contract: targetContract} = await createNestingCollection(helper, owner);
+        const {contract: ftContract} = await createFungibleCollection(helper, owner, testCase.mode);
+
+        const mintingTargetTokenIdResult = await targetContract.methods.mint(owner).send({from: owner});
+        const targetTokenId = mintingTargetTokenIdResult.events.Transfer.returnValues.tokenId;
+        const targetTokenAddress = helper.ethAddress.fromTokenId(targetCollectionId, targetTokenId);
+
+        await ftContract.methods.transfer(targetTokenAddress, 10n).send({from: owner});
+
+        await ftContract.methods.transferFrom(targetTokenAddress, owner, 5n).send({from: owner});
+        expect(await ftContract.methods.balanceOf(targetTokenAddress).call({from: owner})).to.be.equal('5');
+
+        await ftContract.methods.transferFrom(targetTokenAddress, owner, 5n).send({from: owner});
+        expect(await ftContract.methods.balanceOf(targetTokenAddress).call({from: owner})).to.be.equal('0');
+      });
+    });
+
+    [
+      {mode: 'ft' as const},
+      {mode: 'native ft' as const},
+    ].map(testCase => {
+      itEth(`Disallow nest into collection without nesting permission [${testCase.mode}] (except for native fungible collection)`, async ({helper}) => {
+        const owner = await helper.eth.createAccountWithBalance(donor);
+        const {collectionId: targetCollectionId, contract: targetContract} = await createNestingCollection(helper, owner);
+        await targetContract.methods.setCollectionNesting(false).send({from: owner});
+
+        const {contract: ftContract} = await createFungibleCollection(helper, owner, testCase.mode);
+
+        const mintingTargetTokenIdResult = await targetContract.methods.mint(owner).send({from: owner});
+        const targetTokenId = mintingTargetTokenIdResult.events.Transfer.returnValues.tokenId;
+        const targetTokenAddress = helper.ethAddress.fromTokenId(targetCollectionId, targetTokenId);
+
+        if (testCase.mode === 'ft') {
+          await expect(ftContract.methods.transfer(targetTokenAddress, 10n).call({from: owner})).to.be.rejectedWith('UserIsNotAllowedToNest');
+        } else {
+          await expect(ftContract.methods.transfer(targetTokenAddress, 10n).call({from: owner})).to.be.not.rejected;
+        }
+      });
+    });
+  });
 });
modifiedtests/src/eth/nonFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -929,7 +929,7 @@
     });
   });
 
-  itEth.only('Returns collection name', async ({helper}) => {
+  itEth('Returns collection name', async ({helper}) => {
     // FIXME: should not have balance to use .call()
     const caller = await helper.eth.createAccountWithBalance(donor);
     const tokenPropertyPermissions = [{
modifiedtests/src/eth/payable.test.tsdiffbeforeafterboth
--- a/tests/src/eth/payable.test.ts
+++ b/tests/src/eth/payable.test.ts
@@ -41,7 +41,7 @@
     expect(await contract.methods.getCollected().call()).to.be.equal('10000');
   });
 
-  itEth.only('Evm contract can receive wei from substrate account', async ({helper}) => {
+  itEth('Evm contract can receive wei from substrate account', async ({helper}) => {
     const deployer = await helper.eth.createAccountWithBalance(donor);
     const contract = await helper.eth.deployCollectorContract(deployer);
     const [alice] = await helper.arrange.createAccounts([40n], donor);
modifiedtests/src/eth/reFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -679,7 +679,7 @@
     });
   });
 
-  itEth.only('Returns collection name', async ({helper}) => {
+  itEth('Returns collection name', async ({helper}) => {
     // FIXME: should not have balance to use .call()
     const caller = await helper.eth.createAccountWithBalance(alice);
     const tokenPropertyPermissions = [{
modifiedtests/src/eth/tokenProperties.test.tsdiffbeforeafterboth
--- a/tests/src/eth/tokenProperties.test.ts
+++ b/tests/src/eth/tokenProperties.test.ts
@@ -314,7 +314,7 @@
       expect(result.length).to.equal(0);
     }));
 
-  itEth.only('Can be read', async({helper}) => {
+  itEth('Can be read', async({helper}) => {
     // FIXME: User with no balance should be able to call
     const caller = await helper.eth.createAccountWithBalance(alice);
     const collection = await helper.nft.mintCollection(alice, {
modifiedtests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -22,6 +22,7 @@
 
 // Native contracts ABI
 import collectionHelpersAbi from '../../abi/collectionHelpers.json' assert {type: 'json'};
+import nativeFungibleAbi from '../../abi/nativeFungible.json' assert {type: 'json'};
 import fungibleAbi from '../../abi/fungible.json' assert {type: 'json'};
 import fungibleDeprecatedAbi from '../../abi/fungibleDeprecated.json' assert {type: 'json'};
 import nonFungibleAbi from '../../abi/nonFungible.json' assert {type: 'json'};
@@ -112,7 +113,6 @@
       data: object,
       from: signer,
       gas: gas ?? this.helper.eth.DEFAULT_GAS,
-      gasPrice: await this.getGasPrice(),
     });
     return await contract.deploy({data: object}).send({from: signer});
   }
@@ -121,30 +121,33 @@
 
 class NativeContractGroup extends EthGroupBase {
 
-  async contractHelpers(caller: string): Promise<Contract> {
+  contractHelpers(caller: string) {
     const web3 = this.helper.getWeb3();
     return new web3.eth.Contract(contractHelpersAbi as any, this.helper.getApi().consts.evmContractHelpers.contractAddress.toString(), {
       from: caller,
       gas: this.helper.eth.DEFAULT_GAS,
-      gasPrice: await this.getGasPrice(),
     });
   }
 
-  async collectionHelpers(caller: string) {
+  collectionHelpers(caller: string) {
     const web3 = this.helper.getWeb3();
     return new web3.eth.Contract(collectionHelpersAbi as any, this.helper.getApi().consts.common.contractAddress.toString(), {
       from: caller,
       gas: this.helper.eth.DEFAULT_GAS,
-      gasPrice: await this.getGasPrice(),
     });
   }
 
-  async collection(address: string, mode: TCollectionMode, caller?: string, mergeDeprecated = false) {
-    let abi = {
-      'nft': nonFungibleAbi,
-      'rft': refungibleAbi,
-      'ft': fungibleAbi,
-    }[mode];
+  collection(address: string, mode: TCollectionMode, caller?: string, mergeDeprecated = false) {
+    let abi;
+    if (address === this.helper.ethAddress.fromCollectionId(0)) {
+      abi = nativeFungibleAbi;
+    } else {
+      abi ={
+        'nft': nonFungibleAbi,
+        'rft': refungibleAbi,
+        'ft': fungibleAbi,
+      }[mode];
+    }
     if (mergeDeprecated) {
       const deprecated = {
         'nft': nonFungibleDeprecatedAbi,
@@ -156,7 +159,6 @@
     const web3 = this.helper.getWeb3();
     return new web3.eth.Contract(abi as any, address, {
       gas: this.helper.eth.DEFAULT_GAS,
-      gasPrice: await this.getGasPrice(),
       ...(caller ? {from: caller} : {}),
     });
   }
@@ -165,12 +167,11 @@
     return this.collection(this.helper.ethAddress.fromCollectionId(collectionId), mode, caller, mergeDeprecated);
   }
 
-  async rftToken(address: string, caller?: string, mergeDeprecated = false) {
+  rftToken(address: string, caller?: string, mergeDeprecated = false) {
     const web3 = this.helper.getWeb3();
     const abi = mergeDeprecated ? [...refungibleTokenAbi, ...refungibleTokenDeprecatedAbi] : refungibleTokenAbi;
     return new web3.eth.Contract(abi as any, address, {
       gas: this.helper.eth.DEFAULT_GAS,
-      gasPrice: await this.getGasPrice(),
       ...(caller ? {from: caller} : {}),
     });
   }
@@ -210,6 +211,7 @@
   async sendEVM(signer: IKeyringPair, contractAddress: string, abi: string, value: string, gasLimit?: number) {
     if (!gasLimit) gasLimit = this.DEFAULT_GAS;
     const web3 = this.helper.getWeb3();
+    // FIXME: can't send legacy transaction using tx.evm.call
     const gasPrice = await web3.eth.getGasPrice();
     // TODO: check execution status
     await this.helper.executeExtrinsic(
@@ -377,7 +379,7 @@
 class EthAddressGroup extends EthGroupBase {
   extractCollectionId(address: string): number {
     if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');
-    return parseInt(address.substr(address.length - 8), 16);
+    return parseInt(address.slice(address.length - 8), 16);
   }
 
   fromCollectionId(collectionId: number): string {
modifiedtests/src/maintenance.seqtest.tsdiffbeforeafterboth
--- a/tests/src/maintenance.seqtest.ts
+++ b/tests/src/maintenance.seqtest.ts
@@ -325,7 +325,7 @@
       expect(await helper.preimage.getPreimageInfo(preimageHashes[0])).to.have.property('unrequested');
     });
 
-    itSub.only('Does not allow execution of a preimage that would fail', async ({helper}) => {
+    itSub('Does not allow execution of a preimage that would fail', async ({helper}) => {
       const [zeroAccount] = await helper.arrange.createAccounts([0n], superuser);
 
       const preimage = helper.constructApiCall('api.tx.balances.forceTransfer', [
addedtests/src/nativeFungible.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/nativeFungible.test.ts
@@ -0,0 +1,221 @@
+// Copyright 2019-2023 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {IKeyringPair} from '@polkadot/types/types';
+import {expect, itSub, usingPlaygrounds} from './util';
+
+describe('Native fungible', () => {
+  let root: IKeyringPair;
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+
+  before(async () => {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      root = await privateKey('//Alice');
+      const donor = await privateKey({url: import.meta.url});
+      [alice, bob] = await helper.arrange.createAccounts([10n, 10n], donor);
+    });
+  });
+
+  itSub('destroy_collection()', async ({helper}) => {
+    const collection = helper.ft.getCollectionObject(0);
+    await expect(collection.burn(alice)).to.be.rejectedWith('common.UnsupportedOperation');
+    await expect(helper.executeExtrinsic(alice, 'api.tx.unique.destroyCollection', [0])).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('add_to_allow_list()', async ({helper}) => {
+    const collection = helper.ft.getCollectionObject(0);
+    await expect(collection.addToAllowList(alice, {Substrate: bob.address})).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('remove_from_allow_list()', async ({helper}) => {
+    const collection = helper.ft.getCollectionObject(0);
+    await expect(collection.removeFromAllowList(alice, {Substrate: bob.address})).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('change_collection_owner()', async ({helper}) => {
+    const collection = helper.ft.getCollectionObject(0);
+    await expect(collection.changeOwner(alice, bob.address)).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('add_collection_admin()', async ({helper}) => {
+    const collection = helper.ft.getCollectionObject(0);
+    await expect(collection.addAdmin(alice, {Substrate: bob.address})).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('remove_collection_admin()', async ({helper}) => {
+    const collection = helper.ft.getCollectionObject(0);
+    await expect(collection.removeAdmin(alice, {Substrate: bob.address})).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('set_collection_sponsor()', async ({helper}) => {
+    const collection = helper.ft.getCollectionObject(0);
+    await expect(collection.setSponsor(alice, bob.address)).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('confirm_sponsorship()', async ({helper}) => {
+    const collection = helper.ft.getCollectionObject(0);
+    await expect(collection.confirmSponsorship(alice)).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('remove_collection_sponsor()', async ({helper}) => {
+    const collection = helper.ft.getCollectionObject(0);
+    await expect(collection.removeSponsor(alice)).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('create_item()', async ({helper}) => {
+    const collection = helper.ft.getCollectionObject(0);
+    await expect(collection.mint(alice, 100n, {Substrate: bob.address})).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('set_collection_properties()', async ({helper}) => {
+    const collection = helper.ft.getCollectionObject(0);
+    await expect(collection.setProperties(alice, [{key: 'value'}])).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('delete_collection_properties()', async ({helper}) => {
+    const collection = helper.ft.getCollectionObject(0);
+    await expect(collection.deleteProperties(alice, ['key'])).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('set_token_properties()', async ({helper}) => {
+    await expect(helper.executeExtrinsic(
+      alice,
+      'api.tx.unique.setTokenProperties',
+      [0, 0, [{key: 'value'}]],
+      true,
+    )).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('delete_token_properties()', async ({helper}) => {
+    await expect(helper.executeExtrinsic(
+      alice,
+      'api.tx.unique.deleteTokenProperties',
+      [0, 0, ['key']],
+      true,
+    )).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('set_transfers_enabled_flag()', async ({helper}) => {
+    await expect(helper.executeExtrinsic(
+      alice,
+      'api.tx.unique.setTransfersEnabledFlag',
+      [0, true],
+      true,
+    )).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('burn_item()', async ({helper}) => {
+    await expect(helper.executeExtrinsic(
+      alice,
+      'api.tx.unique.burnItem',
+      [0, 0, 100n],
+      true,
+    )).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('burn_from()', async ({helper}) => {
+    const collection = helper.ft.getCollectionObject(0);
+    await expect(collection.burnTokens(alice, 100n)).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('transfer()', async ({helper}) => {
+    const collection = helper.ft.getCollectionObject(0);
+    const balanceAliceBefore = await helper.balance.getSubstrate(alice.address);
+    const balanceBobBefore = await helper.balance.getSubstrate(bob.address);
+    await collection.transfer(alice, {Substrate: bob.address}, 100n);
+    const balanceAliceAfter = await helper.balance.getSubstrate(alice.address);
+    const balanceBobAfter = await helper.balance.getSubstrate(bob.address);
+    expect(balanceAliceBefore - balanceAliceAfter > 100n).to.be.true;
+    expect(balanceBobAfter - balanceBobBefore === 100n).to.be.true;
+  });
+
+  itSub('transfer_from()', async ({helper}) => {
+    const collection = helper.ft.getCollectionObject(0);
+    const balanceAliceBefore = await helper.balance.getSubstrate(alice.address);
+    const balanceBobBefore = await helper.balance.getSubstrate(bob.address);
+
+    await collection.transferFrom(alice, {Substrate: alice.address}, {Substrate: bob.address}, 100n);
+
+    const balanceAliceAfter = await helper.balance.getSubstrate(alice.address);
+    const balanceBobAfter = await helper.balance.getSubstrate(bob.address);
+    expect(balanceAliceBefore - balanceAliceAfter > 100n).to.be.true;
+    expect(balanceBobAfter - balanceBobBefore === 100n).to.be.true;
+
+    await expect(collection.transferFrom(alice, {Substrate: bob.address}, {Substrate: alice.address}, 100n)).to.be.rejectedWith('common.ApprovedValueTooLow');
+  });
+
+  itSub('approve()', async ({helper}) => {
+    const collection = helper.ft.getCollectionObject(0);
+    await expect(collection.approveTokens(alice, {Substrate: bob.address}, 100n)).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('approve_from()', async ({helper}) => {
+    await expect(helper.executeExtrinsic(
+      alice,
+      'api.tx.unique.approveFrom',
+      [{Substrate: alice.address}, {Substrate: bob.address}, 0, 0, 100n],
+      true,
+    )).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('set_collection_limits()', async ({helper}) => {
+    const collection = helper.ft.getCollectionObject(0);
+    await expect(collection.setLimits(alice, {accountTokenOwnershipLimit: 1})).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('set_collection_permissions()', async ({helper}) => {
+    const collection = helper.ft.getCollectionObject(0);
+    await expect(collection.setPermissions(alice, {access: 'AllowList'})).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('repartition()', async ({helper}) => {
+    await expect(helper.executeExtrinsic(
+      alice,
+      'api.tx.unique.repartition',
+      [0, 0, 100n],
+      true,
+    )).to.be.rejectedWith('unique.RepartitionCalledOnNonRefungibleCollection');
+  });
+
+  itSub('force_repair_collection()', async ({helper}) => {
+    await expect(helper.executeExtrinsic(
+      alice,
+      'api.tx.unique.forceRepairCollection',
+      [0],
+      true,
+    )).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('force_repair_item()', async ({helper}) => {
+    await expect(helper.getSudo().executeExtrinsic(
+      root,
+      'api.tx.unique.forceRepairItem',
+      [0, 0],
+      true,
+    )).to.be.rejectedWith('common.UnsupportedOperation');
+  });
+
+  itSub('Nest into NFT token()', async ({helper}) => {
+    const nftCollection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    const targetToken = await nftCollection.mintToken(alice);
+
+    const collection = helper.ft.getCollectionObject(0);
+    await collection.transfer(alice, targetToken.nestingAccount(), 100n);
+
+    await collection.transferFrom(alice, targetToken.nestingAccount(), {Substrate: alice.address}, 100n);
+  });
+});
\ No newline at end of file
modifiedtests/src/nesting/unnest.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/unnest.test.ts
+++ b/tests/src/nesting/unnest.test.ts
@@ -47,6 +47,20 @@
     await expect(nestedToken.getOwner()).to.be.rejected;
   });
 
+  itSub('NativeFungible: allows the owner to successfully unnest a token', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    const targetToken = await collection.mintToken(alice);
+
+    const collectionFT = helper.ft.getCollectionObject(0);
+
+    // Nest
+    await collectionFT.transfer(alice, targetToken.nestingAccount(), 10n);
+    // Unnest
+    await expect(collectionFT.transferFrom(alice, targetToken.nestingAccount(), {Substrate: alice.address}, 9n), 'while unnesting').to.be.fulfilled;
+
+    expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(1n);
+  });
+
   itSub('Fungible: allows the owner to successfully unnest a token', async ({helper}) => {
     const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
     const targetToken = await collection.mintToken(alice);
modifiedtests/src/pallet-presence.test.tsdiffbeforeafterboth
--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -19,6 +19,7 @@
 // Pallets that must always be present
 const requiredPallets = [
   'balances',
+  'balancesadapter',
   'common',
   'timestamp',
   'transactionpayment',
modifiedtests/src/removeCollectionAdmin.test.tsdiffbeforeafterboth
--- a/tests/src/removeCollectionAdmin.test.ts
+++ b/tests/src/removeCollectionAdmin.test.ts
@@ -16,6 +16,7 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import {itSub, usingPlaygrounds, expect} from './util';
+import {NON_EXISTENT_COLLECTION_ID} from './util/playgrounds/types';
 
 describe('Integration Test removeCollectionAdmin(collection_id, account_id):', () => {
   let alice: IKeyringPair;
@@ -68,7 +69,7 @@
   });
 
   itSub('Can\'t remove collection admin from not existing collection', async ({helper}) => {
-    const collectionId = (1 << 32) - 1;
+    const collectionId = NON_EXISTENT_COLLECTION_ID;
 
     await expect(helper.collection.removeAdmin(alice, collectionId, {Substrate: bob.address}))
       .to.be.rejectedWith(/common\.CollectionNotFound/);
modifiedtests/src/removeCollectionSponsor.test.tsdiffbeforeafterboth
--- a/tests/src/removeCollectionSponsor.test.ts
+++ b/tests/src/removeCollectionSponsor.test.ts
@@ -16,6 +16,7 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import {itSub, usingPlaygrounds, expect} from './util';
+import {NON_EXISTENT_COLLECTION_ID} from './util/playgrounds/types';
 
 describe('integration test: ext. removeCollectionSponsor():', () => {
   let donor: IKeyringPair;
@@ -91,7 +92,7 @@
   });
 
   itSub('(!negative test!) Remove sponsor for a collection that never existed', async ({helper}) => {
-    const collectionId = (1 << 32) - 1;
+    const collectionId = NON_EXISTENT_COLLECTION_ID;
     await expect(helper.collection.removeSponsor(alice, collectionId)).to.be.rejectedWith(/common\.CollectionNotFound/);
   });
 
modifiedtests/src/setCollectionLimits.test.tsdiffbeforeafterboth
--- a/tests/src/setCollectionLimits.test.ts
+++ b/tests/src/setCollectionLimits.test.ts
@@ -17,6 +17,7 @@
 // https://unique-network.readthedocs.io/en/latest/jsapi.html#setchainlimits
 import {IKeyringPair} from '@polkadot/types/types';
 import {itSub, usingPlaygrounds, expect} from './util';
+import {NON_EXISTENT_COLLECTION_ID} from './util/playgrounds/types';
 
 const accountTokenOwnershipLimit = 0;
 const sponsoredDataSize = 0;
@@ -110,7 +111,7 @@
   });
 
   itSub('execute setCollectionLimits for not exists collection', async ({helper}) => {
-    const nonExistentCollectionId = (1 << 32) - 1;
+    const nonExistentCollectionId = NON_EXISTENT_COLLECTION_ID;
     await expect(helper.collection.setLimits(
       alice,
       nonExistentCollectionId,
modifiedtests/src/setCollectionSponsor.test.tsdiffbeforeafterboth
--- a/tests/src/setCollectionSponsor.test.ts
+++ b/tests/src/setCollectionSponsor.test.ts
@@ -16,6 +16,7 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import {itSub, usingPlaygrounds, expect, Pallets} from './util';
+import {NON_EXISTENT_COLLECTION_ID} from './util/playgrounds/types';
 
 describe('integration test: ext. setCollectionSponsor():', () => {
   let alice: IKeyringPair;
@@ -105,7 +106,7 @@
   });
 
   itSub('(!negative test!) Add sponsor to a collection that never existed', async ({helper}) => {
-    const collectionId = (1 << 32) - 1;
+    const collectionId = NON_EXISTENT_COLLECTION_ID;
     await expect(helper.collection.setSponsor(alice, collectionId, bob.address))
       .to.be.rejectedWith(/common\.CollectionNotFound/);
   });
modifiedtests/src/setPermissions.test.tsdiffbeforeafterboth
--- a/tests/src/setPermissions.test.ts
+++ b/tests/src/setPermissions.test.ts
@@ -16,6 +16,7 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import {itSub, usingPlaygrounds, expect} from './util';
+import {NON_EXISTENT_COLLECTION_ID} from './util/playgrounds/types';
 
 describe('Integration Test: Set Permissions', () => {
   let alice: IKeyringPair;
@@ -85,7 +86,7 @@
   });
 
   itSub('fails on not existing collection', async ({helper}) => {
-    const collectionId = (1 << 32) - 1;
+    const collectionId = NON_EXISTENT_COLLECTION_ID;
     await expect(helper.collection.setPermissions(alice, collectionId, {access: 'AllowList', mintMode: true}))
       .to.be.rejectedWith(/common\.CollectionNotFound/);
   });
modifiedtests/src/sub/appPromotion/appPromotion.test.tsdiffbeforeafterboth
--- a/tests/src/sub/appPromotion/appPromotion.test.ts
+++ b/tests/src/sub/appPromotion/appPromotion.test.ts
@@ -157,7 +157,8 @@
       await helper.staking.stake(staker, 1000n * nominal);
       await helper.staking.stake(staker, 199n * nominal);
       // check balances
-      expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'ormlvest', amount: 200n * nominal, reasons: 'All'}, {id: 'appstake', amount: 1199n * nominal, reasons: 'All'}]);
+      expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'ormlvest', amount: 200n * nominal, reasons: 'All'}]);
+      expect(await helper.balance.getFrozen(staker.address)).to.deep.eq([{id: 'appstakeappstake', amount: 1199n * nominal}]);
       expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, frozen: 1199n * nominal});
       expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(1199n);
       expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(1199n * nominal);
@@ -453,7 +454,7 @@
       const [_unstake1, unstake2] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
       await helper.wait.forParachainBlockNumber(unstake2.block);
 
-      expect(await helper.balance.getLocked(staker.address)).to.deep.eq([]);
+      expect(await helper.balance.getFrozen(staker.address)).to.deep.eq([]);
       expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, frozen: 0n});
       expect(await helper.balance.getSubstrate(staker.address) / nominal).to.eq(999n);
       expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.eq(0n);
modifiedtests/src/sub/nesting/admin.test.tsdiffbeforeafterboth
--- a/tests/src/sub/nesting/admin.test.ts
+++ b/tests/src/sub/nesting/admin.test.ts
@@ -17,7 +17,7 @@
 import {IKeyringPair} from '@polkadot/types/types';
 import {expect, itSub, usingPlaygrounds} from '../../util';
 
-describe('Collection admin', () => {
+describe('Nesting by collection admin', () => {
   let alice: IKeyringPair;
   let bob: IKeyringPair;
   let charlie: IKeyringPair;
@@ -84,4 +84,3 @@
     expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());
   });
 });
-
modifiedtests/src/sub/nesting/common.test.tsdiffbeforeafterboth
--- a/tests/src/sub/nesting/common.test.ts
+++ b/tests/src/sub/nesting/common.test.ts
@@ -21,102 +21,144 @@
 let alice: IKeyringPair;
 let bob: IKeyringPair;
 
-before(async () => {
-  await usingPlaygrounds(async (helper, privateKey) => {
-    const donor = await privateKey({url: import.meta.url});
-    [alice, bob] = await helper.arrange.createAccounts([100n, 100n], donor);
+describe('Common nesting tests', () => {
+  before(async () => {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      const donor = await privateKey({url: import.meta.url});
+      [alice, bob] = await helper.arrange.createAccounts([100n, 100n], donor);
+    });
   });
-});
 
-[
-  {mode: 'nft' as const, restrictedMode: true, requiredPallets: []},
-  {mode: 'nft' as const, restrictedMode: false, requiredPallets: []},
-  {mode: 'rft' as const, restrictedMode: true, requiredPallets: [Pallets.ReFungible]},
-  {mode: 'rft' as const, restrictedMode: false, requiredPallets: [Pallets.ReFungible]},
-].map(testCase => {
-  itSub.ifWithPallets(`Token owner can nest ${testCase.mode.toUpperCase()} in NFT if "tokenOwner" permission set ${testCase.restrictedMode ? 'in restricted mode': ''}`, testCase.requiredPallets, async ({helper}) => {
-    // Only NFT can be target for nesting in
-    const targetNFTCollection = await helper.nft.mintCollection(alice);
-    const targetTokenBob = await targetNFTCollection.mintToken(alice, {Substrate: bob.address});
+  [
+    {mode: 'nft' as const, restrictedMode: true, requiredPallets: []},
+    {mode: 'nft' as const, restrictedMode: false, requiredPallets: []},
+    {mode: 'rft' as const, restrictedMode: true, requiredPallets: [Pallets.ReFungible]},
+    {mode: 'rft' as const, restrictedMode: false, requiredPallets: [Pallets.ReFungible]},
+  ].map(testCase => {
+    itSub.ifWithPallets(`Token owner can nest ${testCase.mode.toUpperCase()} in NFT if "tokenOwner" permission set ${testCase.restrictedMode ? 'in restricted mode': ''}`, testCase.requiredPallets, async ({helper}) => {
+      // Only NFT can be target for nesting in
+      const targetNFTCollection = await helper.nft.mintCollection(alice);
+      const targetTokenBob = await targetNFTCollection.mintToken(alice, {Substrate: bob.address});
+
+      const collectionForNesting = await helper[testCase.mode].mintCollection(bob);
+      // permissions should be set:
+      await targetNFTCollection.setPermissions(alice, {
+        nesting: {tokenOwner: true, restricted: testCase.restrictedMode ? [collectionForNesting.collectionId] : null},
+      });
 
-    const collectionForNesting = await helper[testCase.mode].mintCollection(bob);
-    // permissions should be set:
-    await targetNFTCollection.setPermissions(alice, {
-      nesting: {tokenOwner: true, restricted: testCase.restrictedMode ? [collectionForNesting.collectionId] : null},
+      // 1. Bob can immediately create nested token:
+      const nestedToken1 = testCase.mode === 'nft'
+        ? await (collectionForNesting as UniqueNFTCollection).mintToken(bob, targetTokenBob.nestingAccount())
+        : await (collectionForNesting as UniqueRFTCollection).mintToken(bob, 10n, targetTokenBob.nestingAccount());
+      expect(await nestedToken1.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});
+      expect(await nestedToken1.getOwner()).to.be.deep.equal(targetTokenBob.nestingAccount().toLowerCase());
+
+      // 2. Bob can mint and nest token:
+      const nestedToken2 = await collectionForNesting.mintToken(bob);
+      await nestedToken2.nest(bob, targetTokenBob);
+      expect(await nestedToken2.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});
+      expect(await nestedToken2.getOwner()).to.be.deep.equal(targetTokenBob.nestingAccount().toLowerCase());
     });
+  });
 
-    // 1. Bob can immediately create nested token:
-    const nestedToken1 = testCase.mode === 'nft'
-      ? await (collectionForNesting as UniqueNFTCollection).mintToken(bob, targetTokenBob.nestingAccount())
-      : await (collectionForNesting as UniqueRFTCollection).mintToken(bob, 10n, targetTokenBob.nestingAccount());
-    expect(await nestedToken1.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});
-    expect(await nestedToken1.getOwner()).to.be.deep.equal(targetTokenBob.nestingAccount().toLowerCase());
 
-    // 2. Bob can mint and nest token:
-    const nestedToken2 = await collectionForNesting.mintToken(bob);
-    await nestedToken2.nest(bob, targetTokenBob);
-    expect(await nestedToken2.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});
-    expect(await nestedToken2.getOwner()).to.be.deep.equal(targetTokenBob.nestingAccount().toLowerCase());
+  [
+    {restrictedMode: true},
+    {restrictedMode: false},
+  ].map(testCase => {
+    itSub(`Token owner can nest FT in NFT if "tokenOwner" permission set  ${testCase.restrictedMode ? 'in restricted mode': ''}`, async ({helper}) => {
+      // Only NFT allows nesting, permissions should be set:
+      const targetNFTCollection = await helper.nft.mintCollection(alice);
+      const targetTokenBob = await targetNFTCollection.mintToken(alice, {Substrate: bob.address});
+
+      const collectionForNesting = await helper.ft.mintCollection(bob);
+      // permissions should be set:
+      await targetNFTCollection.setPermissions(alice, {
+        nesting: {tokenOwner: true, restricted: testCase.restrictedMode ? [collectionForNesting.collectionId] : null},
+      });
+
+      // 1. Alice can immediately create nested tokens:
+      await collectionForNesting.mint(bob, 100n, targetTokenBob.nestingAccount());
+      expect(await collectionForNesting.getTop10Owners()).deep.eq([targetTokenBob.nestingAccount().toLowerCase()]);
+      expect(await collectionForNesting.getBalance(targetTokenBob.nestingAccount())).eq(100n);
+
+      // 2. Alice can mint and nest token:
+      await collectionForNesting.mint(bob, 100n);
+      await collectionForNesting.transfer(bob, targetTokenBob.nestingAccount(), 50n);
+      expect(await collectionForNesting.getBalance(targetTokenBob.nestingAccount())).eq(150n);
+      expect(await targetTokenBob.getChildren()).to.be.deep.equal([{collectionId: collectionForNesting.collectionId, tokenId: 0}]);
+    });
   });
-});
 
+  [
+    {restrictedMode: true},
+    {restrictedMode: false},
+  ].map(testCase => {
+    itSub(`Token owner can nest Native FT in NFT if "tokenOwner" permission set  ${testCase.restrictedMode ? 'in restricted mode': ''}`, async ({helper}) => {
+      // Only NFT allows nesting, permissions should be set:
+      const targetNFTCollection = await helper.nft.mintCollection(alice);
+      const targetTokenBob = await targetNFTCollection.mintToken(alice, {Substrate: bob.address});
+      expect(await targetTokenBob.getChildren()).to.be.empty;
 
-[
-  {restrictedMode: true},
-  {restrictedMode: false},
-].map(testCase => {
-  itSub(`Token owner can nest FT in NFT if "tokenOwner" permission set  ${testCase.restrictedMode ? 'in restricted mode': ''}`, async ({helper}) => {
-    // Only NFT allows nesting, permissions should be set:
-    const targetNFTCollection = await helper.nft.mintCollection(alice);
-    const targetTokenBob = await targetNFTCollection.mintToken(alice, {Substrate: bob.address});
+      const collectionForNesting = helper.ft.getCollectionObject(0);
+      // permissions should be set:
+      await targetNFTCollection.setPermissions(alice, {
+        nesting: {tokenOwner: true, restricted: testCase.restrictedMode ? [collectionForNesting.collectionId] : null},
+      });
 
-    const collectionForNesting = await helper.ft.mintCollection(bob);
-    // permissions should be set:
-    await targetNFTCollection.setPermissions(alice, {
-      nesting: {tokenOwner: true, restricted: testCase.restrictedMode ? [collectionForNesting.collectionId] : null},
+      // Bob can nest Native FT into their NFT:
+      await collectionForNesting.transfer(bob, targetTokenBob.nestingAccount(), 50n);
+      expect(await collectionForNesting.getBalance(targetTokenBob.nestingAccount())).eq(50n);
+      // Native FT should't be visible in NFT children:
+      expect(await targetTokenBob.getChildren()).to.be.deep.equal([]);
     });
+  });
+
 
-    // 1. Alice can immediately create nested tokens:
-    await collectionForNesting.mint(bob, 100n, targetTokenBob.nestingAccount());
-    expect(await collectionForNesting.getTop10Owners()).deep.eq([targetTokenBob.nestingAccount().toLowerCase()]);
-    expect(await collectionForNesting.getBalance(targetTokenBob.nestingAccount())).eq(100n);
+  itSub.ifWithPallets('Owner can unnest tokens using transferFrom', [Pallets.ReFungible], async ({helper}) => {
+    const collectionToNest = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    const tokenA = await collectionToNest.mintToken(alice);
+    const tokenB = await collectionToNest.mintToken(alice);
 
-    // 2. Alice can mint and nest token:
-    await collectionForNesting.mint(bob, 100n);
-    await collectionForNesting.transfer(bob, targetTokenBob.nestingAccount(), 50n);
-    expect(await collectionForNesting.getBalance(targetTokenBob.nestingAccount())).eq(150n);
-  });
-});
+    // Create a nested token
+    const nftCollectionToBeNested = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    const rftCollectionToBeNested = await helper.rft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    const ftCollectionToBeNested = await helper.ft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    const nativeFtCollectionToBeNested = helper.ft.getCollectionObject(0);
 
+    const nestedNFT = await nftCollectionToBeNested.mintToken(alice, tokenA.nestingAccount());
+    const nestedRFT = await rftCollectionToBeNested.mintToken(alice, 100n, tokenA.nestingAccount());
+    const _nestedFT = await ftCollectionToBeNested.mint(alice, 100n, tokenA.nestingAccount());
+    await nativeFtCollectionToBeNested.transfer(alice, tokenA.nestingAccount(), 100n);
+    expect(await nestedNFT.getOwner()).to.be.deep.equal(tokenA.nestingAccount().toLowerCase());
+    expect(await nestedRFT.getOwner()).to.be.deep.equal(tokenA.nestingAccount().toLowerCase());
+    expect(await ftCollectionToBeNested.getBalance(tokenA.nestingAccount())).to.equal(100n);
+    expect(await nativeFtCollectionToBeNested.getBalance(tokenA.nestingAccount())).to.equal(100n);
 
-itSub.ifWithPallets('Owner can unnest tokens using transferFrom', [Pallets.ReFungible], async ({helper}) => {
-  const collectionToNest = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
-  const tokenA = await collectionToNest.mintToken(alice);
-  const tokenB = await collectionToNest.mintToken(alice);
+    expect(await tokenA.getChildren()).to.be.length(3);
+    expect(await tokenB.getChildren()).to.be.length(0);
 
-  // Create a nested token
-  const nftCollectionToBeNested = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
-  const rftCollectionToBeNested = await helper.rft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
-  const ftCollectionToBeNested = await helper.ft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    // Transfer the nested token to another token
+    await nestedNFT.transferFrom(alice, tokenA.nestingAccount(), tokenB.nestingAccount());
+    await nestedRFT.transferFrom(alice, tokenA.nestingAccount(), tokenB.nestingAccount(), 25n);
+    await ftCollectionToBeNested.transferFrom(alice, tokenA.nestingAccount(), tokenB.nestingAccount(), 25n);
+    await nativeFtCollectionToBeNested.transferFrom(alice, tokenA.nestingAccount(), tokenB.nestingAccount(), 25n);
 
-  const nestedNFT = await nftCollectionToBeNested.mintToken(alice, tokenA.nestingAccount());
-  const nestedRFT = await rftCollectionToBeNested.mintToken(alice, 100n, tokenA.nestingAccount());
-  const _nestedFT = await ftCollectionToBeNested.mint(alice, 100n, tokenA.nestingAccount());
-  expect(await nestedNFT.getOwner()).to.be.deep.equal(tokenA.nestingAccount().toLowerCase());
-  expect(await nestedRFT.getOwner()).to.be.deep.equal(tokenA.nestingAccount().toLowerCase());
-  expect(await ftCollectionToBeNested.getBalance(tokenA.nestingAccount())).to.equal(100n);
+    expect(await nestedNFT.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});
+    expect(await nestedNFT.getOwner()).to.be.deep.equal(tokenB.nestingAccount().toLowerCase());
 
-  // Transfer the nested token to another token
-  await nestedNFT.transferFrom(alice, tokenA.nestingAccount(), tokenB.nestingAccount());
-  await nestedRFT.transferFrom(alice, tokenA.nestingAccount(), tokenB.nestingAccount(), 25n);
-  await ftCollectionToBeNested.transferFrom(alice, tokenA.nestingAccount(), tokenB.nestingAccount(), 25n);
+    expect(await nestedRFT.getBalance(tokenB.nestingAccount())).to.equal(25n);
+    expect(await nestedRFT.getBalance(tokenA.nestingAccount())).to.equal(75n);
 
-  expect(await nestedNFT.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});
-  expect(await nestedNFT.getOwner()).to.be.deep.equal(tokenB.nestingAccount().toLowerCase());
+    expect(await ftCollectionToBeNested.getBalance(tokenB.nestingAccount())).to.equal(25n);
+    expect(await ftCollectionToBeNested.getBalance(tokenA.nestingAccount())).to.equal(75n);
 
-  expect(await nestedRFT.getBalance(tokenB.nestingAccount())).to.equal(25n);
-  expect(await nestedRFT.getBalance(tokenA.nestingAccount())).to.equal(75n);
+    expect(await nativeFtCollectionToBeNested.getBalance(tokenB.nestingAccount())).to.equal(25n);
+    expect(await nativeFtCollectionToBeNested.getBalance(tokenA.nestingAccount())).to.equal(75n);
 
-  expect(await ftCollectionToBeNested.getBalance(tokenB.nestingAccount())).to.equal(25n);
-  expect(await ftCollectionToBeNested.getBalance(tokenA.nestingAccount())).to.equal(75n);
+    // RFT, FT, and without native FT
+    expect(await tokenA.getChildren()).to.be.length(2);
+    // NFT, RFT, FT, and without native FT
+    expect(await tokenB.getChildren()).to.be.length(3);
+  });
 });
modifiedtests/src/sub/nesting/e2e.test.tsdiffbeforeafterboth
--- a/tests/src/sub/nesting/e2e.test.ts
+++ b/tests/src/sub/nesting/e2e.test.ts
@@ -32,6 +32,7 @@
     const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
     const collectionB = await helper.ft.mintCollection(alice);
     const collectionC = await helper.rft.mintCollection(alice);
+    const collectionNative = helper.ft.getCollectionObject(0);
 
     const targetToken = await collectionA.mintToken(alice);
     expect((await targetToken.getChildren()).length).to.be.equal(0, 'Children length check at creation');
@@ -73,6 +74,14 @@
       {tokenId: tokenC.tokenId, collectionId: collectionC.collectionId},
     ]).and.has.length(3);
 
+    // Nest native fungible token into another collection
+    await collectionNative.transfer(alice, targetToken.nestingAccount(), 2n);
+    expect(await targetToken.getChildren()).to.have.deep.members([
+      {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},
+      {tokenId: 0, collectionId: collectionB.collectionId},
+      {tokenId: tokenC.tokenId, collectionId: collectionC.collectionId},
+    ]).and.has.length(3);
+
     // Burn all nested pieces
     await tokenC.burnFrom(alice, targetToken.nestingAccount(), 2n);
     expect(await targetToken.getChildren()).to.have.deep.members([
modifiedtests/src/sub/nesting/nesting.negative.test.tsdiffbeforeafterboth
--- a/tests/src/sub/nesting/nesting.negative.test.ts
+++ b/tests/src/sub/nesting/nesting.negative.test.ts
@@ -23,238 +23,272 @@
 let bob: IKeyringPair;
 let charlie: IKeyringPair;
 
-before(async () => {
-  await usingPlaygrounds(async (helper, privateKey) => {
-    const donor = await privateKey({url: import.meta.url});
-    [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+describe('Negative Test: Nesting', () => {
+  before(async () => {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      const donor = await privateKey({url: import.meta.url});
+      [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+    });
   });
-});
 
-[
-  {mode: 'nft' as const, requiredPallets: []},
-  {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
-].map(testCase => {
-  itSub.ifWithPallets(`Owner cannot nest ${testCase.mode.toUpperCase()} if nesting is disabled`, testCase.requiredPallets, async ({helper}) => {
-    // Create default collection, permissions are not set:
-    const aliceNFTCollection = await helper.nft.mintCollection(alice);
-    const targetToken = await aliceNFTCollection.mintToken(alice);
+  [
+    {mode: 'nft' as const, requiredPallets: []},
+    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+  ].map(testCase => {
+    itSub.ifWithPallets(`Owner cannot nest ${testCase.mode.toUpperCase()} if nesting is disabled`, testCase.requiredPallets, async ({helper}) => {
+      // Create default collection, permissions are not set:
+      const aliceNFTCollection = await helper.nft.mintCollection(alice);
+      const targetToken = await aliceNFTCollection.mintToken(alice);
 
-    const collectionForNesting = await helper[testCase.mode].mintCollection(alice);
+      const collectionForNesting = await helper[testCase.mode].mintCollection(alice);
 
-    // 1. Alice cannot create immediately nested tokens:
-    const nestingTx = testCase.mode === 'nft'
-      ? (collectionForNesting as UniqueNFTCollection).mintToken(alice, targetToken.nestingAccount())
-      : (collectionForNesting as UniqueRFTCollection).mintToken(alice, 10n, targetToken.nestingAccount());
-    await expect(nestingTx).to.be.rejectedWith('common.UserIsNotAllowedToNest');
+      // 1. Alice cannot create immediately nested tokens:
+      const nestingTx = testCase.mode === 'nft'
+        ? (collectionForNesting as UniqueNFTCollection).mintToken(alice, targetToken.nestingAccount())
+        : (collectionForNesting as UniqueRFTCollection).mintToken(alice, 10n, targetToken.nestingAccount());
+      await expect(nestingTx).to.be.rejectedWith('common.UserIsNotAllowedToNest');
 
-    // 2. Alice cannot mint and nest token:
-    const nestedToken2 = await collectionForNesting.mintToken(alice);
-    await expect(nestedToken2.nest(alice, targetToken)).to.be.rejectedWith('common.UserIsNotAllowedToNest');
+      // 2. Alice cannot mint and nest token:
+      const nestedToken2 = await collectionForNesting.mintToken(alice);
+      await expect(nestedToken2.nest(alice, targetToken)).to.be.rejectedWith('common.UserIsNotAllowedToNest');
+    });
   });
-});
 
-itSub('Owner cannot nest FT if nesting is disabled', async ({helper}) => {
-  // Create default collection, permissions are not set:
-  const aliceNFTCollection = await helper.nft.mintCollection(alice);
-  const targetToken = await aliceNFTCollection.mintToken(alice);
+  [
+    {mode: 'ft'},
+    {mode: 'nativeFt'},
+  ].map(testCase => {
+    itSub(`Owner cannot nest [${testCase.mode}] if nesting is disabled (except for native fungible collection)`, async ({helper}) => {
+    // Create default collection, permissions are not set:
+      const aliceNFTCollection = await helper.nft.mintCollection(alice);
+      const targetToken = await aliceNFTCollection.mintToken(alice);
 
-  const collectionForNesting = await helper.ft.mintCollection(alice);
+      const collectionForNesting = testCase.mode === 'ft' ? await helper.ft.mintCollection(alice) : helper.ft.getCollectionObject(0);
 
-  // 1. Alice cannot create immediately nested tokens:
-  await expect(collectionForNesting.mint(alice, 100n, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest');
+      // Alice cannot create immediately nested tokens:
+      if (testCase.mode === 'ft') {
+        await expect(collectionForNesting.mint(alice, 100n, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest');
+      } else {
+        await expect(collectionForNesting.transfer(alice, targetToken.nestingAccount(), 100n)).to.be.not.rejected;
+      }
 
-  // 2. Alice can mint and nest token:
-  await collectionForNesting.mint(alice, 100n);
-  await expect(collectionForNesting.transfer(alice, targetToken.nestingAccount(), 50n)).to.be.rejectedWith('common.UserIsNotAllowedToNest');
-});
+      // Alice can't mint and nest tokens:
+      if (testCase.mode === 'ft') {
+        await collectionForNesting.mint(alice, 100n);
+      }
 
-[
-  {mode: 'nft' as const},
-  {mode: 'rft' as const},
-  {mode: 'ft' as const},
-].map(testCase => {
-  itSub(`Non-owner and non-admin cannot nest ${testCase.mode.toUpperCase()} in someone else's tokens`, async ({helper}) => {
-    const targetCollection = await helper.nft.mintCollection(alice, {permissions:
-      {nesting: {tokenOwner: true, collectionAdmin: true}},
+      if (testCase.mode === 'ft') {
+        await expect(collectionForNesting.transfer(alice, targetToken.nestingAccount(), 50n)).to.be.rejectedWith('common.UserIsNotAllowedToNest');
+      } else {
+        await expect(collectionForNesting.transfer(alice, targetToken.nestingAccount(), 50n)).to.be.not.rejected;
+      }
     });
-    const targetToken = await targetCollection.mintToken(alice);
+  });
+
+  [
+    {mode: 'nft' as const},
+    {mode: 'rft' as const},
+    {mode: 'ft' as const},
+    {mode: 'native ft' as const},
+  ].map(testCase => {
+    itSub(`Non-owner and non-admin cannot nest ${testCase.mode.toUpperCase()} in someone else's tokens (except for native fungible collection)`, async ({helper}) => {
+      const targetCollection = await helper.nft.mintCollection(alice, {permissions:
+        {nesting: {tokenOwner: true, collectionAdmin: true}},
+      });
+      const targetToken = await targetCollection.mintToken(alice);
 
-    const nestedCollectionBob = await helper[testCase.mode].mintCollection(bob);
+      const nestedCollectionBob = await (
+        testCase.mode === 'native ft'
+          ? helper.ft.getCollectionObject(0)
+          : helper[testCase.mode].mintCollection(bob)
+      );
 
-    let nestedTokenBob: UniqueNFToken | UniqueRFToken;
-    switch (testCase.mode) {
-      case 'nft': nestedTokenBob = await (nestedCollectionBob as UniqueNFTCollection).mintToken(bob); break;
-      case 'rft': nestedTokenBob = await (nestedCollectionBob as UniqueRFTCollection).mintToken(bob, 100n); break;
-      case 'ft': await (nestedCollectionBob as UniqueFTCollection).mint(bob, 100n); break;
-    }
+      let nestedTokenBob: UniqueNFToken | UniqueRFToken;
+      switch (testCase.mode) {
+        case 'nft': nestedTokenBob = await (nestedCollectionBob as UniqueNFTCollection).mintToken(bob); break;
+        case 'rft': nestedTokenBob = await (nestedCollectionBob as UniqueRFTCollection).mintToken(bob, 100n); break;
+        case 'ft': await (nestedCollectionBob as UniqueFTCollection).mint(bob, 100n); break;
+        case 'native ft': await expect((nestedCollectionBob as UniqueFTCollection).mint(bob, 100n)).to.be.rejectedWith('common.UnsupportedOperation'); break;
+      }
 
-    // Bob non-owner of targetToken and non admin of targetCollection, so
-    // 1. cannot mint nested token:
-    switch (testCase.mode) {
-      case 'nft': await expect((nestedCollectionBob as UniqueNFTCollection).mintToken(bob, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;
-      case 'rft': await expect((nestedCollectionBob as UniqueRFTCollection).mintToken(bob, 100n, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;
-      case 'ft': await expect((nestedCollectionBob as UniqueFTCollection).mint(bob, 100n, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;
-    }
+      // Bob non-owner of targetToken and non admin of targetCollection, so
+      // 1. cannot mint nested token:
+      switch (testCase.mode) {
+        case 'nft': await expect((nestedCollectionBob as UniqueNFTCollection).mintToken(bob, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;
+        case 'rft': await expect((nestedCollectionBob as UniqueRFTCollection).mintToken(bob, 100n, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;
+        case 'ft': await expect((nestedCollectionBob as UniqueFTCollection).mint(bob, 100n, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;
+        case 'native ft': await expect((nestedCollectionBob as UniqueFTCollection).mint(bob, 100n, targetToken.nestingAccount())).to.be.rejectedWith('common.UnsupportedOperation'); break;
+      }
 
-    // 2. cannot nest existing token:
-    switch (testCase.mode) {
-      case 'nft':
-      case 'rft': await expect(nestedTokenBob!.transfer(bob, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;
-      case 'ft': await expect((nestedCollectionBob as UniqueFTCollection).transfer(bob, targetToken.nestingAccount(), 100n)).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;
-    }
+      // 2. cannot nest existing token:
+      switch (testCase.mode) {
+        case 'nft':
+        case 'rft': await expect(nestedTokenBob!.transfer(bob, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;
+        case 'ft': await expect((nestedCollectionBob as UniqueFTCollection).transfer(bob, targetToken.nestingAccount(), 100n)).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;
+        case 'native ft': await expect((nestedCollectionBob as UniqueFTCollection).transfer(bob, targetToken.nestingAccount(), 100n)).to.be.not.rejected; break;
+      }
+    });
   });
-});
 
-[
-  {mode: 'nft' as const, nesting: {tokenOwner: true,  collectionAdmin: false}},
-  {mode: 'nft' as const, nesting: {tokenOwner: false, collectionAdmin: true}},
-].map(testCase => {
-  itSub(`${testCase.nesting.tokenOwner ? 'Admin' : 'Token owner'} cannot nest when only ${testCase.nesting.tokenOwner ? 'tokenOwner' : 'collectionAdmin'} is allowed`, async ({helper}) => {
-    // Create collection with tokenOwner or create collection with collectionAdmin permission:
-    const targetCollection = await helper.nft.mintCollection(alice, {permissions: {nesting: testCase.nesting}});
-    const targetTokenCharlie = await targetCollection.mintToken(alice, {Substrate: charlie.address});
-    await targetCollection.addAdmin(alice, {Substrate: bob.address});
+  [
+    {mode: 'nft' as const, nesting: {tokenOwner: true,  collectionAdmin: false}},
+    {mode: 'nft' as const, nesting: {tokenOwner: false, collectionAdmin: true}},
+  ].map(testCase => {
+    itSub(`${testCase.nesting.tokenOwner ? 'Admin' : 'Token owner'} cannot nest when only ${testCase.nesting.tokenOwner ? 'tokenOwner' : 'collectionAdmin'} is allowed`, async ({helper}) => {
+      // Create collection with tokenOwner or create collection with collectionAdmin permission:
+      const targetCollection = await helper.nft.mintCollection(alice, {permissions: {nesting: testCase.nesting}});
+      const targetTokenCharlie = await targetCollection.mintToken(alice, {Substrate: charlie.address});
+      await targetCollection.addAdmin(alice, {Substrate: bob.address});
 
-    const nestedCollectionCharlie = await helper[testCase.mode].mintCollection(charlie);
-    const nestedCollectionBob = await helper[testCase.mode].mintCollection(bob);
-    // if nesting permissions restricted for token owner – minter is bob (admin),
-    // if collectionAdmin – charlie (owner)
-    testCase.nesting.tokenOwner
-      ? await expect(nestedCollectionBob.mintToken(bob, targetTokenCharlie.nestingAccount())).to.be.rejectedWith(/common\.UserIsNotAllowedToNest/)
-      : await expect(nestedCollectionCharlie.mintToken(charlie, targetTokenCharlie.nestingAccount())).to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+      const nestedCollectionCharlie = await helper[testCase.mode].mintCollection(charlie);
+      const nestedCollectionBob = await helper[testCase.mode].mintCollection(bob);
+      // if nesting permissions restricted for token owner – minter is bob (admin),
+      // if collectionAdmin – charlie (owner)
+      testCase.nesting.tokenOwner
+        ? await expect(nestedCollectionBob.mintToken(bob, targetTokenCharlie.nestingAccount())).to.be.rejectedWith(/common\.UserIsNotAllowedToNest/)
+        : await expect(nestedCollectionCharlie.mintToken(charlie, targetTokenCharlie.nestingAccount())).to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+    });
   });
-});
 
-itSub.ifWithPallets('Cannot nest in non existing token', [Pallets.ReFungible], async ({helper}) => {
-  const collection = await helper.nft.mintCollection(alice);
-  // To avoid UserIsNotAllowedToNest error
-  await helper.collection.setPermissions(alice, collection.collectionId, {nesting: {collectionAdmin: true}});
+  itSub.ifWithPallets('Cannot nest in non existing token (except for native fungible collection)', [Pallets.ReFungible], async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice);
+    // To avoid UserIsNotAllowedToNest error
+    await helper.collection.setPermissions(alice, collection.collectionId, {nesting: {collectionAdmin: true}});
 
-  // The list of non-existing tokens:
-  const tokenFromNonExistingCollection = helper.nft.getTokenObject(9999999, 1);
-  const tokenBurnt = await collection.mintToken(alice);
-  await tokenBurnt.burn(alice);
-  const tokenNotMintedYet = helper.nft.getTokenObject(collection.collectionId, 2);
+    // The list of non-existing tokens:
+    const tokenFromNonExistingCollection = helper.nft.getTokenObject(9999999, 1);
+    const tokenBurnt = await collection.mintToken(alice);
+    await tokenBurnt.burn(alice);
+    const tokenNotMintedYet = helper.nft.getTokenObject(collection.collectionId, 2);
 
-  // The list of collections to nest tokens from:
-  const nftCollectionForNesting = await helper.nft.mintCollection(alice);
-  const rftCollectionForNesting = await helper.rft.mintCollection(alice);
-  const ftCollectionForNesting = await helper.ft.mintCollection(alice);
+    // The list of collections to nest tokens from:
+    const nftCollectionForNesting = await helper.nft.mintCollection(alice);
+    const rftCollectionForNesting = await helper.rft.mintCollection(alice);
+    const ftCollectionForNesting = await helper.ft.mintCollection(alice);
+    const nativeFtCollectionForNesting = helper.ft.getCollectionObject(0);
 
-  const testCases = [
-    {token: tokenFromNonExistingCollection, error: 'CollectionNotFound'},
-    {token: tokenBurnt, error: 'TokenNotFound'},
-    {token: tokenNotMintedYet, error: 'TokenNotFound'},
-  ];
+    const testCases = [
+      {token: tokenFromNonExistingCollection, error: 'CollectionNotFound'},
+      {token: tokenBurnt, error: 'TokenNotFound'},
+      {token: tokenNotMintedYet, error: 'TokenNotFound'},
+    ];
 
-  for(const testCase of testCases) {
-    // 1. Alice cannot create nested token to non-existing token
-    await expect(nftCollectionForNesting.mintToken(alice, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);
-    await expect(rftCollectionForNesting.mintToken(alice, 10n, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);
-    await expect(ftCollectionForNesting.mint(alice, 10n, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);
+    for(const testCase of testCases) {
+      // 1. Alice cannot create nested token to non-existing token
+      await expect(nftCollectionForNesting.mintToken(alice, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);
+      await expect(rftCollectionForNesting.mintToken(alice, 10n, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);
+      await expect(ftCollectionForNesting.mint(alice, 10n, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);
 
-    // 2. Alice cannot mint and nest token:
-    const nft = await nftCollectionForNesting.mintToken(alice);
-    const rft = await rftCollectionForNesting.mintToken(alice, 100n);
-    const _ft = await ftCollectionForNesting.mint(alice, 100n);
-    await expect(nft.transfer(alice, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);
-    await expect(rft.transfer(alice, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);
-    await expect(ftCollectionForNesting.transfer(alice, testCase.token.nestingAccount(), 50n)).to.be.rejectedWith(testCase.error);
-  }
-});
+      // 2. Alice cannot mint and nest token:
+      const nft = await nftCollectionForNesting.mintToken(alice);
+      const rft = await rftCollectionForNesting.mintToken(alice, 100n);
+      const _ft = await ftCollectionForNesting.mint(alice, 100n);
+      await expect(nft.transfer(alice, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);
+      await expect(rft.transfer(alice, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);
+      await expect(ftCollectionForNesting.transfer(alice, testCase.token.nestingAccount(), 50n)).to.be.rejectedWith(testCase.error);
+      await expect(nativeFtCollectionForNesting.transfer(alice, testCase.token.nestingAccount(), 50n)).to.be.not.rejected;
+    }
+  });
 
-itEth.ifWithPallets('Cannot nest in collection address', [Pallets.ReFungible], async({helper}) => {
-  const existingCollection = await helper.nft.mintCollection(alice);
-  const existingCollectionAddress = helper.ethAddress.fromCollectionId(existingCollection.collectionId);
-  const futureCollectionAddress = helper.ethAddress.fromCollectionId(99999999);
+  itEth.ifWithPallets('Cannot nest in collection address', [Pallets.ReFungible], async({helper}) => {
+    const existingCollection = await helper.nft.mintCollection(alice);
+    const existingCollectionAddress = helper.ethAddress.fromCollectionId(existingCollection.collectionId);
+    const futureCollectionAddress = helper.ethAddress.fromCollectionId(99999999);
 
-  const nftCollectionForNesting = await helper.nft.mintCollection(alice);
+    const nftCollectionForNesting = await helper.nft.mintCollection(alice);
 
-  // 1. Alice cannot create nested token to collection address
-  await expect(nftCollectionForNesting.mintToken(alice, {Ethereum: existingCollectionAddress})).to.be.rejectedWith('CantNestTokenUnderCollection');
-  await expect(nftCollectionForNesting.mintToken(alice, {Ethereum: futureCollectionAddress})).to.be.rejectedWith('CantNestTokenUnderCollection');
+    // 1. Alice cannot create nested token to collection address
+    await expect(nftCollectionForNesting.mintToken(alice, {Ethereum: existingCollectionAddress})).to.be.rejectedWith('CantNestTokenUnderCollection');
+    await expect(nftCollectionForNesting.mintToken(alice, {Ethereum: futureCollectionAddress})).to.be.rejectedWith('CantNestTokenUnderCollection');
 
-  // 2. Alice cannot mint and nest token to collection address:
-  const nft = await nftCollectionForNesting.mintToken(alice);
-  await expect(nft.transfer(alice, {Ethereum: existingCollectionAddress})).to.be.rejectedWith('CantNestTokenUnderCollection');
-  await expect(nft.transfer(alice, {Ethereum: futureCollectionAddress})).to.be.rejectedWith('CantNestTokenUnderCollection');
-});
+    // 2. Alice cannot mint and nest token to collection address:
+    const nft = await nftCollectionForNesting.mintToken(alice);
+    await expect(nft.transfer(alice, {Ethereum: existingCollectionAddress})).to.be.rejectedWith('CantNestTokenUnderCollection');
+    await expect(nft.transfer(alice, {Ethereum: futureCollectionAddress})).to.be.rejectedWith('CantNestTokenUnderCollection');
+  });
 
-itEth.ifWithPallets('Cannot nest in RFT or FT', [Pallets.ReFungible], async ({helper}) => {
-  // Create default collection, permissions are not set:
-  const rftCollection = await helper.rft.mintCollection(alice);
-  const ftCollection = await helper.ft.mintCollection(alice);
+  itEth.ifWithPallets('Cannot nest in RFT or FT (except for native fungible collection)', [Pallets.ReFungible], async ({helper}) => {
+    // Create default collection, permissions are not set:
+    const rftCollection = await helper.rft.mintCollection(alice);
+    const ftCollection = await helper.ft.mintCollection(alice);
+    const nativeFtCollection = helper.ft.getCollectionObject(0);
 
-  const rftToken = await rftCollection.mintToken(alice);
-  const _ftToken = await ftCollection.mint(alice, 100n);
+    const rftToken = await rftCollection.mintToken(alice);
+    const _ftToken = await ftCollection.mint(alice, 100n);
 
-  const collectionForNesting = await helper.nft.mintCollection(alice);
+    const collectionForNesting = await helper.nft.mintCollection(alice);
 
-  // 1. Alice cannot create immediately nested tokens:
-  await expect(collectionForNesting.mintToken(alice, rftToken.nestingAccount())).to.be.rejectedWith('refungible.RefungibleDisallowsNesting');
-  await expect(collectionForNesting.mintToken(alice, {Ethereum: helper.ethAddress.fromTokenId(ftCollection.collectionId, 0)})).to.be.rejectedWith('fungible.FungibleDisallowsNesting');
+    // 1. Alice cannot create immediately nested tokens:
+    await expect(collectionForNesting.mintToken(alice, rftToken.nestingAccount())).to.be.rejectedWith('refungible.RefungibleDisallowsNesting');
+    await expect(collectionForNesting.mintToken(alice, {Ethereum: helper.ethAddress.fromTokenId(ftCollection.collectionId, 0)})).to.be.rejectedWith('fungible.FungibleDisallowsNesting');
+    await expect(collectionForNesting.mintToken(alice, {Ethereum: helper.ethAddress.fromTokenId(nativeFtCollection.collectionId, 0)})).to.be.rejectedWith('common.UnsupportedOperation');
 
-  // 2. Alice cannot mint and nest token:
-  const nestedToken2 = await collectionForNesting.mintToken(alice);
-  await expect(nestedToken2.nest(alice, rftToken)).to.be.rejectedWith('refungible.RefungibleDisallowsNesting');
-  await expect(ftCollection.transfer(alice, {Ethereum: helper.ethAddress.fromTokenId(ftCollection.collectionId, 0)})).to.be.rejectedWith('fungible.FungibleDisallowsNesting');
-});
+    // 2. Alice cannot mint and nest token:
+    const nestedToken2 = await collectionForNesting.mintToken(alice);
+    await expect(nestedToken2.nest(alice, rftToken)).to.be.rejectedWith('refungible.RefungibleDisallowsNesting');
+    await expect(ftCollection.transfer(alice, {Ethereum: helper.ethAddress.fromTokenId(ftCollection.collectionId, 0)})).to.be.rejectedWith('fungible.FungibleDisallowsNesting');
+    await expect(nativeFtCollection.transfer(alice, {Ethereum: helper.ethAddress.fromTokenId(nativeFtCollection.collectionId, 0)})).to.be.not.rejected;
+  });
 
-itSub('Cannot nest in restricted collection if collection is not in the list', async ({helper}) => {
-  const {collectionId: allowedCollectionId} = await helper.nft.mintCollection(alice);
-  const notAllowedCollectionNFT = await helper.nft.mintCollection(alice);
-  const notAllowedCollectionRFT = await helper.rft.mintCollection(alice);
-  const notAllowedCollectionFT = await helper.ft.mintCollection(alice);
+  itSub('Cannot nest in restricted collection if collection is not in the list (except native fungible collection)', async ({helper}) => {
+    const {collectionId: allowedCollectionId} = await helper.nft.mintCollection(alice);
+    const notAllowedCollectionNFT = await helper.nft.mintCollection(alice);
+    const notAllowedCollectionRFT = await helper.rft.mintCollection(alice);
+    const notAllowedCollectionFT = await helper.ft.mintCollection(alice);
+    const allowedCollectionNativeFT = helper.ft.getCollectionObject(0);
 
-  // Collection restricted to allowedCollectionId
-  const restrictedCollectionA = await helper.nft.mintCollection(alice, {permissions:
-    {nesting: {tokenOwner: true, restricted: [allowedCollectionId]}},
-  });
-  // Create collection with restricted nesting -- even self is not allowed
-  const restrictedCollectionB = await helper.nft.mintCollection(alice, {permissions:
-    {nesting: {tokenOwner: true, restricted: []}},
-  });
+    // Collection restricted to allowedCollectionId
+    const restrictedCollectionA = await helper.nft.mintCollection(alice, {permissions:
+      {nesting: {tokenOwner: true, restricted: [allowedCollectionId]}},
+    });
+    // Create collection with restricted nesting -- even self is not allowed
+    const restrictedCollectionB = await helper.nft.mintCollection(alice, {permissions:
+      {nesting: {tokenOwner: true, restricted: []}},
+    });
 
-  const targetTokenA = await restrictedCollectionA.mintToken(alice);
-  const targetTokenB = await restrictedCollectionB.mintToken(alice);
+    const targetTokenA = await restrictedCollectionA.mintToken(alice);
+    const targetTokenB = await restrictedCollectionB.mintToken(alice);
 
-  // 1. Cannot mint in own collection after allowlisting the accounts:
-  await expect(restrictedCollectionA.mintToken(alice, targetTokenA.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
-  await expect(restrictedCollectionB.mintToken(alice, targetTokenB.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
+    // 1. Cannot mint in own collection after allowlisting the accounts:
+    await expect(restrictedCollectionA.mintToken(alice, targetTokenA.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
+    await expect(restrictedCollectionB.mintToken(alice, targetTokenB.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
 
-  // 2. Cannot mint from notAllowedCollection:
-  await expect(notAllowedCollectionNFT.mintToken(alice, targetTokenA.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
-  await expect(notAllowedCollectionNFT.mintToken(alice, targetTokenB.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
-  await expect(notAllowedCollectionRFT.mintToken(alice, 100n, targetTokenA.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
-  await expect(notAllowedCollectionRFT.mintToken(alice, 100n, targetTokenB.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
-  await expect(notAllowedCollectionFT.mint(alice, 100n, targetTokenA.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
-  await expect(notAllowedCollectionFT.mint(alice, 100n, targetTokenB.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
-});
+    // 2. Cannot mint from notAllowedCollection:
+    await expect(notAllowedCollectionNFT.mintToken(alice, targetTokenA.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
+    await expect(notAllowedCollectionNFT.mintToken(alice, targetTokenB.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
+    await expect(notAllowedCollectionRFT.mintToken(alice, 100n, targetTokenA.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
+    await expect(notAllowedCollectionRFT.mintToken(alice, 100n, targetTokenB.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
+    await expect(notAllowedCollectionFT.mint(alice, 100n, targetTokenA.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
+    await expect(notAllowedCollectionFT.mint(alice, 100n, targetTokenB.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
+    await expect(allowedCollectionNativeFT.transfer(alice, targetTokenA.nestingAccount(), 100n)).to.be.not.rejected;
+    await expect(allowedCollectionNativeFT.transfer(alice, targetTokenB.nestingAccount(), 100n)).to.be.not.rejected;
+  });
 
-itSub('Cannot create nesting chains greater than 5', async ({helper}) => {
-  const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
-  let token = await collection.mintToken(alice);
+  itSub('Cannot create nesting chains greater than 5', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    let token = await collection.mintToken(alice);
 
-  const maxNestingLevel = 5;
+    const maxNestingLevel = 5;
 
-  // Create a nested-token matryoshka
-  for (let i = 0; i < maxNestingLevel; i++) {
-    token = await collection.mintToken(alice, token.nestingAccount());
-  }
+    // Create a nested-token matryoshka
+    for (let i = 0; i < maxNestingLevel; i++) {
+      token = await collection.mintToken(alice, token.nestingAccount());
+    }
 
-  // The nesting depth is limited by `maxNestingLevel`
-  // 1. Cannot mint:
-  await expect(collection.mintToken(alice, token.nestingAccount()))
-    .to.be.rejectedWith(/structure\.DepthLimit/);
-  // 2. Cannot transfer:
-  const anotherToken = await collection.mintToken(alice);
-  await expect(anotherToken.transfer(alice, token.nestingAccount()))
-    .to.be.rejectedWith(/structure\.DepthLimit/);
-  // 3. Cannot nest FT pieces:
-  const ftCollection = await helper.ft.mintCollection(alice);
-  await expect(ftCollection.mint(alice, 100n, token.nestingAccount()))
-    .to.be.rejectedWith(/structure\.DepthLimit/);
+    // The nesting depth is limited by `maxNestingLevel`
+    // 1. Cannot mint:
+    await expect(collection.mintToken(alice, token.nestingAccount()))
+      .to.be.rejectedWith(/structure\.DepthLimit/);
+    // 2. Cannot transfer:
+    const anotherToken = await collection.mintToken(alice);
+    await expect(anotherToken.transfer(alice, token.nestingAccount()))
+      .to.be.rejectedWith(/structure\.DepthLimit/);
+    // 3. Cannot nest FT pieces:
+    const ftCollection = await helper.ft.mintCollection(alice);
+    await expect(ftCollection.mint(alice, 100n, token.nestingAccount()))
+      .to.be.rejectedWith(/structure\.DepthLimit/);
 
-  expect(await token.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});
-  expect(await token.getChildren()).to.has.length(0);
+    expect(await token.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});
+    expect(await token.getChildren()).to.has.length(0);
+  });
 });
modifiedtests/src/sub/nesting/refungible.test.tsdiffbeforeafterboth
--- a/tests/src/sub/nesting/refungible.test.ts
+++ b/tests/src/sub/nesting/refungible.test.ts
@@ -17,44 +17,45 @@
 import {IKeyringPair} from '@polkadot/types/types';
 import {expect, itSub, Pallets, usingPlaygrounds} from '../../util';
 
-// ReFungible specific nesting tests
-let alice: IKeyringPair;
+describe('ReFungible-specific nesting tests', () => {
+  let alice: IKeyringPair;
 
-before(async () => {
-  await usingPlaygrounds(async (helper, privateKey) => {
-    const donor = await privateKey({url: import.meta.url});
-    [alice] = await helper.arrange.createAccounts([200n], donor);
+  before(async () => {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      const donor = await privateKey({url: import.meta.url});
+      [alice] = await helper.arrange.createAccounts([200n], donor);
+    });
   });
-});
 
-itSub.ifWithPallets('ReFungible: getTopmostOwner works correctly with Nesting', [Pallets.ReFungible], async({helper}) => {
-  const collectionNFT = await helper.nft.mintCollection(alice, {
-    permissions: {
-      nesting: {
-        tokenOwner: true,
+  itSub.ifWithPallets('ReFungible: getTopmostOwner works correctly with Nesting', [Pallets.ReFungible], async({helper}) => {
+    const collectionNFT = await helper.nft.mintCollection(alice, {
+      permissions: {
+        nesting: {
+          tokenOwner: true,
+        },
       },
-    },
-  });
-  const collectionRFT = await helper.rft.mintCollection(alice);
+    });
+    const collectionRFT = await helper.rft.mintCollection(alice);
 
-  const nft = await collectionNFT.mintToken(alice, {Substrate: alice.address});
-  const rft = await collectionRFT.mintToken(alice, 100n, {Substrate: alice.address});
+    const nft = await collectionNFT.mintToken(alice, {Substrate: alice.address});
+    const rft = await collectionRFT.mintToken(alice, 100n, {Substrate: alice.address});
 
-  expect(await rft.getTopmostOwner()).deep.equal({Substrate: alice.address});
+    expect(await rft.getTopmostOwner()).deep.equal({Substrate: alice.address});
 
-  await rft.transfer(alice, nft.nestingAccount(), 40n);
+    await rft.transfer(alice, nft.nestingAccount(), 40n);
 
-  expect(await rft.getTopmostOwner()).deep.equal(null);
+    expect(await rft.getTopmostOwner()).deep.equal(null);
 
-  await rft.transfer(alice, nft.nestingAccount(), 60n);
+    await rft.transfer(alice, nft.nestingAccount(), 60n);
 
-  expect(await rft.getTopmostOwner()).deep.equal({Substrate: alice.address});
+    expect(await rft.getTopmostOwner()).deep.equal({Substrate: alice.address});
 
-  await rft.transferFrom(alice, nft.nestingAccount(), {Substrate: alice.address}, 30n);
+    await rft.transferFrom(alice, nft.nestingAccount(), {Substrate: alice.address}, 30n);
 
-  expect(await rft.getTopmostOwner()).deep.equal(null);
+    expect(await rft.getTopmostOwner()).deep.equal(null);
 
-  await rft.transferFrom(alice, nft.nestingAccount(), {Substrate: alice.address}, 70n);
+    await rft.transferFrom(alice, nft.nestingAccount(), {Substrate: alice.address}, 70n);
 
-  expect(await rft.getTopmostOwner()).deep.equal({Substrate: alice.address});
+    expect(await rft.getTopmostOwner()).deep.equal({Substrate: alice.address});
+  });
 });
modifiedtests/src/sub/nesting/unnesting.negative.test.tsdiffbeforeafterboth
--- a/tests/src/sub/nesting/unnesting.negative.test.ts
+++ b/tests/src/sub/nesting/unnesting.negative.test.ts
@@ -52,12 +52,19 @@
   });
 
   [
-    {restrictedMode: true},
-    {restrictedMode: false},
+    {mode: 'ft' as const},
+    {mode: 'native ft' as const},
+  ].map(md => [
+    {mode: md.mode, restrictedMode: true},
+    {mode: md.mode, restrictedMode: false},
   ].map(testCase => {
-    itSub(`Fungible: disallows a non-Owner to unnest someone else's token ${testCase.restrictedMode ? '(Restricted nesting)' : ''}`, async ({helper}) => {
+    itSub(`Fungible: disallows a non-Owner to unnest someone else's token [${testCase.mode}${testCase.restrictedMode ? ' (Restricted nesting)' : ''}]`, async ({helper}) => {
       const collectionNFT = await helper.nft.mintCollection(alice);
-      const collectionFT = await helper.ft.mintCollection(alice);
+      const collectionFT = await (
+        testCase.mode === 'ft'
+          ? helper.ft.mintCollection(alice)
+          : helper.ft.getCollectionObject(0)
+      );
       const targetToken = await collectionNFT.mintToken(alice, {Substrate: bob.address});
 
       await collectionNFT.setPermissions(alice, {nesting: {
@@ -65,12 +72,16 @@
       }});
 
       // Nest some tokens as Alice into Bob's token
-      await collectionFT.mint(alice, 5n, targetToken.nestingAccount());
+      await (
+        testCase.mode === 'ft'
+          ? collectionFT.mint(alice, 5n, targetToken.nestingAccount())
+          : collectionFT.transfer(alice, targetToken.nestingAccount(), 5n)
+      );
 
       // Try to pull it out as Alice still
       await expect(collectionFT.transferFrom(alice, targetToken.nestingAccount(), {Substrate: bob.address}, 1n))
         .to.be.rejectedWith(/common\.ApprovedValueTooLow/);
       expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(5n);
     });
-  });
+  }));
 });
modifiedtests/src/transfer.test.tsdiffbeforeafterboth
--- a/tests/src/transfer.test.ts
+++ b/tests/src/transfer.test.ts
@@ -17,6 +17,7 @@
 import {IKeyringPair} from '@polkadot/types/types';
 import {itEth, usingEthPlaygrounds} from './eth/util';
 import {itSub, Pallets, usingPlaygrounds, expect} from './util';
+import {NON_EXISTENT_COLLECTION_ID} from './util/playgrounds/types';
 
 describe('Integration Test Transfer(recipient, collection_id, item_id, value)', () => {
   let donor: IKeyringPair;
@@ -124,20 +125,17 @@
 
 
   itSub('[nft] Transfer with not existed collection_id', async ({helper}) => {
-    const collectionId = (1 << 32) - 1;
-    await expect(helper.nft.transferToken(alice, collectionId, 1, {Substrate: bob.address}))
+    await expect(helper.nft.transferToken(alice, NON_EXISTENT_COLLECTION_ID, 1, {Substrate: bob.address}))
       .to.be.rejectedWith(/common\.CollectionNotFound/);
   });
 
   itSub('[fungible] Transfer with not existed collection_id', async ({helper}) => {
-    const collectionId = (1 << 32) - 1;
-    await expect(helper.ft.transfer(alice, collectionId, {Substrate: bob.address}))
+    await expect(helper.ft.transfer(alice, NON_EXISTENT_COLLECTION_ID, {Substrate: bob.address}))
       .to.be.rejectedWith(/common\.CollectionNotFound/);
   });
 
   itSub.ifWithPallets('[refungible] Transfer with not existed collection_id', [Pallets.ReFungible], async ({helper}) => {
-    const collectionId = (1 << 32) - 1;
-    await expect(helper.rft.transferToken(alice, collectionId, 1, {Substrate: bob.address}))
+    await expect(helper.rft.transferToken(alice, NON_EXISTENT_COLLECTION_ID, 1, {Substrate: bob.address}))
       .to.be.rejectedWith(/common\.CollectionNotFound/);
   });
 
modifiedtests/src/transferFrom.test.tsdiffbeforeafterboth
--- a/tests/src/transferFrom.test.ts
+++ b/tests/src/transferFrom.test.ts
@@ -16,6 +16,7 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import {itSub, Pallets, usingPlaygrounds, expect} from './util';
+import {NON_EXISTENT_COLLECTION_ID} from './util/playgrounds/types';
 
 describe('Integration Test transferFrom(from, recipient, collection_id, item_id, value):', () => {
   let alice: IKeyringPair;
@@ -97,10 +98,9 @@
   });
 
   itSub('transferFrom for a collection that does not exist', async ({helper}) => {
-    const collectionId = (1 << 32) - 1;
-    await expect(helper.collection.approveToken(alice, collectionId, 0, {Substrate: bob.address}, 1n))
+    await expect(helper.collection.approveToken(alice, NON_EXISTENT_COLLECTION_ID, 0, {Substrate: bob.address}, 1n))
       .to.be.rejectedWith(/common\.CollectionNotFound/);
-    await expect(helper.collection.transferTokenFrom(bob, collectionId, 0, {Substrate: alice.address}, {Substrate: bob.address}, 1n))
+    await expect(helper.collection.transferTokenFrom(bob, NON_EXISTENT_COLLECTION_ID, 0, {Substrate: alice.address}, {Substrate: bob.address}, 1n))
       .to.be.rejectedWith(/common\.CollectionNotFound/);
   });
 
modifiedtests/src/util/playgrounds/types.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -3,6 +3,8 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 
+export const NON_EXISTENT_COLLECTION_ID = 4_294_967_295;
+
 export interface IEvent {
   section: string;
   method: string;
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
before · tests/src/util/playgrounds/unique.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {SignerOptions} from '@polkadot/api/types/submittable';10import '../../interfaces/augment-api-tx';11import {AugmentedSubmittables} from '@polkadot/api-base/types/submittable';12import {RpcInterface} from '@polkadot/rpc-core/types';13import {QueryableStorage} from '@polkadot/api-base/types/storage';14import {DecoratedRpc} from '@polkadot/api-base/types/rpc';15import {ApiInterfaceEvents} from '@polkadot/api/types';16import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';17import {IKeyringPair} from '@polkadot/types/types';18import {hexToU8a} from '@polkadot/util/hex';19import {u8aConcat} from '@polkadot/util/u8a';20import {21  IApiListeners,22  IBlock,23  IEvent,24  IChainProperties,25  ICollectionCreationOptions,26  ICollectionLimits,27  ICollectionPermissions,28  ICrossAccountId,29  ICrossAccountIdLower,30  ILogger,31  INestingPermissions,32  IProperty,33  IStakingInfo,34  ISchedulerOptions,35  ISubstrateBalance,36  IToken,37  ITokenPropertyPermission,38  ITransactionResult,39  IUniqueHelperLog,40  TApiAllowedListeners,41  TEthereumAccount,42  TSigner,43  TSubstrateAccount,44  TNetworks,45  IForeignAssetMetadata,46  AcalaAssetMetadata,47  MoonbeamAssetInfo,48  DemocracyStandardAccountVote,49  IEthCrossAccountId,50} from './types';51import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';52import type {Vec} from '@polkadot/types-codec';53import {FrameSystemEventRecord} from '@polkadot/types/lookup';5455export class CrossAccountId {56  Substrate!: TSubstrateAccount;57  Ethereum!: TEthereumAccount;5859  constructor(account: ICrossAccountId) {60    if ('Substrate' in account) this.Substrate = account.Substrate;61    else this.Ethereum = account.Ethereum;62  }6364  static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {65    switch (domain) {66      case 'Substrate': return new CrossAccountId({Substrate: account.address});67      case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();68    }69  }7071  static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {72    if ('substrate' in address) return new CrossAccountId({Substrate: address.substrate});73    else return new CrossAccountId({Ethereum: address.ethereum});74  }7576  static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {77    return encodeAddress(decodeAddress(address), ss58Format);78  }7980  static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {81    return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});82  }8384  withNormalizedSubstrate(ss58Format = 42): CrossAccountId {85    if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);86    return this;87  }8889  static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {90    return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));91  }9293  toEthereum(): CrossAccountId {94    if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});95    return this;96  }9798  static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {99    return evmToAddress(address, ss58Format);100  }101102  toSubstrate(ss58Format?: number): CrossAccountId {103    if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});104    return this;105  }106107  toLowerCase(): CrossAccountId {108    if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();109    if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();110    return this;111  }112}113114const nesting = {115  toChecksumAddress(address: string): string {116    if (typeof address === 'undefined') return '';117118    if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);119120    address = address.toLowerCase().replace(/^0x/i, '');121    const addressHash = keccakAsHex(address).replace(/^0x/i, '');122    const checksumAddress = ['0x'];123124    for (let i = 0; i < address.length; i++) {125      // If ith character is 8 to f then make it uppercase126      if (parseInt(addressHash[i], 16) > 7) {127        checksumAddress.push(address[i].toUpperCase());128      } else {129        checksumAddress.push(address[i]);130      }131    }132    return checksumAddress.join('');133  },134  tokenIdToAddress(collectionId: number, tokenId: number) {135    return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);136  },137};138139class UniqueUtil {140  static transactionStatus = {141    NOT_READY: 'NotReady',142    FAIL: 'Fail',143    SUCCESS: 'Success',144  };145146  static chainLogType = {147    EXTRINSIC: 'extrinsic',148    RPC: 'rpc',149  };150151  static getTokenAccount(token: IToken): CrossAccountId {152    return new CrossAccountId({Ethereum: this.getTokenAddress(token)});153  }154155  static getTokenAddress(token: IToken): string {156    return nesting.tokenIdToAddress(token.collectionId, token.tokenId);157  }158159  static getDefaultLogger(): ILogger {160    return {161      log(msg: any, level = 'INFO') {162        console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));163      },164      level: {165        ERROR: 'ERROR',166        WARNING: 'WARNING',167        INFO: 'INFO',168      },169    };170  }171172  static vec2str(arr: string[] | number[]) {173    return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');174  }175176  static str2vec(string: string) {177    if (typeof string !== 'string') return string;178    return Array.from(string).map(x => x.charCodeAt(0));179  }180181  static fromSeed(seed: string, ss58Format = 42) {182    const keyring = new Keyring({type: 'sr25519', ss58Format});183    return keyring.addFromUri(seed);184  }185186  static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {187    if (creationResult.status !== this.transactionStatus.SUCCESS) {188      throw Error('Unable to create collection!');189    }190191    let collectionId = null;192    creationResult.result.events.forEach(({event: {data, method, section}}) => {193      if ((section === 'common') && (method === 'CollectionCreated')) {194        collectionId = parseInt(data[0].toString(), 10);195      }196    });197198    if (collectionId === null) {199      throw Error('No CollectionCreated event was found!');200    }201202    return collectionId;203  }204205  static extractTokensFromCreationResult(creationResult: ITransactionResult): {206    success: boolean,207    tokens: { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[],208  } {209    if (creationResult.status !== this.transactionStatus.SUCCESS) {210      throw Error('Unable to create tokens!');211    }212    let success = false;213    const tokens = [] as { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[];214    creationResult.result.events.forEach(({event: {data, method, section}}) => {215      if (method === 'ExtrinsicSuccess') {216        success = true;217      } else if ((section === 'common') && (method === 'ItemCreated')) {218        tokens.push({219          collectionId: parseInt(data[0].toString(), 10),220          tokenId: parseInt(data[1].toString(), 10),221          owner: data[2].toHuman(),222          amount: data[3].toBigInt(),223        });224      }225    });226    return {success, tokens};227  }228229  static extractTokensFromBurnResult(burnResult: ITransactionResult): {230    success: boolean,231    tokens: { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[],232  } {233    if (burnResult.status !== this.transactionStatus.SUCCESS) {234      throw Error('Unable to burn tokens!');235    }236    let success = false;237    const tokens = [] as { collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint }[];238    burnResult.result.events.forEach(({event: {data, method, section}}) => {239      if (method === 'ExtrinsicSuccess') {240        success = true;241      } else if ((section === 'common') && (method === 'ItemDestroyed')) {242        tokens.push({243          collectionId: parseInt(data[0].toString(), 10),244          tokenId: parseInt(data[1].toString(), 10),245          owner: data[2].toHuman(),246          amount: data[3].toBigInt(),247        });248      }249    });250    return {success, tokens};251  }252253  static findCollectionInEvents(events: { event: IEvent }[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {254    let eventId = null;255    events.forEach(({event: {data, method, section}}) => {256      if ((section === expectedSection) && (method === expectedMethod)) {257        eventId = parseInt(data[0].toString(), 10);258      }259    });260261    if (eventId === null) {262      throw Error(`No ${expectedMethod} event was found!`);263    }264    return eventId === collectionId;265  }266267  static isTokenTransferSuccess(events: { event: IEvent }[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {268    const normalizeAddress = (address: string | ICrossAccountId) => {269      if (typeof address === 'string') return address;270      const obj = {} as any;271      Object.keys(address).forEach(k => {272        obj[k.toLocaleLowerCase()] = (address as any)[k];273      });274      if (obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);275      if (obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();276      return address;277    };278    let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;279    events.forEach(({event: {data, method, section}}) => {280      if ((section === 'common') && (method === 'Transfer')) {281        const hData = (data as any).toJSON();282        transfer = {283          collectionId: hData[0],284          tokenId: hData[1],285          from: normalizeAddress(hData[2]),286          to: normalizeAddress(hData[3]),287          amount: BigInt(hData[4]),288        };289      }290    });291    let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;292    isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);293    isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);294    isSuccess = isSuccess && amount === transfer.amount;295    return isSuccess;296  }297298  static bigIntToDecimals(number: bigint, decimals = 18) {299    const numberStr = number.toString();300    const dotPos = numberStr.length - decimals;301302    if (dotPos <= 0) {303      return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;304    } else {305      const intPart = numberStr.substring(0, dotPos);306      const fractPart = numberStr.substring(dotPos);307      return intPart + '.' + fractPart;308    }309  }310}311312class UniqueEventHelper {313  private static extractIndex(index: any): [number, number] | string {314    if (index.toRawType() === '[u8;2]') return [index[0], index[1]];315    return index.toJSON();316  }317318  private static extractSub(data: any, subTypes: any): { [key: string]: any } {319    let obj: any = {};320    let index = 0;321322    if (data.entries) {323      for (const [key, value] of data.entries()) {324        obj[key] = this.extractData(value, subTypes[index]);325        index++;326      }327    } else obj = data.toJSON();328329    return obj;330  }331332  private static toHuman(data: any) {333    return data && data.toHuman ? data.toHuman() : `${data}`;334  }335336  private static extractData(data: any, type: any): any {337    if (!type) return this.toHuman(data);338    if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();339    if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();340    if (type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);341    return this.toHuman(data);342  }343344  public static extractEvents(events: { event: any, phase: any }[]): IEvent[] {345    const parsedEvents: IEvent[] = [];346347    events.forEach((record) => {348      const {event, phase} = record;349      const types = event.typeDef;350351      const eventData: IEvent = {352        section: event.section.toString(),353        method: event.method.toString(),354        index: this.extractIndex(event.index),355        data: [],356        phase: phase.toJSON(),357      };358359      event.data.forEach((val: any, index: number) => {360        eventData.data.push(this.extractData(val, types[index]));361      });362363      parsedEvents.push(eventData);364    });365366    return parsedEvents;367  }368}369const InvalidTypeSymbol = Symbol('Invalid type');370// eslint-disable-next-line @typescript-eslint/no-unused-vars371export type Invalid<ErrorMessage> =372  | ((373    invalidType: typeof InvalidTypeSymbol,374    ..._: typeof InvalidTypeSymbol[]375  ) => typeof InvalidTypeSymbol)376  | null377  | undefined;378// Has slightly better error messages than Get379type Get2<T, P extends string, E> =380  P extends `${infer Key}.${infer Key2}` ? Key extends keyof T ? Key2 extends keyof T[Key] ? T[Key][Key2] : E : E : E;381type ForceFunction<T> = T extends (...args: any) => any ? T : (...args: any) => Invalid<'not a function'>;382type ReturnTypeWithArgs<T extends (...args: any[]) => any, ARGS_T> =383  Extract<384    T extends { (...args: infer A1): infer R1; (...args: infer A2): infer R2; (...args: infer A3): infer R3; (...args: infer A4): infer R4; } ? [A1, R1] | [A2, R2] | [A3, R3] | [A4, R4] :385    T extends { (...args: infer A1): infer R1; (...args: infer A2): infer R2; (...args: infer A3): infer R3; } ? [A1, R1] | [A2, R2] | [A3, R3] :386    T extends { (...args: infer A1): infer R1; (...args: infer A2): infer R2; } ? [A1, R1] | [A2, R2] :387    T extends { (...args: infer A1): infer R1; } ? [A1, R1] :388    never,389    [ARGS_T, any]390  >[1]391392export class ChainHelperBase {393  helperBase: any;394395  transactionStatus = UniqueUtil.transactionStatus;396  chainLogType = UniqueUtil.chainLogType;397  util: typeof UniqueUtil;398  eventHelper: typeof UniqueEventHelper;399  logger: ILogger;400  api: ApiPromise | null;401  forcedNetwork: TNetworks | null;402  network: TNetworks | null;403  wsEndpoint: string | null;404  chainLog: IUniqueHelperLog[];405  children: ChainHelperBase[];406  address: AddressGroup;407  chain: ChainGroup;408409  constructor(logger?: ILogger, helperBase?: any) {410    this.helperBase = helperBase;411412    this.util = UniqueUtil;413    this.eventHelper = UniqueEventHelper;414    if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();415    this.logger = logger;416    this.api = null;417    this.forcedNetwork = null;418    this.network = null;419    this.wsEndpoint = null;420    this.chainLog = [];421    this.children = [];422    this.address = new AddressGroup(this);423    this.chain = new ChainGroup(this);424  }425426  clone(helperCls: ChainHelperBaseConstructor, options: { [key: string]: any } = {}) {427    Object.setPrototypeOf(helperCls.prototype, this);428    const newHelper = new helperCls(this.logger, options);429430    newHelper.api = this.api;431    newHelper.network = this.network;432    newHelper.forceNetwork = this.forceNetwork;433434    this.children.push(newHelper);435436    return newHelper;437  }438439  getEndpoint(): string {440    if (this.wsEndpoint === null) throw Error('No connection was established');441    return this.wsEndpoint;442  }443444  getApi(): ApiPromise {445    if (this.api === null) throw Error('API not initialized');446    return this.api;447  }448449  async subscribeEvents(expectedEvents: { section: string, names: string[] }[]) {450    const collectedEvents: IEvent[] = [];451    const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {452      const ievents = this.eventHelper.extractEvents(events);453      ievents.forEach((event) => {454        expectedEvents.forEach((e => {455          if (event.section === e.section && e.names.includes(event.method)) {456            collectedEvents.push(event);457          }458        }));459      });460    });461    return {unsubscribe: unsubscribe as any, collectedEvents};462  }463464  clearChainLog(): void {465    this.chainLog = [];466  }467468  forceNetwork(value: TNetworks): void {469    this.forcedNetwork = value;470  }471472  async connect(wsEndpoint: string, listeners?: IApiListeners) {473    if (this.api !== null) throw Error('Already connected');474    const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);475    this.wsEndpoint = wsEndpoint;476    this.api = api;477    this.network = network;478  }479480  async disconnect() {481    for (const child of this.children) {482      child.clearApi();483    }484485    if (this.api === null) return;486    await this.api.disconnect();487    this.clearApi();488  }489490  clearApi() {491    this.api = null;492    this.network = null;493  }494495  static async detectNetwork(api: ApiPromise): Promise<TNetworks> {496    const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;497    const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];498499    if (xcmChains.indexOf(spec.specName) > -1) return spec.specName;500501    if (['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;502    return 'opal';503  }504505  static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {506    const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});507    await api.isReady;508509    const network = await this.detectNetwork(api);510511    await api.disconnect();512513    return network;514  }515516  static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{517    api: ApiPromise;518    network: TNetworks;519  }> {520    if (typeof network === 'undefined' || network === null) network = 'opal';521    const supportedRPC = {522      opal: {523        unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,524      },525      quartz: {526        unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,527      },528      unique: {529        unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,530      },531      rococo: {},532      westend: {},533      moonbeam: {},534      moonriver: {},535      acala: {},536      karura: {},537      westmint: {},538    };539    if (!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);540    const rpc = supportedRPC[network];541542    // TODO: investigate how to replace rpc in runtime543    // api._rpcCore.addUserInterfaces(rpc);544545    const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});546547    await api.isReadyOrError;548549    if (typeof listeners === 'undefined') listeners = {};550    for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {551      if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;552      api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);553    }554555    return {api, network};556  }557558  getTransactionStatus(data: { events: { event: IEvent }[], status: any }) {559    const {events, status} = data;560    if (status.isReady) {561      return this.transactionStatus.NOT_READY;562    }563    if (status.isBroadcast) {564      return this.transactionStatus.NOT_READY;565    }566    if (status.isInBlock || status.isFinalized) {567      const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');568      if (errors.length > 0) {569        return this.transactionStatus.FAIL;570      }571      if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {572        return this.transactionStatus.SUCCESS;573      }574    }575576    return this.transactionStatus.FAIL;577  }578579  signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {580    const sign = (callback: any) => {581      if (options !== null) return transaction.signAndSend(sender, options, callback);582      return transaction.signAndSend(sender, callback);583    };584    // eslint-disable-next-line no-async-promise-executor585    return new Promise(async (resolve, reject) => {586      try {587        const unsub = await sign((result: any) => {588          const status = this.getTransactionStatus(result);589590          if (status === this.transactionStatus.SUCCESS) {591            this.logger.log(`${label} successful`);592            unsub();593            resolve({result, status, blockHash: result.status.asInBlock.toHuman()});594          } else if (status === this.transactionStatus.FAIL) {595            let moduleError = null;596597            if (result.hasOwnProperty('dispatchError')) {598              const dispatchError = result['dispatchError'];599600              if (dispatchError) {601                if (dispatchError.isModule) {602                  const modErr = dispatchError.asModule;603                  const errorMeta = dispatchError.registry.findMetaError(modErr);604605                  moduleError = `${errorMeta.section}.${errorMeta.name}`;606                } else {607                  moduleError = dispatchError.toHuman();608                }609              } else {610                this.logger.log(result, this.logger.level.ERROR);611              }612            }613614            this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);615            unsub();616            reject({status, moduleError, result});617          }618        });619      } catch (e) {620        this.logger.log(e, this.logger.level.ERROR);621        reject(e);622      }623    });624  }625626  async signTransactionWithoutSending(signer: TSigner, tx: any) {627    const api = this.getApi();628    const signingInfo = await api.derive.tx.signingInfo(signer.address);629630    tx.sign(signer, {631      blockHash: api.genesisHash,632      genesisHash: api.genesisHash,633      runtimeVersion: api.runtimeVersion,634      nonce: signingInfo.nonce,635    });636637    return tx.toHex();638  }639640  async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {641    const api = this.getApi();642    const signingInfo = await api.derive.tx.signingInfo(signer.address);643644    // We need to sign the tx because645    // unsigned transactions does not have an inclusion fee646    tx.sign(signer, {647      blockHash: api.genesisHash,648      genesisHash: api.genesisHash,649      runtimeVersion: api.runtimeVersion,650      nonce: signingInfo.nonce,651    });652653    if (len === null) {654      return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;655    } else {656      return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;657    }658  }659660  constructApiCall(apiCall: string, params: any[]) {661    if (!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);662    let call = this.getApi() as any;663    for (const part of apiCall.slice(4).split('.')) {664      call = call[part];665      if (!call) {666        const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';667        throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);668      }669    }670    return call(...params);671  }672673  encodeApiCall(apiCall: string, params: any[]) {674    return this.constructApiCall(apiCall, params).method.toHex();675  }676677  async executeExtrinsic<678    E extends string,679    V extends (680...args: any) => any = ForceFunction<681      Get2<682        AugmentedSubmittables<'promise'>,683        E, (...args: any) => Invalid<'not found'>684      >685    >686  >(687    sender: TSigner,688    extrinsic: `api.tx.${E}`,689    params: Parameters<V>,690    expectSuccess = true,691    options: Partial<SignerOptions> | null = null,/*, failureMessage='expected success'*/692  ): Promise<ITransactionResult> {693    if (this.api === null) throw Error('API not initialized');694    if (!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);695696    const startTime = (new Date()).getTime();697    let result: ITransactionResult;698    let events: IEvent[] = [];699    try {700      result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;701      events = this.eventHelper.extractEvents(result.result.events);702      const errorEvent = events.find((event) => event.method == 'ExecutedFailed' || event.method == 'CreatedFailed');703      if (errorEvent)704        throw Error(errorEvent.method + ': ' + extrinsic);705    }706    catch (e) {707      if (!(e as object).hasOwnProperty('status')) throw e;708      result = e as ITransactionResult;709    }710711    const endTime = (new Date()).getTime();712713    const log = {714      executedAt: endTime,715      executionTime: endTime - startTime,716      type: this.chainLogType.EXTRINSIC,717      status: result.status,718      call: extrinsic,719      signer: this.getSignerAddress(sender),720      params,721    } as IUniqueHelperLog;722723    let errorMessage = '';724725    if (result.status !== this.transactionStatus.SUCCESS) {726      if (result.moduleError) {727        errorMessage = typeof result.moduleError === 'string'728          ? result.moduleError729          : `${Object.keys(result.moduleError)[0]}: ${Object.values(result.moduleError)[0]}`;730        log.moduleError = errorMessage;731      }732      else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;733    }734    if (events.length > 0) log.events = events;735736    this.chainLog.push(log);737738    if (expectSuccess && result.status !== this.transactionStatus.SUCCESS) {739      if (result.moduleError) throw Error(`${errorMessage}`);740      else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));741    }742    return result as any;743  }744745  async callRpc746  // <747  // K extends 'rpc' | 'query',748  // E extends string,749  // V extends (...args: any) => any = ForceFunction<750  //   Get2<751  //     K extends 'rpc' ? DecoratedRpc<'promise', RpcInterface> : QueryableStorage<'promise'>,752  //     E, (...args: any) => Invalid<'not found'>753  //   >754  // >,755  // P = Parameters<V>,756  // >757  (rpc: string, params?: any[]): Promise<any> {758759    if (typeof params === 'undefined') params = [] as any;760    if (this.api === null) throw Error('API not initialized');761    if (!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);762763    const startTime = (new Date()).getTime();764    let result;765    let error = null;766    const log = {767      type: this.chainLogType.RPC,768      call: rpc,769      params,770    } as any as IUniqueHelperLog;771772    try {773      result = await this.constructApiCall(rpc, params as any);774    }775    catch (e) {776      error = e;777    }778779    const endTime = (new Date()).getTime();780781    log.executedAt = endTime;782    log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';783    log.executionTime = endTime - startTime;784785    this.chainLog.push(log);786787    if (error !== null) throw error;788789    return result;790  }791792  getSignerAddress(signer: IKeyringPair | string): string {793    if (typeof signer === 'string') return signer;794    return signer.address;795  }796797  fetchAllPalletNames(): string[] {798    if (this.api === null) throw Error('API not initialized');799    return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase()).sort();800  }801802  fetchMissingPalletNames(requiredPallets: readonly string[]): string[] {803    const palletNames = this.fetchAllPalletNames();804    return requiredPallets.filter(p => !palletNames.includes(p));805  }806}807808809class HelperGroup<T extends ChainHelperBase> {810  helper: T;811812  constructor(uniqueHelper: T) {813    this.helper = uniqueHelper;814  }815}816817818class CollectionGroup extends HelperGroup<UniqueHelper> {819  /**820 * Get number of blocks when sponsored transaction is available.821 *822 * @param collectionId ID of collection823 * @param tokenId ID of token824 * @param addressObj address for which the sponsorship is checked825 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});826 * @returns number of blocks or null if sponsorship hasn't been set827 */828  async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {829    return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();830  }831832  /**833   * Get the number of created collections.834   *835   * @returns number of created collections836   */837  async getTotalCount(): Promise<number> {838    return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();839  }840841  /**842   * Get information about the collection with additional data,843   * including the number of tokens it contains, its administrators,844   * the normalized address of the collection's owner, and decoded name and description.845   *846   * @param collectionId ID of collection847   * @example await getData(2)848   * @returns collection information object849   */850  async getData(collectionId: number): Promise<{851    id: number;852    name: string;853    description: string;854    tokensCount: number;855    admins: CrossAccountId[];856    normalizedOwner: TSubstrateAccount;857    raw: any858  } | null> {859    const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);860    const humanCollection = collection.toHuman(), collectionData = {861      id: collectionId, name: null, description: null, tokensCount: 0, admins: [],862      raw: humanCollection,863    } as any, jsonCollection = collection.toJSON();864    if (humanCollection === null) return null;865    collectionData.raw.limits = jsonCollection.limits;866    collectionData.raw.permissions = jsonCollection.permissions;867    collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);868    for (const key of ['name', 'description']) {869      collectionData[key] = this.helper.util.vec2str(humanCollection[key]);870    }871872    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))873      ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)874      : 0;875    collectionData.admins = await this.getAdmins(collectionId);876877    return collectionData;878  }879880  /**881   * Get the addresses of the collection's administrators, optionally normalized.882   *883   * @param collectionId ID of collection884   * @param normalize whether to normalize the addresses to the default ss58 format885   * @example await getAdmins(1)886   * @returns array of administrators887   */888  async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {889    const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();890891    return normalize892      ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())893      : admins;894  }895896  /**897   * Get the addresses added to the collection allow-list, optionally normalized.898   * @param collectionId ID of collection899   * @param normalize whether to normalize the addresses to the default ss58 format900   * @example await getAllowList(1)901   * @returns array of allow-listed addresses902   */903  async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {904    const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();905    return normalize906      ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())907      : allowListed;908  }909910  /**911   * Get the effective limits of the collection instead of null for default values912   *913   * @param collectionId ID of collection914   * @example await getEffectiveLimits(2)915   * @returns object of collection limits916   */917  async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {918    return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();919  }920921  /**922   * Burns the collection if the signer has sufficient permissions and collection is empty.923   *924   * @param signer keyring of signer925   * @param collectionId ID of collection926   * @example await helper.collection.burn(aliceKeyring, 3);927   * @returns ```true``` if extrinsic success, otherwise ```false```928   */929  async burn(signer: TSigner, collectionId: number): Promise<boolean> {930    const result = await this.helper.executeExtrinsic(931      signer,932      'api.tx.unique.destroyCollection', [collectionId],933      true,934    );935936    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');937  }938939  /**940   * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.941   *942   * @param signer keyring of signer943   * @param collectionId ID of collection944   * @param sponsorAddress Sponsor substrate address945   * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")946   * @returns ```true``` if extrinsic success, otherwise ```false```947   */948  async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {949    const result = await this.helper.executeExtrinsic(950      signer,951      'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],952      true,953    );954955    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');956  }957958  /**959   * Confirms consent to sponsor the collection on behalf of the signer.960   *961   * @param signer keyring of signer962   * @param collectionId ID of collection963   * @example confirmSponsorship(aliceKeyring, 10)964   * @returns ```true``` if extrinsic success, otherwise ```false```965   */966  async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {967    const result = await this.helper.executeExtrinsic(968      signer,969      'api.tx.unique.confirmSponsorship', [collectionId],970      true,971    );972973    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');974  }975976  /**977   * Removes the sponsor of a collection, regardless if it consented or not.978   *979   * @param signer keyring of signer980   * @param collectionId ID of collection981   * @example removeSponsor(aliceKeyring, 10)982   * @returns ```true``` if extrinsic success, otherwise ```false```983   */984  async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {985    const result = await this.helper.executeExtrinsic(986      signer,987      'api.tx.unique.removeCollectionSponsor', [collectionId],988      true,989    );990991    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');992  }993994  /**995   * Sets the limits of the collection. At least one limit must be specified for a correct call.996   *997   * @param signer keyring of signer998   * @param collectionId ID of collection999   * @param limits collection limits object1000   * @example1001   * await setLimits(1002   *   aliceKeyring,1003   *   10,1004   *   {1005   *     sponsorTransferTimeout: 0,1006   *     ownerCanDestroy: false1007   *   }1008   * )1009   * @returns ```true``` if extrinsic success, otherwise ```false```1010   */1011  async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {1012    const result = await this.helper.executeExtrinsic(1013      signer,1014      'api.tx.unique.setCollectionLimits', [collectionId, limits],1015      true,1016    );10171018    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');1019  }10201021  /**1022   * Changes the owner of the collection to the new Substrate address.1023   *1024   * @param signer keyring of signer1025   * @param collectionId ID of collection1026   * @param ownerAddress substrate address of new owner1027   * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")1028   * @returns ```true``` if extrinsic success, otherwise ```false```1029   */1030  async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {1031    const result = await this.helper.executeExtrinsic(1032      signer,1033      'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],1034      true,1035    );10361037    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');1038  }10391040  /**1041   * Adds a collection administrator.1042   *1043   * @param signer keyring of signer1044   * @param collectionId ID of collection1045   * @param adminAddressObj Administrator address (substrate or ethereum)1046   * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})1047   * @returns ```true``` if extrinsic success, otherwise ```false```1048   */1049  async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1050    const result = await this.helper.executeExtrinsic(1051      signer,1052      'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],1053      true,1054    );10551056    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');1057  }10581059  /**1060   * Removes a collection administrator.1061   *1062   * @param signer keyring of signer1063   * @param collectionId ID of collection1064   * @param adminAddressObj Administrator address (substrate or ethereum)1065   * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})1066   * @returns ```true``` if extrinsic success, otherwise ```false```1067   */1068  async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1069    const result = await this.helper.executeExtrinsic(1070      signer,1071      'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],1072      true,1073    );10741075    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1076  }10771078  /**1079   * Check if user is in allow list.1080   *1081   * @param collectionId ID of collection1082   * @param user Account to check1083   * @example await getAdmins(1)1084   * @returns is user in allow list1085   */1086  async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1087    return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1088  }10891090  /**1091   * Adds an address to allow list1092   * @param signer keyring of signer1093   * @param collectionId ID of collection1094   * @param addressObj address to add to the allow list1095   * @returns ```true``` if extrinsic success, otherwise ```false```1096   */1097  async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1098    const result = await this.helper.executeExtrinsic(1099      signer,1100      'api.tx.unique.addToAllowList', [collectionId, addressObj],1101      true,1102    );11031104    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1105  }11061107  /**1108   * Removes an address from allow list1109   *1110   * @param signer keyring of signer1111   * @param collectionId ID of collection1112   * @param addressObj address to remove from the allow list1113   * @returns ```true``` if extrinsic success, otherwise ```false```1114   */1115  async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1116    const result = await this.helper.executeExtrinsic(1117      signer,1118      'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1119      true,1120    );11211122    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1123  }11241125  /**1126   * Sets onchain permissions for selected collection.1127   *1128   * @param signer keyring of signer1129   * @param collectionId ID of collection1130   * @param permissions collection permissions object1131   * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1132   * @returns ```true``` if extrinsic success, otherwise ```false```1133   */1134  async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1135    const result = await this.helper.executeExtrinsic(1136      signer,1137      'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1138      true,1139    );11401141    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1142  }11431144  /**1145   * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1146   *1147   * @param signer keyring of signer1148   * @param collectionId ID of collection1149   * @param permissions nesting permissions object1150   * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1151   * @returns ```true``` if extrinsic success, otherwise ```false```1152   */1153  async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1154    return await this.setPermissions(signer, collectionId, {nesting: permissions});1155  }11561157  /**1158   * Disables nesting for selected collection.1159   *1160   * @param signer keyring of signer1161   * @param collectionId ID of collection1162   * @example disableNesting(aliceKeyring, 10);1163   * @returns ```true``` if extrinsic success, otherwise ```false```1164   */1165  async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1166    return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1167  }11681169  /**1170   * Sets onchain properties to the collection.1171   *1172   * @param signer keyring of signer1173   * @param collectionId ID of collection1174   * @param properties array of property objects1175   * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1176   * @returns ```true``` if extrinsic success, otherwise ```false```1177   */1178  async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1179    const result = await this.helper.executeExtrinsic(1180      signer,1181      'api.tx.unique.setCollectionProperties', [collectionId, properties],1182      true,1183    );11841185    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1186  }11871188  /**1189   * Get collection properties.1190   *1191   * @param collectionId ID of collection1192   * @param propertyKeys optionally filter the returned properties to only these keys1193   * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1194   * @returns array of key-value pairs1195   */1196  async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1197    return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1198  }11991200  async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1201    const api = this.helper.getApi();1202    const props = (await api.query.common.collectionProperties(collectionId)).toJSON();12031204    return (props! as any).consumedSpace;1205  }12061207  async getCollectionOptions(collectionId: number) {1208    return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1209  }12101211  /**1212   * Deletes onchain properties from the collection.1213   *1214   * @param signer keyring of signer1215   * @param collectionId ID of collection1216   * @param propertyKeys array of property keys to delete1217   * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1218   * @returns ```true``` if extrinsic success, otherwise ```false```1219   */1220  async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1221    const result = await this.helper.executeExtrinsic(1222      signer,1223      'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1224      true,1225    );12261227    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1228  }12291230  /**1231   * Changes the owner of the token.1232   *1233   * @param signer keyring of signer1234   * @param collectionId ID of collection1235   * @param tokenId ID of token1236   * @param addressObj address of a new owner1237   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1238   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1239   * @returns true if the token success, otherwise false1240   */1241  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1242    const result = await this.helper.executeExtrinsic(1243      signer,1244      'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1245      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1246    );12471248    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1249  }12501251  /**1252   *1253   * Change ownership of a token(s) on behalf of the owner.1254   *1255   * @param signer keyring of signer1256   * @param collectionId ID of collection1257   * @param tokenId ID of token1258   * @param fromAddressObj address on behalf of which the token will be sent1259   * @param toAddressObj new token owner1260   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1261   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1262   * @returns true if the token success, otherwise false1263   */1264  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1265    const result = await this.helper.executeExtrinsic(1266      signer,1267      'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1268      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1269    );1270    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1271  }12721273  /**1274   *1275   * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1276   *1277   * @param signer keyring of signer1278   * @param collectionId ID of collection1279   * @param tokenId ID of token1280   * @param amount amount of tokens to be burned. For NFT must be set to 1n1281   * @example burnToken(aliceKeyring, 10, 5);1282   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1283   */1284  async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount = 1n): Promise<boolean> {1285    const burnResult = await this.helper.executeExtrinsic(1286      signer,1287      'api.tx.unique.burnItem', [collectionId, tokenId, amount],1288      true, // `Unable to burn token for ${label}`,1289    );1290    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1291    if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1292    return burnedTokens.success;1293  }12941295  /**1296   * Destroys a concrete instance of NFT on behalf of the owner1297   *1298   * @param signer keyring of signer1299   * @param collectionId ID of collection1300   * @param tokenId ID of token1301   * @param fromAddressObj address on behalf of which the token will be burnt1302   * @param amount amount of tokens to be burned. For NFT must be set to 1n1303   * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1304   * @returns ```true``` if extrinsic success, otherwise ```false```1305   */1306  async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1307    const burnResult = await this.helper.executeExtrinsic(1308      signer,1309      'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1310      true, // `Unable to burn token from for ${label}`,1311    );1312    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1313    return burnedTokens.success && burnedTokens.tokens.length > 0;1314  }13151316  /**1317   * Set, change, or remove approved address to transfer the ownership of the NFT.1318   *1319   * @param signer keyring of signer1320   * @param collectionId ID of collection1321   * @param tokenId ID of token1322   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1323   * @param amount amount of token to be approved. For NFT must be set to 1n1324   * @returns ```true``` if extrinsic success, otherwise ```false```1325   */1326  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1327    const approveResult = await this.helper.executeExtrinsic(1328      signer,1329      'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1330      true, // `Unable to approve token for ${label}`,1331    );13321333    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1334  }13351336  /**1337   * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1338   *1339   * @param signer keyring of signer1340   * @param collectionId ID of collection1341   * @param tokenId ID of token1342   * @param fromAddressObj Signer's Ethereum address containing her tokens1343   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1344   * @param amount amount of token to be approved. For NFT must be set to 1n1345   * @returns ```true``` if extrinsic success, otherwise ```false```1346   */1347  async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {1348    const approveResult = await this.helper.executeExtrinsic(1349      signer,1350      'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1351      true, // `Unable to approve token for ${label}`,1352    );13531354    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1355  }13561357  /**1358   * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1359   *1360   * @param signer keyring of signer1361   * @param collectionId ID of collection1362   * @param tokenId ID of token1363   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1364   * @param amount amount of token to be approved. For NFT must be set to 1n1365   * @returns ```true``` if extrinsic success, otherwise ```false```1366   */1367  async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1368    const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();1369    return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);1370  }13711372  /**1373   * Get the amount of token pieces approved to transfer or burn. Normally 0.1374   *1375   * @param collectionId ID of collection1376   * @param tokenId ID of token1377   * @param toAccountObj address which is approved to use token pieces1378   * @param fromAccountObj address which may have allowed the use of its owned tokens1379   * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1380   * @returns number of approved to transfer pieces1381   */1382  async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1383    return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1384  }13851386  /**1387   * Get the last created token ID in a collection1388   *1389   * @param collectionId ID of collection1390   * @example getLastTokenId(10);1391   * @returns id of the last created token1392   */1393  async getLastTokenId(collectionId: number): Promise<number> {1394    return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1395  }13961397  /**1398   * Check if token exists1399   *1400   * @param collectionId ID of collection1401   * @param tokenId ID of token1402   * @example doesTokenExist(10, 20);1403   * @returns true if the token exists, otherwise false1404   */1405  async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1406    return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1407  }1408}14091410class NFTnRFT extends CollectionGroup {1411  /**1412   * Get tokens owned by account1413   *1414   * @param collectionId ID of collection1415   * @param addressObj tokens owner1416   * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1417   * @returns array of token ids owned by account1418   */1419  async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1420    return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1421  }14221423  /**1424   * Get token data1425   *1426   * @param collectionId ID of collection1427   * @param tokenId ID of token1428   * @param propertyKeys optionally filter the token properties to only these keys1429   * @param blockHashAt optionally query the data at some block with this hash1430   * @example getToken(10, 5);1431   * @returns human readable token data1432   */1433  async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1434    properties: IProperty[];1435    owner: CrossAccountId;1436    normalizedOwner: CrossAccountId;1437  } | null> {1438    let tokenData;1439    if (typeof blockHashAt === 'undefined') {1440      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1441    }1442    else {1443      if (propertyKeys.length == 0) {1444        const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1445        if (!collection) return null;1446        propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1447      }1448      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1449    }1450    tokenData = tokenData.toHuman();1451    if (tokenData === null || tokenData.owner === null) return null;1452    const owner = {} as any;1453    for (const key of Object.keys(tokenData.owner)) {1454      owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1455        ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1456        : tokenData.owner[key];1457    }1458    tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1459    return tokenData;1460  }14611462  /**1463   * Get token's owner1464   * @param collectionId ID of collection1465   * @param tokenId ID of token1466   * @param blockHashAt optionally query the data at the block with this hash1467   * @example getTokenOwner(10, 5);1468   * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1469   */1470  async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1471    let owner;1472    if (typeof blockHashAt === 'undefined') {1473      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1474    } else {1475      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1476    }1477    return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1478  }14791480  /**1481   * Recursively find the address that owns the token1482   * @param collectionId ID of collection1483   * @param tokenId ID of token1484   * @param blockHashAt1485   * @example getTokenTopmostOwner(10, 5);1486   * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1487   */1488  async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1489    let owner;1490    if (typeof blockHashAt === 'undefined') {1491      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1492    } else {1493      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1494    }14951496    if (owner === null) return null;14971498    return owner.toHuman();1499  }15001501  /**1502   * Nest one token into another1503   * @param signer keyring of signer1504   * @param tokenObj token to be nested1505   * @param rootTokenObj token to be parent1506   * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1507   * @returns ```true``` if extrinsic success, otherwise ```false```1508   */1509  async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1510    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1511    const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1512    if (!result) {1513      throw Error('Unable to nest token!');1514    }1515    return result;1516  }15171518  /**1519     * Remove token from nested state1520     * @param signer keyring of signer1521     * @param tokenObj token to unnest1522     * @param rootTokenObj parent of a token1523     * @param toAddressObj address of a new token owner1524     * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1525     * @returns ```true``` if extrinsic success, otherwise ```false```1526     */1527  async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1528    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1529    const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1530    if (!result) {1531      throw Error('Unable to unnest token!');1532    }1533    return result;1534  }15351536  /**1537   * Set permissions to change token properties1538   *1539   * @param signer keyring of signer1540   * @param collectionId ID of collection1541   * @param permissions permissions to change a property by the collection admin or token owner1542   * @example setTokenPropertyPermissions(1543   *   aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1544   * )1545   * @returns true if extrinsic success otherwise false1546   */1547  async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1548    const result = await this.helper.executeExtrinsic(1549      signer,1550      'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1551      true,1552    );15531554    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1555  }15561557  /**1558   * Get token property permissions.1559   *1560   * @param collectionId ID of collection1561   * @param propertyKeys optionally filter the returned property permissions to only these keys1562   * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1563   * @returns array of key-permission pairs1564   */1565  async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1566    return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1567  }15681569  /**1570   * Set token properties1571   *1572   * @param signer keyring of signer1573   * @param collectionId ID of collection1574   * @param tokenId ID of token1575   * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1576   * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1577   * @returns ```true``` if extrinsic success, otherwise ```false```1578   */1579  async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1580    const result = await this.helper.executeExtrinsic(1581      signer,1582      'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1583      true,1584    );15851586    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1587  }15881589  /**1590   * Get properties, metadata assigned to a token.1591   *1592   * @param collectionId ID of collection1593   * @param tokenId ID of token1594   * @param propertyKeys optionally filter the returned properties to only these keys1595   * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1596   * @returns array of key-value pairs1597   */1598  async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1599    return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1600  }16011602  /**1603   * Delete the provided properties of a token1604   * @param signer keyring of signer1605   * @param collectionId ID of collection1606   * @param tokenId ID of token1607   * @param propertyKeys property keys to be deleted1608   * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1609   * @returns ```true``` if extrinsic success, otherwise ```false```1610   */1611  async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1612    const result = await this.helper.executeExtrinsic(1613      signer,1614      'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1615      true,1616    );16171618    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1619  }16201621  /**1622   * Mint new collection1623   *1624   * @param signer keyring of signer1625   * @param collectionOptions basic collection options and properties1626   * @param mode NFT or RFT type of a collection1627   * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1628   * @returns object of the created collection1629   */1630  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1631    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1632    collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1633    for (const key of ['name', 'description', 'tokenPrefix']) {1634      if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1635    }1636    const creationResult = await this.helper.executeExtrinsic(1637      signer,1638      'api.tx.unique.createCollectionEx', [collectionOptions],1639      true, // errorLabel,1640    );1641    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1642  }16431644  getCollectionObject(_collectionId: number): any {1645    return null;1646  }16471648  getTokenObject(_collectionId: number, _tokenId: number): any {1649    return null;1650  }16511652  /**1653   * Tells whether the given `owner` approves the `operator`.1654   * @param collectionId ID of collection1655   * @param owner owner address1656   * @param operator operator addrees1657   * @returns true if operator is enabled1658   */1659  async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1660    return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1661  }16621663  /** Sets or unsets the approval of a given operator.1664   *  The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1665   *  @param operator Operator1666   *  @param approved Should operator status be granted or revoked?1667   *  @returns ```true``` if extrinsic success, otherwise ```false```1668   */1669  async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1670    const result = await this.helper.executeExtrinsic(1671      signer,1672      'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1673      true,1674    );1675    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1676  }1677}167816791680class NFTGroup extends NFTnRFT {1681  /**1682   * Get collection object1683   * @param collectionId ID of collection1684   * @example getCollectionObject(2);1685   * @returns instance of UniqueNFTCollection1686   */1687  getCollectionObject(collectionId: number): UniqueNFTCollection {1688    return new UniqueNFTCollection(collectionId, this.helper);1689  }16901691  /**1692   * Get token object1693   * @param collectionId ID of collection1694   * @param tokenId ID of token1695   * @example getTokenObject(10, 5);1696   * @returns instance of UniqueNFTToken1697   */1698  getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1699    return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1700  }17011702  /**1703   * Is token approved to transfer1704   * @param collectionId ID of collection1705   * @param tokenId ID of token1706   * @param toAccountObj address to be approved1707   * @returns ```true``` if extrinsic success, otherwise ```false```1708   */1709  async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1710    return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1711  }17121713  /**1714   * Changes the owner of the token.1715   *1716   * @param signer keyring of signer1717   * @param collectionId ID of collection1718   * @param tokenId ID of token1719   * @param addressObj address of a new owner1720   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1721   * @returns ```true``` if extrinsic success, otherwise ```false```1722   */1723  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1724    return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1725  }17261727  /**1728   *1729   * Change ownership of a NFT on behalf of the owner.1730   *1731   * @param signer keyring of signer1732   * @param collectionId ID of collection1733   * @param tokenId ID of token1734   * @param fromAddressObj address on behalf of which the token will be sent1735   * @param toAddressObj new token owner1736   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1737   * @returns ```true``` if extrinsic success, otherwise ```false```1738   */1739  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1740    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1741  }17421743  /**1744   * Get tokens nested in the provided token1745   * @param collectionId ID of collection1746   * @param tokenId ID of token1747   * @param blockHashAt optionally query the data at the block with this hash1748   * @example getTokenChildren(10, 5);1749   * @returns tokens whose depth of nesting is <= 51750   */1751  async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1752    let children;1753    if (typeof blockHashAt === 'undefined') {1754      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1755    } else {1756      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1757    }17581759    return children.toJSON().map((x: any) => {1760      return {collectionId: x.collection, tokenId: x.token};1761    });1762  }17631764  /**1765   * Mint new collection1766   * @param signer keyring of signer1767   * @param collectionOptions Collection options1768   * @example1769   * mintCollection(aliceKeyring, {1770   *   name: 'New',1771   *   description: 'New collection',1772   *   tokenPrefix: 'NEW',1773   * })1774   * @returns object of the created collection1775   */1776  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1777    return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1778  }17791780  /**1781   * Mint new token1782   * @param signer keyring of signer1783   * @param data token data1784   * @returns created token object1785   */1786  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1787    const creationResult = await this.helper.executeExtrinsic(1788      signer,1789      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1790        NFT: {1791          properties: data.properties,1792        },1793      }],1794      true,1795    );1796    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1797    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1798    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1799    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1800  }18011802  /**1803   * Mint multiple NFT tokens1804   * @param signer keyring of signer1805   * @param collectionId ID of collection1806   * @param tokens array of tokens with owner and properties1807   * @example1808   * mintMultipleTokens(aliceKeyring, 10, [{1809   *     owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1810   *     properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1811   *   },{1812   *     owner: {Ethereum: "0x9F0583DbB855d..."},1813   *     properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1814   * }]);1815   * @returns ```true``` if extrinsic success, otherwise ```false```1816   */1817  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: { owner: ICrossAccountId, properties?: IProperty[] }[]): Promise<UniqueNFToken[]> {1818    const creationResult = await this.helper.executeExtrinsic(1819      signer,1820      'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1821      true,1822    );1823    const collection = this.getCollectionObject(collectionId);1824    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1825  }18261827  /**1828   * Mint multiple NFT tokens with one owner1829   * @param signer keyring of signer1830   * @param collectionId ID of collection1831   * @param owner tokens owner1832   * @param tokens array of tokens with owner and properties1833   * @example1834   * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1835   *   properties: [{1836   *   key: "gender",1837   *   value: "female",1838   *  },{1839   *   key: "age",1840   *   value: "33",1841   *  }],1842   * }]);1843   * @returns array of newly created tokens1844   */1845  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: { properties?: IProperty[] }[]): Promise<UniqueNFToken[]> {1846    const rawTokens = [];1847    for (const token of tokens) {1848      const raw = {NFT: {properties: token.properties}};1849      rawTokens.push(raw);1850    }1851    const creationResult = await this.helper.executeExtrinsic(1852      signer,1853      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1854      true,1855    );1856    const collection = this.getCollectionObject(collectionId);1857    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1858  }18591860  /**1861   * Set, change, or remove approved address to transfer the ownership of the NFT.1862   *1863   * @param signer keyring of signer1864   * @param collectionId ID of collection1865   * @param tokenId ID of token1866   * @param toAddressObj address to approve1867   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1868   * @returns ```true``` if extrinsic success, otherwise ```false```1869   */1870  approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {1871    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1872  }1873}187418751876class RFTGroup extends NFTnRFT {1877  /**1878   * Get collection object1879   * @param collectionId ID of collection1880   * @example getCollectionObject(2);1881   * @returns instance of UniqueRFTCollection1882   */1883  getCollectionObject(collectionId: number): UniqueRFTCollection {1884    return new UniqueRFTCollection(collectionId, this.helper);1885  }18861887  /**1888   * Get token object1889   * @param collectionId ID of collection1890   * @param tokenId ID of token1891   * @example getTokenObject(10, 5);1892   * @returns instance of UniqueNFTToken1893   */1894  getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1895    return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1896  }18971898  /**1899   * Get top 10 token owners with the largest number of pieces1900   * @param collectionId ID of collection1901   * @param tokenId ID of token1902   * @example getTokenTop10Owners(10, 5);1903   * @returns array of top 10 owners1904   */1905  async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1906    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1907  }19081909  /**1910   * Get number of pieces owned by address1911   * @param collectionId ID of collection1912   * @param tokenId ID of token1913   * @param addressObj address token owner1914   * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1915   * @returns number of pieces ownerd by address1916   */1917  async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1918    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1919  }19201921  /**1922   * Transfer pieces of token to another address1923   * @param signer keyring of signer1924   * @param collectionId ID of collection1925   * @param tokenId ID of token1926   * @param addressObj address of a new owner1927   * @param amount number of pieces to be transfered1928   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1929   * @returns ```true``` if extrinsic success, otherwise ```false```1930   */1931  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1932    return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1933  }19341935  /**1936   * Change ownership of some pieces of RFT on behalf of the owner.1937   * @param signer keyring of signer1938   * @param collectionId ID of collection1939   * @param tokenId ID of token1940   * @param fromAddressObj address on behalf of which the token will be sent1941   * @param toAddressObj new token owner1942   * @param amount number of pieces to be transfered1943   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1944   * @returns ```true``` if extrinsic success, otherwise ```false```1945   */1946  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {1947    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1948  }19491950  /**1951   * Mint new collection1952   * @param signer keyring of signer1953   * @param collectionOptions Collection options1954   * @example1955   * mintCollection(aliceKeyring, {1956   *   name: 'New',1957   *   description: 'New collection',1958   *   tokenPrefix: 'NEW',1959   * })1960   * @returns object of the created collection1961   */1962  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1963    return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1964  }19651966  /**1967   * Mint new token1968   * @param signer keyring of signer1969   * @param data token data1970   * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1971   * @returns created token object1972   */1973  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1974    const creationResult = await this.helper.executeExtrinsic(1975      signer,1976      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1977        ReFungible: {1978          pieces: data.pieces,1979          properties: data.properties,1980        },1981      }],1982      true,1983    );1984    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1985    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1986    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1987    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1988  }19891990  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: { owner: ICrossAccountId, pieces: bigint, properties?: IProperty[] }[]): Promise<UniqueRFToken[]> {1991    throw Error('Not implemented');1992    const creationResult = await this.helper.executeExtrinsic(1993      signer,1994      'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1995      true, // `Unable to mint RFT tokens for ${label}`,1996    );1997    const collection = this.getCollectionObject(collectionId);1998    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1999  }20002001  /**2002   * Mint multiple RFT tokens with one owner2003   * @param signer keyring of signer2004   * @param collectionId ID of collection2005   * @param owner tokens owner2006   * @param tokens array of tokens with properties and pieces2007   * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);2008   * @returns array of newly created RFT tokens2009   */2010  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: { pieces: bigint, properties?: IProperty[] }[]): Promise<UniqueRFToken[]> {2011    const rawTokens = [];2012    for (const token of tokens) {2013      const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};2014      rawTokens.push(raw);2015    }2016    const creationResult = await this.helper.executeExtrinsic(2017      signer,2018      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2019      true,2020    );2021    const collection = this.getCollectionObject(collectionId);2022    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));2023  }20242025  /**2026   * Destroys a concrete instance of RFT.2027   * @param signer keyring of signer2028   * @param collectionId ID of collection2029   * @param tokenId ID of token2030   * @param amount number of pieces to be burnt2031   * @example burnToken(aliceKeyring, 10, 5);2032   * @returns ```true``` if the extrinsic is successful, otherwise ```false```2033   */2034  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount = 1n): Promise<boolean> {2035    return await super.burnToken(signer, collectionId, tokenId, amount);2036  }20372038  /**2039   * Destroys a concrete instance of RFT on behalf of the owner.2040   * @param signer keyring of signer2041   * @param collectionId ID of collection2042   * @param tokenId ID of token2043   * @param fromAddressObj address on behalf of which the token will be burnt2044   * @param amount number of pieces to be burnt2045   * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)2046   * @returns ```true``` if extrinsic success, otherwise ```false```2047   */2048  async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {2049    return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);2050  }20512052  /**2053   * Set, change, or remove approved address to transfer the ownership of the RFT.2054   *2055   * @param signer keyring of signer2056   * @param collectionId ID of collection2057   * @param tokenId ID of token2058   * @param toAddressObj address to approve2059   * @param amount number of pieces to be approved2060   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);2061   * @returns true if the token success, otherwise false2062   */2063  approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {2064    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);2065  }20662067  /**2068   * Get total number of pieces2069   * @param collectionId ID of collection2070   * @param tokenId ID of token2071   * @example getTokenTotalPieces(10, 5);2072   * @returns number of pieces2073   */2074  async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {2075    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();2076  }20772078  /**2079   * Change number of token pieces. Signer must be the owner of all token pieces.2080   * @param signer keyring of signer2081   * @param collectionId ID of collection2082   * @param tokenId ID of token2083   * @param amount new number of pieces2084   * @example repartitionToken(aliceKeyring, 10, 5, 12345n);2085   * @returns true if the repartion was success, otherwise false2086   */2087  async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {2088    const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);2089    const repartitionResult = await this.helper.executeExtrinsic(2090      signer,2091      'api.tx.unique.repartition', [collectionId, tokenId, amount],2092      true,2093    );2094    if (currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');2095    return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');2096  }2097}209820992100class FTGroup extends CollectionGroup {2101  /**2102   * Get collection object2103   * @param collectionId ID of collection2104   * @example getCollectionObject(2);2105   * @returns instance of UniqueFTCollection2106   */2107  getCollectionObject(collectionId: number): UniqueFTCollection {2108    return new UniqueFTCollection(collectionId, this.helper);2109  }21102111  /**2112   * Mint new fungible collection2113   * @param signer keyring of signer2114   * @param collectionOptions Collection options2115   * @param decimalPoints number of token decimals2116   * @example2117   * mintCollection(aliceKeyring, {2118   *   name: 'New',2119   *   description: 'New collection',2120   *   tokenPrefix: 'NEW',2121   * }, 18)2122   * @returns newly created fungible collection2123   */2124  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2125    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object2126    if (collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2127    collectionOptions.mode = {fungible: decimalPoints};2128    for (const key of ['name', 'description', 'tokenPrefix']) {2129      if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);2130    }2131    const creationResult = await this.helper.executeExtrinsic(2132      signer,2133      'api.tx.unique.createCollectionEx', [collectionOptions],2134      true,2135    );2136    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2137  }21382139  /**2140   * Mint tokens2141   * @param signer keyring of signer2142   * @param collectionId ID of collection2143   * @param owner address owner of new tokens2144   * @param amount amount of tokens to be meanted2145   * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2146   * @returns ```true``` if extrinsic success, otherwise ```false```2147   */2148  async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2149    const creationResult = await this.helper.executeExtrinsic(2150      signer,2151      'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2152        Fungible: {2153          value: amount,2154        },2155      }],2156      true, // `Unable to mint fungible tokens for ${label}`,2157    );2158    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2159  }21602161  /**2162   * Mint multiple Fungible tokens with one owner2163   * @param signer keyring of signer2164   * @param collectionId ID of collection2165   * @param owner tokens owner2166   * @param tokens array of tokens with properties and pieces2167   * @returns ```true``` if extrinsic success, otherwise ```false```2168   */2169  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: { value: bigint }[], owner: ICrossAccountId): Promise<boolean> {2170    const rawTokens = [];2171    for (const token of tokens) {2172      const raw = {Fungible: {Value: token.value}};2173      rawTokens.push(raw);2174    }2175    const creationResult = await this.helper.executeExtrinsic(2176      signer,2177      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2178      true,2179    );2180    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2181  }21822183  /**2184   * Get the top 10 owners with the largest balance for the Fungible collection2185   * @param collectionId ID of collection2186   * @example getTop10Owners(10);2187   * @returns array of ```ICrossAccountId```2188   */2189  async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2190    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2191  }21922193  /**2194   * Get account balance2195   * @param collectionId ID of collection2196   * @param addressObj address of owner2197   * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2198   * @returns amount of fungible tokens owned by address2199   */2200  async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2201    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2202  }22032204  /**2205   * Transfer tokens to address2206   * @param signer keyring of signer2207   * @param collectionId ID of collection2208   * @param toAddressObj address recipient2209   * @param amount amount of tokens to be sent2210   * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2211   * @returns ```true``` if extrinsic success, otherwise ```false```2212   */2213  async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount = 1n) {2214    return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2215  }22162217  /**2218   * Transfer some tokens on behalf of the owner.2219   * @param signer keyring of signer2220   * @param collectionId ID of collection2221   * @param fromAddressObj address on behalf of which tokens will be sent2222   * @param toAddressObj address where token to be sent2223   * @param amount number of tokens to be sent2224   * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2225   * @returns ```true``` if extrinsic success, otherwise ```false```2226   */2227  async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {2228    return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2229  }22302231  /**2232   * Destroy some amount of tokens2233   * @param signer keyring of signer2234   * @param collectionId ID of collection2235   * @param amount amount of tokens to be destroyed2236   * @example burnTokens(aliceKeyring, 10, 1000n);2237   * @returns ```true``` if extrinsic success, otherwise ```false```2238   */2239  async burnTokens(signer: IKeyringPair, collectionId: number, amount = 1n): Promise<boolean> {2240    return await super.burnToken(signer, collectionId, 0, amount);2241  }22422243  /**2244   * Burn some tokens on behalf of the owner.2245   * @param signer keyring of signer2246   * @param collectionId ID of collection2247   * @param fromAddressObj address on behalf of which tokens will be burnt2248   * @param amount amount of tokens to be burnt2249   * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2250   * @returns ```true``` if extrinsic success, otherwise ```false```2251   */2252  async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount = 1n): Promise<boolean> {2253    return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2254  }22552256  /**2257   * Get total collection supply2258   * @param collectionId2259   * @returns2260   */2261  async getTotalPieces(collectionId: number): Promise<bigint> {2262    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2263  }22642265  /**2266   * Set, change, or remove approved address to transfer tokens.2267   *2268   * @param signer keyring of signer2269   * @param collectionId ID of collection2270   * @param toAddressObj address to be approved2271   * @param amount amount of tokens to be approved2272   * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2273   * @returns ```true``` if extrinsic success, otherwise ```false```2274   */2275  approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount = 1n) {2276    return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2277  }22782279  /**2280   * Get amount of fungible tokens approved to transfer2281   * @param collectionId ID of collection2282   * @param fromAddressObj owner of tokens2283   * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2284   * @returns number of tokens approved for the transfer2285   */2286  getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2287    return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2288  }2289}229022912292class ChainGroup extends HelperGroup<ChainHelperBase> {2293  /**2294   * Get system properties of a chain2295   * @example getChainProperties();2296   * @returns ss58Format, token decimals, and token symbol2297   */2298  getChainProperties(): IChainProperties {2299    const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2300    return {2301      ss58Format: properties.ss58Format.toJSON(),2302      tokenDecimals: properties.tokenDecimals.toJSON(),2303      tokenSymbol: properties.tokenSymbol.toJSON(),2304    };2305  }23062307  /**2308   * Get chain header2309   * @example getLatestBlockNumber();2310   * @returns the number of the last block2311   */2312  async getLatestBlockNumber(): Promise<number> {2313    return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2314  }23152316  /**2317   * Get block hash by block number2318   * @param blockNumber number of block2319   * @example getBlockHashByNumber(12345);2320   * @returns hash of a block2321   */2322  async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2323    const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2324    if (blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2325    return blockHash;2326  }23272328  // TODO add docs2329  async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2330    const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2331    if (!blockHash) return null;2332    return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2333  }23342335  /**2336   * Get latest relay block2337   * @returns {number} relay block2338   */2339  async getRelayBlockNumber(): Promise<bigint> {2340    const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2341    return BigInt(blockNumber);2342  }23432344  /**2345   * Get account nonce2346   * @param address substrate address2347   * @example getNonce("5GrwvaEF5zXb26Fz...");2348   * @returns number, account's nonce2349   */2350  async getNonce(address: TSubstrateAccount): Promise<number> {2351    return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2352  }2353}23542355class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2356  /**2357 * Get substrate address balance2358 * @param address substrate address2359 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2360 * @returns amount of tokens on address2361 */2362  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2363    return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2364  }23652366  /**2367   * Transfer tokens to substrate address2368   * @param signer keyring of signer2369   * @param address substrate address of a recipient2370   * @param amount amount of tokens to be transfered2371   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2372   * @returns ```true``` if extrinsic success, otherwise ```false```2373   */2374  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2375    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true/*, `Unable to transfer balance from ${this.helper.getSignerAddress(signer)} to ${address}`*/);23762377    let transfer = {from: null, to: null, amount: 0n} as any;2378    result.result.events.forEach(({event: {data, method, section}}) => {2379      if ((section === 'balances') && (method === 'Transfer')) {2380        transfer = {2381          from: this.helper.address.normalizeSubstrate(data[0]),2382          to: this.helper.address.normalizeSubstrate(data[1]),2383          amount: BigInt(data[2]),2384        };2385      }2386    });2387    const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2388      && this.helper.address.normalizeSubstrate(address) === transfer.to2389      && BigInt(amount) === transfer.amount;2390    return isSuccess;2391  }23922393  /**2394   * Get full substrate balance including free, frozen, and reserved2395   * @param address substrate address2396   * @returns2397   */2398  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2399    const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2400    return {free: accountInfo.free.toBigInt(), frozen: accountInfo.frozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2401  }24022403  async getLocked(address: TSubstrateAccount): Promise<[{ id: string, amount: bigint, reason: string }]> {2404    const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2405    return locks.map((lock: any) => { return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons}; });2406  }24072408  async getFrozen(address: TSubstrateAccount): Promise<[{ id: string, amount: bigint}]> {2409    const locks = (await this.helper.callRpc('api.query.balances.freezes', [address])).toHuman();2410    return locks.map((lock: any) => { return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, ''))}; });2411  }2412}24132414class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2415  /**2416   * Get ethereum address balance2417   * @param address ethereum address2418   * @example getEthereum("0x9F0583DbB855d...")2419   * @returns amount of tokens on address2420   */2421  async getEthereum(address: TEthereumAccount): Promise<bigint> {2422    return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2423  }24242425  /**2426   * Transfer tokens to address2427   * @param signer keyring of signer2428   * @param address Ethereum address of a recipient2429   * @param amount amount of tokens to be transfered2430   * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2431   * @returns ```true``` if extrinsic success, otherwise ```false```2432   */2433  async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2434    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);24352436    let transfer = {from: null, to: null, amount: 0n} as any;2437    result.result.events.forEach(({event: {data, method, section}}) => {2438      if ((section === 'balances') && (method === 'Transfer')) {2439        transfer = {2440          from: data[0].toString(),2441          to: data[1].toString(),2442          amount: BigInt(data[2]),2443        };2444      }2445    });2446    const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2447      && address === transfer.to2448      && BigInt(amount) === transfer.amount;2449    return isSuccess;2450  }2451}24522453class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2454  subBalanceGroup: SubstrateBalanceGroup<T>;2455  ethBalanceGroup: EthereumBalanceGroup<T>;24562457  constructor(helper: T) {2458    super(helper);2459    this.subBalanceGroup = new SubstrateBalanceGroup(helper);2460    this.ethBalanceGroup = new EthereumBalanceGroup(helper);2461  }24622463  getCollectionCreationPrice(): bigint {2464    return 2n * this.getOneTokenNominal();2465  }2466  /**2467   * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2468   * @example getOneTokenNominal()2469   * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2470   */2471  getOneTokenNominal(): bigint {2472    const chainProperties = this.helper.chain.getChainProperties();2473    return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2474  }24752476  /**2477   * Get substrate address balance2478   * @param address substrate address2479   * @example getSubstrate("5GrwvaEF5zXb26Fz...")2480   * @returns amount of tokens on address2481   */2482  getSubstrate(address: TSubstrateAccount): Promise<bigint> {2483    return this.subBalanceGroup.getSubstrate(address);2484  }24852486  /**2487   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2488   * @param address substrate address2489   * @returns2490   */2491  getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2492    return this.subBalanceGroup.getSubstrateFull(address);2493  }24942495  /**2496   * Get locked balances2497   * @param address substrate address2498   * @returns locked balances with reason via api.query.balances.locks2499   */2500  getLocked(address: TSubstrateAccount) {2501    return this.subBalanceGroup.getLocked(address);2502  }25032504  /**2505   * Get frozen balances2506   * @param address substrate address2507   * @returns frozen balances with id via api.query.balances.freezes2508   */2509  getFrozen(address: TSubstrateAccount) {2510    return this.subBalanceGroup.getFrozen(address);2511  }25122513  /**2514   * Get ethereum address balance2515   * @param address ethereum address2516   * @example getEthereum("0x9F0583DbB855d...")2517   * @returns amount of tokens on address2518   */2519  getEthereum(address: TEthereumAccount): Promise<bigint> {2520    return this.ethBalanceGroup.getEthereum(address);2521  }25222523  async setBalanceSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint, reservedAmount = 0n) {2524    await this.helper.executeExtrinsic(signer, 'api.tx.balances.setBalance', [address, amount, reservedAmount], true);2525  }25262527  /**2528   * Transfer tokens to substrate address2529   * @param signer keyring of signer2530   * @param address substrate address of a recipient2531   * @param amount amount of tokens to be transfered2532   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2533   * @returns ```true``` if extrinsic success, otherwise ```false```2534   */2535  transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2536    return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2537  }25382539  async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2540    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);25412542    let transfer = {from: null, to: null, amount: 0n} as any;2543    result.result.events.forEach(({event: {data, method, section}}) => {2544      if ((section === 'balances') && (method === 'Transfer')) {2545        transfer = {2546          from: this.helper.address.normalizeSubstrate(data[0]),2547          to: this.helper.address.normalizeSubstrate(data[1]),2548          amount: BigInt(data[2]),2549        };2550      }2551    });2552    let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2553    isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2554    isSuccess = isSuccess && BigInt(amount) === transfer.amount;2555    return isSuccess;2556  }25572558  /**2559   * Transfer tokens with the unlock period2560   * @param signer signers Keyring2561   * @param address Substrate address of recipient2562   * @param schedule Schedule params2563   * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002564   */2565  async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: { start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint }): Promise<void> {2566    const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2567    const event = result.result.events2568      .find(e => e.event.section === 'vesting' &&2569        e.event.method === 'VestingScheduleAdded' &&2570        e.event.data[0].toHuman() === signer.address);2571    if (!event) throw Error('Cannot find transfer in events');2572  }25732574  /**2575   * Get schedule for recepient of vested transfer2576   * @param address Substrate address of recipient2577   * @returns2578   */2579  async getVestingSchedules(address: TSubstrateAccount): Promise<{ start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint }[]> {2580    const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2581    return schedule.map((schedule: any) => {2582      return {2583        start: BigInt(schedule.start),2584        period: BigInt(schedule.period),2585        periodCount: BigInt(schedule.periodCount),2586        perPeriod: BigInt(schedule.perPeriod),2587      };2588    });2589  }25902591  /**2592   * Claim vested tokens2593   * @param signer signers Keyring2594   */2595  async claim(signer: TSigner) {2596    const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2597    const event = result.result.events2598      .find(e => e.event.section === 'vesting' &&2599        e.event.method === 'Claimed' &&2600        e.event.data[0].toHuman() === signer.address);2601    if (!event) throw Error('Cannot find claim in events');2602  }2603}26042605class AddressGroup extends HelperGroup<ChainHelperBase> {2606  /**2607   * Normalizes the address to the specified ss58 format, by default ```42```.2608   * @param address substrate address2609   * @param ss58Format format for address conversion, by default ```42```2610   * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2611   * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2612   */2613  normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2614    return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2615  }26162617  /**2618   * Get address in the connected chain format2619   * @param address substrate address2620   * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2621   * @returns address in chain format2622   */2623  normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2624    return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2625  }26262627  /**2628   * Get substrate mirror of an ethereum address2629   * @param ethAddress ethereum address2630   * @param toChainFormat false for normalized account2631   * @example ethToSubstrate('0x9F0583DbB855d...')2632   * @returns substrate mirror of a provided ethereum address2633   */2634  ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat = false): TSubstrateAccount {2635    return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2636  }26372638  /**2639   * Get ethereum mirror of a substrate address2640   * @param subAddress substrate account2641   * @example substrateToEth("5DnSF6RRjwteE3BrC...")2642   * @returns ethereum mirror of a provided substrate address2643   */2644  substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2645    return CrossAccountId.translateSubToEth(subAddress);2646  }26472648  /**2649   * Encode key to substrate address2650   * @param key key for encoding address2651   * @param ss58Format prefix for encoding to the address of the corresponding network2652   * @returns encoded substrate address2653   */2654  encodeSubstrateAddress(key: Uint8Array | string | bigint, ss58Format = 42): string {2655    const u8a: Uint8Array = typeof key === 'string'2656      ? hexToU8a(key)2657      : typeof key === 'bigint'2658        ? hexToU8a(key.toString(16))2659        : key;26602661    if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2662      throw new Error(`ss58Format is not valid, received ${typeof ss58Format} "${ss58Format}"`);2663    }26642665    const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2666    if (!allowedDecodedLengths.includes(u8a.length)) {2667      throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2668    }26692670    const u8aPrefix = ss58Format < 642671      ? new Uint8Array([ss58Format])2672      : new Uint8Array([2673        ((ss58Format & 0xfc) >> 2) | 0x40,2674        (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2675      ]);26762677    const input = u8aConcat(u8aPrefix, u8a);26782679    return base58Encode(u8aConcat(2680      input,2681      blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2682    ));2683  }26842685  /**2686   * Restore substrate address from bigint representation2687   * @param number decimal representation of substrate address2688   * @returns substrate address2689   */2690  restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2691    if (this.helper.api === null) {2692      throw 'Not connected';2693    }2694    const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2695    if (res === undefined || res === null) {2696      throw 'Restore address error';2697    }2698    return res.toString();2699  }27002701  /**2702   * Convert etherium cross account id to substrate cross account id2703   * @param ethCrossAccount etherium cross account2704   * @returns substrate cross account id2705   */2706  convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2707    if (ethCrossAccount.sub === '0') {2708      return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2709    }27102711    const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2712    return {Substrate: ss58};2713  }27142715  paraSiblingSovereignAccount(paraid: number) {2716    // We are getting a *sibling* parachain sovereign account,2717    // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2718    const siblingPrefix = '0x7369626c';27192720    const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2721    const suffix = '000000000000000000000000000000000000000000000000';27222723    return siblingPrefix + encodedParaId + suffix;2724  }2725}27262727class StakingGroup extends HelperGroup<UniqueHelper> {2728  /**2729   * Stake tokens for App Promotion2730   * @param signer keyring of signer2731   * @param amountToStake amount of tokens to stake2732   * @param label extra label for log2733   * @returns2734   */2735  async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2736    if (typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2737    const _stakeResult = await this.helper.executeExtrinsic(2738      signer, 'api.tx.appPromotion.stake',2739      [amountToStake], true,2740    );2741    // TODO extract info from stakeResult2742    return true;2743  }27442745  /**2746   * Unstake all staked tokens2747   * @param signer keyring of signer2748   * @param amountToUnstake amount of tokens to unstake2749   * @param label extra label for log2750   * @returns block hash where unstake happened2751   */2752  async unstakeAll(signer: TSigner, label?: string): Promise<string> {2753    if (typeof label === 'undefined') label = `${signer.address}`;2754    const unstakeResult = await this.helper.executeExtrinsic(2755      signer, 'api.tx.appPromotion.unstakeAll',2756      [], true,2757    );2758    return unstakeResult.blockHash;2759  }27602761  /**2762   * Unstake the part of a staked tokens2763   * @param signer keyring of signer2764   * @param amount amount of tokens to unstake2765   * @param label extra label for log2766   * @returns block hash where unstake happened2767   */2768  async unstakePartial(signer: TSigner, amount: bigint, label?: string): Promise<string> {2769    if (typeof label === 'undefined') label = `${signer.address}`;2770    const unstakeResult = await this.helper.executeExtrinsic(2771      signer, 'api.tx.appPromotion.unstakePartial',2772      [amount], true,2773    );2774    return unstakeResult.blockHash;2775  }27762777  /**2778   * Get total number of active stakes2779   * @param address substrate address2780   * @returns {number}2781   */2782  async getStakesNumber(address: ICrossAccountId): Promise<number> {2783    if ('Ethereum' in address) throw Error('only substrate address');2784    return (await this.helper.callRpc('api.query.appPromotion.stakesPerAccount', [address.Substrate])).toNumber();2785  }27862787  /**2788   * Get total staked amount for address2789   * @param address substrate or ethereum address2790   * @returns total staked amount2791   */2792  async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2793    if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2794    return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2795  }27962797  /**2798   * Get total staked per block2799   * @param address substrate or ethereum address2800   * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2801   */2802  async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2803    const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2804    return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2805      return {2806        block: block.toBigInt(),2807        amount: amount.toBigInt(),2808      };2809    });2810  }28112812  /**2813   * Get total pending unstake amount for address2814   * @param address substrate or ethereum address2815   * @returns total pending unstake amount2816   */2817  async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2818    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2819  }28202821  /**2822   * Get pending unstake amount per block for address2823   * @param address substrate or ethereum address2824   * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2825   */2826  async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2827    const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2828    const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2829      return {2830        block: block.toBigInt(),2831        amount: amount.toBigInt(),2832      };2833    });2834    return result;2835  }2836}28372838class SchedulerGroup extends HelperGroup<UniqueHelper> {2839  constructor(helper: UniqueHelper) {2840    super(helper);2841  }28422843  cancelScheduled(signer: TSigner, scheduledId: string) {2844    return this.helper.executeExtrinsic(2845      signer,2846      'api.tx.scheduler.cancelNamed',2847      [scheduledId],2848      true,2849    );2850  }28512852  changePriority(signer: TSigner, scheduledId: string, priority: number) {2853    return this.helper.executeExtrinsic(2854      signer,2855      'api.tx.scheduler.changeNamedPriority',2856      [scheduledId, priority],2857      true,2858    );2859  }28602861  scheduleAt<T extends UniqueHelper>(2862    executionBlockNumber: number,2863    options: ISchedulerOptions = {},2864  ) {2865    return this.schedule<T>('schedule', executionBlockNumber, options);2866  }28672868  scheduleAfter<T extends UniqueHelper>(2869    blocksBeforeExecution: number,2870    options: ISchedulerOptions = {},2871  ) {2872    return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2873  }28742875  schedule<T extends UniqueHelper>(2876    scheduleFn: 'schedule' | 'scheduleAfter',2877    blocksNum: number,2878    options: ISchedulerOptions = {},2879  ) {2880    // eslint-disable-next-line @typescript-eslint/naming-convention2881    const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2882    return this.helper.clone(ScheduledHelperType, {2883      scheduleFn,2884      blocksNum,2885      options,2886    }) as T;2887  }2888}28892890class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2891  //todo:collator documentation2892  addInvulnerable(signer: TSigner, address: string) {2893    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2894  }28952896  removeInvulnerable(signer: TSigner, address: string) {2897    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2898  }28992900  async getInvulnerables(): Promise<string[]> {2901    return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2902  }29032904  /** and also total max invulnerables */2905  maxCollators(): number {2906    return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2907  }29082909  async getDesiredCollators(): Promise<number> {2910    return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2911  }29122913  setLicenseBond(signer: TSigner, amount: bigint) {2914    return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2915  }29162917  async getLicenseBond(): Promise<bigint> {2918    return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2919  }29202921  obtainLicense(signer: TSigner) {2922    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2923  }29242925  releaseLicense(signer: TSigner) {2926    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2927  }29282929  forceReleaseLicense(signer: TSigner, released: string) {2930    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceReleaseLicense', [released]);2931  }29322933  async hasLicense(address: string): Promise<bigint> {2934    return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2935  }29362937  onboard(signer: TSigner) {2938    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2939  }29402941  offboard(signer: TSigner) {2942    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2943  }29442945  async getCandidates(): Promise<string[]> {2946    return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2947  }2948}29492950class PreimageGroup extends HelperGroup<UniqueHelper> {2951  async getPreimageInfo(h256: string) {2952    return (await this.helper.callRpc('api.query.preimage.statusFor', [h256])).toJSON();2953  }29542955  /**2956   * Create a preimage with a hex or a byte array.2957   * @param signer keyring of the signer.2958   * @param bytes preimage encoded in hex or a byte array, e.g. an extrinsic call.2959   * @example await notePreimage(preimageMaker,2960   *   helper.constructApiCall('api.tx.identity.forceInsertIdentities', [identitiesToAdd]).method.toHex()2961   * );2962   * @returns promise of extrinsic execution.2963   */2964  notePreimage(signer: TSigner, bytes: string | Uint8Array) {2965    return this.helper.executeExtrinsic(signer, 'api.tx.preimage.notePreimage', [bytes]);2966  }29672968  /**2969   * Delete an existing preimage and return the deposit.2970   * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2971   * @param h256 hash of the preimage.2972   * @returns promise of extrinsic execution.2973   */2974  unnotePreimage(signer: TSigner, h256: string) {2975    return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unnotePreimage', [h256]);2976  }29772978  /**2979   * Request a preimage be uploaded to the chain without paying any fees or deposits.2980   * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2981   * @param h256 hash of the preimage.2982   * @returns promise of extrinsic execution.2983   */2984  requestPreimage(signer: TSigner, h256: string) {2985    return this.helper.executeExtrinsic(signer, 'api.tx.preimage.requestPreimage', [h256]);2986  }29872988  /**2989   * Clear a previously made request for a preimage.2990   * @param signer keyring of the signer - either the owner or the preimage manager (sudo).2991   * @param h256 hash of the preimage.2992   * @returns promise of extrinsic execution.2993   */2994  unrequestPreimage(signer: TSigner, h256: string) {2995    return this.helper.executeExtrinsic(signer, 'api.tx.preimage.unrequestPreimage', [h256]);2996  }2997}29982999class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {3000  async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {3001    await this.helper.executeExtrinsic(3002      signer,3003      'api.tx.foreignAssets.registerForeignAsset',3004      [ownerAddress, location, metadata],3005      true,3006    );3007  }30083009  async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {3010    await this.helper.executeExtrinsic(3011      signer,3012      'api.tx.foreignAssets.updateForeignAsset',3013      [foreignAssetId, location, metadata],3014      true,3015    );3016  }3017}30183019class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {3020  palletName: string;30213022  constructor(helper: T, palletName: string) {3023    super(helper);30243025    this.palletName = palletName;3026  }30273028  async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {3029    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);3030  }30313032  async setSafeXcmVersion(signer: TSigner, version: number) {3033    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.forceDefaultXcmVersion`, [version], true);3034  }30353036  async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {3037    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);3038  }30393040  async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint, xcmVersion = 3) {3041    const destinationContent = {3042      parents: 0,3043      interior: {3044        X1: {3045          Parachain: destinationParaId,3046        },3047      },3048    };30493050    const beneficiaryContent = {3051      parents: 0,3052      interior: {3053        X1: {3054          AccountId32: {3055            network: 'Any',3056            id: targetAccount,3057          },3058        },3059      },3060    };30613062    const assetsContent = [3063      {3064        id: {3065          Concrete: {3066            parents: 0,3067            interior: 'Here',3068          },3069        },3070        fun: {3071          Fungible: amount,3072        },3073      },3074    ];30753076    let destination;3077    let beneficiary;3078    let assets;30793080    if (xcmVersion == 2) {3081      destination = {V1: destinationContent};3082      beneficiary = {V1: beneficiaryContent};3083      assets = {V1: assetsContent};30843085    } else if (xcmVersion == 3) {3086      destination = {V2: destinationContent};3087      beneficiary = {V2: beneficiaryContent};3088      assets = {V2: assetsContent};30893090    } else {3091      throw Error('Unknown XCM version: ' + xcmVersion);3092    }30933094    const feeAssetItem = 0;30953096    await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);3097  }30983099  async send(signer: IKeyringPair, destination: any, message: any) {3100    await this.helper.executeExtrinsic(3101      signer,3102      `api.tx.${this.palletName}.send`,3103      [3104        destination,3105        message,3106      ],3107      true,3108    );3109  }3110}31113112class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3113  async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {3114    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);3115  }31163117  async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {3118    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);3119  }31203121  async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {3122    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);3123  }3124}31253126class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {3127  async accounts(address: string, currencyId: any) {3128    const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;3129    return BigInt(free);3130  }3131}31323133class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {3134  async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {3135    await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);3136  }31373138  async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {3139    await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);3140  }31413142  async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {3143    await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);3144  }31453146  async account(assetId: string | number, address: string) {3147    const accountAsset = (3148      await this.helper.callRpc('api.query.assets.account', [assetId, address])3149    ).toJSON()! as any;31503151    if (accountAsset !== null) {3152      return BigInt(accountAsset['balance']);3153    } else {3154      return null;3155    }3156  }3157}31583159class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {3160  async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {3161    await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);3162  }3163}31643165class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {3166  makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {3167    const apiPrefix = 'api.tx.assetManager.';31683169    const registerTx = this.helper.constructApiCall(3170      apiPrefix + 'registerForeignAsset',3171      [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],3172    );31733174    const setUnitsTx = this.helper.constructApiCall(3175      apiPrefix + 'setAssetUnitsPerSecond',3176      [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],3177    );31783179    const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);3180    const encodedProposal = batchCall?.method.toHex() || '';3181    return encodedProposal;3182  }31833184  async assetTypeId(location: any) {3185    return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);3186  }3187}31883189class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {3190  notePreimagePallet: string;31913192  constructor(helper: MoonbeamHelper, options: { [key: string]: any } = {}) {3193    super(helper);3194    this.notePreimagePallet = options.notePreimagePallet;3195  }31963197  async notePreimage(signer: TSigner, encodedProposal: string) {3198    await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);3199  }32003201  externalProposeMajority(proposal: any) {3202    return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);3203  }32043205  fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {3206    return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3207  }32083209  async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {3210    await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);3211  }3212}32133214class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {3215  collective: string;32163217  constructor(helper: MoonbeamHelper, collective: string) {3218    super(helper);32193220    this.collective = collective;3221  }32223223  async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {3224    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);3225  }32263227  async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {3228    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);3229  }32303231  async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {3232    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);3233  }32343235  async proposalCount() {3236    return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));3237  }3238}32393240export type ChainHelperBaseConstructor = new (...args: any[]) => ChainHelperBase;3241export type UniqueHelperConstructor = new (...args: any[]) => UniqueHelper;32423243export class UniqueHelper extends ChainHelperBase {3244  balance: BalanceGroup<UniqueHelper>;3245  collection: CollectionGroup;3246  nft: NFTGroup;3247  rft: RFTGroup;3248  ft: FTGroup;3249  staking: StakingGroup;3250  scheduler: SchedulerGroup;3251  collatorSelection: CollatorSelectionGroup;3252  preimage: PreimageGroup;3253  foreignAssets: ForeignAssetsGroup;3254  xcm: XcmGroup<UniqueHelper>;3255  xTokens: XTokensGroup<UniqueHelper>;3256  tokens: TokensGroup<UniqueHelper>;32573258  constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3259    super(logger, options.helperBase ?? UniqueHelper);32603261    this.balance = new BalanceGroup(this);3262    this.collection = new CollectionGroup(this);3263    this.nft = new NFTGroup(this);3264    this.rft = new RFTGroup(this);3265    this.ft = new FTGroup(this);3266    this.staking = new StakingGroup(this);3267    this.scheduler = new SchedulerGroup(this);3268    this.collatorSelection = new CollatorSelectionGroup(this);3269    this.preimage = new PreimageGroup(this);3270    this.foreignAssets = new ForeignAssetsGroup(this);3271    this.xcm = new XcmGroup(this, 'polkadotXcm');3272    this.xTokens = new XTokensGroup(this);3273    this.tokens = new TokensGroup(this);3274  }32753276  getSudo<T extends UniqueHelper>() {3277    // eslint-disable-next-line @typescript-eslint/naming-convention3278    const SudoHelperType = SudoHelper(this.helperBase);3279    return this.clone(SudoHelperType) as T;3280  }3281}32823283export class XcmChainHelper extends ChainHelperBase {3284  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {3285    const wsProvider = new WsProvider(wsEndpoint);3286    this.api = new ApiPromise({3287      provider: wsProvider,3288    });3289    await this.api.isReadyOrError;3290    this.network = await UniqueHelper.detectNetwork(this.api);3291  }3292}32933294export class RelayHelper extends XcmChainHelper {3295  balance: SubstrateBalanceGroup<RelayHelper>;3296  xcm: XcmGroup<RelayHelper>;32973298  constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3299    super(logger, options.helperBase ?? RelayHelper);33003301    this.balance = new SubstrateBalanceGroup(this);3302    this.xcm = new XcmGroup(this, 'xcmPallet');3303  }3304}33053306export class WestmintHelper extends XcmChainHelper {3307  balance: SubstrateBalanceGroup<WestmintHelper>;3308  xcm: XcmGroup<WestmintHelper>;3309  assets: AssetsGroup<WestmintHelper>;3310  xTokens: XTokensGroup<WestmintHelper>;33113312  constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3313    super(logger, options.helperBase ?? WestmintHelper);33143315    this.balance = new SubstrateBalanceGroup(this);3316    this.xcm = new XcmGroup(this, 'polkadotXcm');3317    this.assets = new AssetsGroup(this);3318    this.xTokens = new XTokensGroup(this);3319  }3320}33213322export class MoonbeamHelper extends XcmChainHelper {3323  balance: EthereumBalanceGroup<MoonbeamHelper>;3324  assetManager: MoonbeamAssetManagerGroup;3325  assets: AssetsGroup<MoonbeamHelper>;3326  xTokens: XTokensGroup<MoonbeamHelper>;3327  democracy: MoonbeamDemocracyGroup;3328  collective: {3329    council: MoonbeamCollectiveGroup,3330    techCommittee: MoonbeamCollectiveGroup,3331  };33323333  constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3334    super(logger, options.helperBase ?? MoonbeamHelper);33353336    this.balance = new EthereumBalanceGroup(this);3337    this.assetManager = new MoonbeamAssetManagerGroup(this);3338    this.assets = new AssetsGroup(this);3339    this.xTokens = new XTokensGroup(this);3340    this.democracy = new MoonbeamDemocracyGroup(this, options);3341    this.collective = {3342      council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3343      techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3344    };3345  }3346}33473348export class AstarHelper extends XcmChainHelper {3349  balance: SubstrateBalanceGroup<AstarHelper>;3350  assets: AssetsGroup<AstarHelper>;3351  xcm: XcmGroup<AstarHelper>;33523353  constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3354    super(logger, options.helperBase ?? AstarHelper);33553356    this.balance = new SubstrateBalanceGroup(this);3357    this.assets = new AssetsGroup(this);3358    this.xcm = new XcmGroup(this, 'polkadotXcm');3359  }33603361  getSudo<T extends UniqueHelper>() {3362    // eslint-disable-next-line @typescript-eslint/naming-convention3363    const SudoHelperType = SudoHelper(this.helperBase);3364    return this.clone(SudoHelperType) as T;3365  }3366}33673368export class AcalaHelper extends XcmChainHelper {3369  balance: SubstrateBalanceGroup<AcalaHelper>;3370  assetRegistry: AcalaAssetRegistryGroup;3371  xTokens: XTokensGroup<AcalaHelper>;3372  tokens: TokensGroup<AcalaHelper>;3373  xcm: XcmGroup<AcalaHelper>;33743375  constructor(logger?: ILogger, options: { [key: string]: any } = {}) {3376    super(logger, options.helperBase ?? AcalaHelper);33773378    this.balance = new SubstrateBalanceGroup(this);3379    this.assetRegistry = new AcalaAssetRegistryGroup(this);3380    this.xTokens = new XTokensGroup(this);3381    this.tokens = new TokensGroup(this);3382    this.xcm = new XcmGroup(this, 'polkadotXcm');3383  }33843385  getSudo<T extends AcalaHelper>() {3386    // eslint-disable-next-line @typescript-eslint/naming-convention3387    const SudoHelperType = SudoHelper(this.helperBase);3388    return this.clone(SudoHelperType) as T;3389  }3390}33913392// eslint-disable-next-line @typescript-eslint/naming-convention3393function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3394  return class extends Base {3395    scheduleFn: 'schedule' | 'scheduleAfter';3396    blocksNum: number;3397    options: ISchedulerOptions;33983399    constructor(...args: any[]) {3400      const logger = args[0] as ILogger;3401      const options = args[1] as {3402        scheduleFn: 'schedule' | 'scheduleAfter',3403        blocksNum: number,3404        options: ISchedulerOptions3405      };34063407      super(logger);34083409      this.scheduleFn = options.scheduleFn;3410      this.blocksNum = options.blocksNum;3411      this.options = options.options;3412    }34133414    executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3415      const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);34163417      const mandatorySchedArgs = [3418        this.blocksNum,3419        this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3420        this.options.priority ?? null,3421        scheduledTx,3422      ];34233424      let schedArgs;3425      let scheduleFn;34263427      if (this.options.scheduledId) {3428        schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];34293430        if (this.scheduleFn == 'schedule') {3431          scheduleFn = 'scheduleNamed';3432        } else if (this.scheduleFn == 'scheduleAfter') {3433          scheduleFn = 'scheduleNamedAfter';3434        }3435      } else {3436        schedArgs = mandatorySchedArgs;3437        scheduleFn = this.scheduleFn;3438      }34393440      const extrinsic = 'api.tx.scheduler.' + scheduleFn;34413442      return super.executeExtrinsic(3443        sender,3444        extrinsic as any,3445        schedArgs,3446        expectSuccess,3447      );3448    }3449  };3450}34513452// eslint-disable-next-line @typescript-eslint/naming-convention3453function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3454  return class extends Base {3455    constructor(...args: any[]) {3456      super(...args);3457    }34583459    async executeExtrinsic(3460      sender: IKeyringPair,3461      extrinsic: string,3462      params: any[],3463      expectSuccess?: boolean,3464      options: Partial<SignerOptions> | null = null,3465    ): Promise<ITransactionResult> {3466      const call = this.constructApiCall(extrinsic, params);3467      const result = await super.executeExtrinsic(3468        sender,3469        'api.tx.sudo.sudo',3470        [call],3471        expectSuccess,3472        options,3473      );34743475      if (result.status === 'Fail') return result;34763477      const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3478      if (data.isErr) {3479        if (data.asErr.isModule) {3480          const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3481          const metaError = super.getApi()?.registry.findMetaError(error);3482          throw new Error(`${metaError.section}.${metaError.name}`);3483        } else if (data.asErr.isToken) {3484          throw new Error(`Token: ${data.asErr.asToken}`);3485        }3486      }3487      return result;3488    }3489  };3490}34913492export class UniqueBaseCollection {3493  helper: UniqueHelper;3494  collectionId: number;34953496  constructor(collectionId: number, uniqueHelper: UniqueHelper) {3497    this.collectionId = collectionId;3498    this.helper = uniqueHelper;3499  }35003501  async getData() {3502    return await this.helper.collection.getData(this.collectionId);3503  }35043505  async getLastTokenId() {3506    return await this.helper.collection.getLastTokenId(this.collectionId);3507  }35083509  async doesTokenExist(tokenId: number) {3510    return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3511  }35123513  async getAdmins() {3514    return await this.helper.collection.getAdmins(this.collectionId);3515  }35163517  async getAllowList() {3518    return await this.helper.collection.getAllowList(this.collectionId);3519  }35203521  async getEffectiveLimits() {3522    return await this.helper.collection.getEffectiveLimits(this.collectionId);3523  }35243525  async getProperties(propertyKeys?: string[] | null) {3526    return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3527  }35283529  async getPropertiesConsumedSpace() {3530    return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3531  }35323533  async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3534    return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3535  }35363537  async getOptions() {3538    return await this.helper.collection.getCollectionOptions(this.collectionId);3539  }35403541  async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3542    return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3543  }35443545  async confirmSponsorship(signer: TSigner) {3546    return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3547  }35483549  async removeSponsor(signer: TSigner) {3550    return await this.helper.collection.removeSponsor(signer, this.collectionId);3551  }35523553  async setLimits(signer: TSigner, limits: ICollectionLimits) {3554    return await this.helper.collection.setLimits(signer, this.collectionId, limits);3555  }35563557  async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3558    return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3559  }35603561  async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3562    return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3563  }35643565  async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3566    return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3567  }35683569  async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3570    return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3571  }35723573  async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3574    return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3575  }35763577  async setProperties(signer: TSigner, properties: IProperty[]) {3578    return await this.helper.collection.setProperties(signer, this.collectionId, properties);3579  }35803581  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3582    return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3583  }35843585  async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3586    return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3587  }35883589  async enableNesting(signer: TSigner, permissions: INestingPermissions) {3590    return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3591  }35923593  async disableNesting(signer: TSigner) {3594    return await this.helper.collection.disableNesting(signer, this.collectionId);3595  }35963597  async burn(signer: TSigner) {3598    return await this.helper.collection.burn(signer, this.collectionId);3599  }36003601  scheduleAt<T extends UniqueHelper>(3602    executionBlockNumber: number,3603    options: ISchedulerOptions = {},3604  ) {3605    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3606    return new UniqueBaseCollection(this.collectionId, scheduledHelper);3607  }36083609  scheduleAfter<T extends UniqueHelper>(3610    blocksBeforeExecution: number,3611    options: ISchedulerOptions = {},3612  ) {3613    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3614    return new UniqueBaseCollection(this.collectionId, scheduledHelper);3615  }36163617  getSudo<T extends UniqueHelper>() {3618    return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3619  }3620}362136223623export class UniqueNFTCollection extends UniqueBaseCollection {3624  getTokenObject(tokenId: number) {3625    return new UniqueNFToken(tokenId, this);3626  }36273628  async getTokensByAddress(addressObj: ICrossAccountId) {3629    return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3630  }36313632  async getToken(tokenId: number, blockHashAt?: string) {3633    return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3634  }36353636  async getTokenOwner(tokenId: number, blockHashAt?: string) {3637    return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3638  }36393640  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3641    return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3642  }36433644  async getTokenChildren(tokenId: number, blockHashAt?: string) {3645    return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3646  }36473648  async getPropertyPermissions(propertyKeys: string[] | null = null) {3649    return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3650  }36513652  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3653    return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3654  }36553656  async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3657    const api = this.helper.getApi();3658    const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();36593660    return (props! as any).consumedSpace;3661  }36623663  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3664    return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3665  }36663667  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3668    return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3669  }36703671  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3672    return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3673  }36743675  async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3676    return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3677  }36783679  async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3680    return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3681  }36823683  async mintMultipleTokens(signer: TSigner, tokens: { owner: ICrossAccountId, properties?: IProperty[] }[]) {3684    return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3685  }36863687  async burnToken(signer: TSigner, tokenId: number) {3688    return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3689  }36903691  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3692    return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3693  }36943695  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3696    return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3697  }36983699  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3700    return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3701  }37023703  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3704    return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3705  }37063707  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3708    return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3709  }37103711  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3712    return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3713  }37143715  scheduleAt<T extends UniqueHelper>(3716    executionBlockNumber: number,3717    options: ISchedulerOptions = {},3718  ) {3719    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3720    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3721  }37223723  scheduleAfter<T extends UniqueHelper>(3724    blocksBeforeExecution: number,3725    options: ISchedulerOptions = {},3726  ) {3727    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3728    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3729  }37303731  getSudo<T extends UniqueHelper>() {3732    return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3733  }3734}373537363737export class UniqueRFTCollection extends UniqueBaseCollection {3738  getTokenObject(tokenId: number) {3739    return new UniqueRFToken(tokenId, this);3740  }37413742  async getToken(tokenId: number, blockHashAt?: string) {3743    return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3744  }37453746  async getTokenOwner(tokenId: number, blockHashAt?: string) {3747    return await this.helper.rft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3748  }37493750  async getTokensByAddress(addressObj: ICrossAccountId) {3751    return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3752  }37533754  async getTop10TokenOwners(tokenId: number) {3755    return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3756  }37573758  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3759    return await this.helper.rft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3760  }37613762  async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3763    return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3764  }37653766  async getTokenTotalPieces(tokenId: number) {3767    return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3768  }37693770  async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3771    return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3772  }37733774  async getPropertyPermissions(propertyKeys: string[] | null = null) {3775    return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3776  }37773778  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3779    return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3780  }37813782  async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3783    const api = this.helper.getApi();3784    const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();37853786    return (props! as any).consumedSpace;3787  }37883789  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount = 1n) {3790    return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3791  }37923793  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {3794    return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3795  }37963797  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount = 1n) {3798    return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3799  }38003801  async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3802    return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3803  }38043805  async mintToken(signer: TSigner, pieces = 1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3806    return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3807  }38083809  async mintMultipleTokens(signer: TSigner, tokens: { pieces: bigint, owner: ICrossAccountId, properties?: IProperty[] }[]) {3810    return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3811  }38123813  async burnToken(signer: TSigner, tokenId: number, amount = 1n) {3814    return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3815  }38163817  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount = 1n) {3818    return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3819  }38203821  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3822    return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3823  }38243825  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3826    return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3827  }38283829  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3830    return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3831  }38323833  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3834    return await this.helper.rft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3835  }38363837  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3838    return await this.helper.rft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3839  }38403841  scheduleAt<T extends UniqueHelper>(3842    executionBlockNumber: number,3843    options: ISchedulerOptions = {},3844  ) {3845    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3846    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3847  }38483849  scheduleAfter<T extends UniqueHelper>(3850    blocksBeforeExecution: number,3851    options: ISchedulerOptions = {},3852  ) {3853    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3854    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3855  }38563857  getSudo<T extends UniqueHelper>() {3858    return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3859  }3860}386138623863export class UniqueFTCollection extends UniqueBaseCollection {3864  async getBalance(addressObj: ICrossAccountId) {3865    return await this.helper.ft.getBalance(this.collectionId, addressObj);3866  }38673868  async getTotalPieces() {3869    return await this.helper.ft.getTotalPieces(this.collectionId);3870  }38713872  async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3873    return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3874  }38753876  async getTop10Owners() {3877    return await this.helper.ft.getTop10Owners(this.collectionId);3878  }38793880  async mint(signer: TSigner, amount = 1n, owner: ICrossAccountId = {Substrate: signer.address}) {3881    return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3882  }38833884  async mintWithOneOwner(signer: TSigner, tokens: { value: bigint }[], owner: ICrossAccountId = {Substrate: signer.address}) {3885    return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3886  }38873888  async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {3889    return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3890  }38913892  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {3893    return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3894  }38953896  async burnTokens(signer: TSigner, amount = 1n) {3897    return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3898  }38993900  async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount = 1n) {3901    return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3902  }39033904  async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {3905    return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3906  }39073908  scheduleAt<T extends UniqueHelper>(3909    executionBlockNumber: number,3910    options: ISchedulerOptions = {},3911  ) {3912    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3913    return new UniqueFTCollection(this.collectionId, scheduledHelper);3914  }39153916  scheduleAfter<T extends UniqueHelper>(3917    blocksBeforeExecution: number,3918    options: ISchedulerOptions = {},3919  ) {3920    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3921    return new UniqueFTCollection(this.collectionId, scheduledHelper);3922  }39233924  getSudo<T extends UniqueHelper>() {3925    return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3926  }3927}392839293930export class UniqueBaseToken {3931  collection: UniqueNFTCollection | UniqueRFTCollection;3932  collectionId: number;3933  tokenId: number;39343935  constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3936    this.collection = collection;3937    this.collectionId = collection.collectionId;3938    this.tokenId = tokenId;3939  }39403941  async getNextSponsored(addressObj: ICrossAccountId) {3942    return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3943  }39443945  async getProperties(propertyKeys?: string[] | null) {3946    return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3947  }39483949  async getTokenPropertiesConsumedSpace() {3950    return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3951  }39523953  async setProperties(signer: TSigner, properties: IProperty[]) {3954    return await this.collection.setTokenProperties(signer, this.tokenId, properties);3955  }39563957  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3958    return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3959  }39603961  async doesExist() {3962    return await this.collection.doesTokenExist(this.tokenId);3963  }39643965  nestingAccount() {3966    return this.collection.helper.util.getTokenAccount(this);3967  }39683969  scheduleAt<T extends UniqueHelper>(3970    executionBlockNumber: number,3971    options: ISchedulerOptions = {},3972  ) {3973    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3974    return new UniqueBaseToken(this.tokenId, scheduledCollection);3975  }39763977  scheduleAfter<T extends UniqueHelper>(3978    blocksBeforeExecution: number,3979    options: ISchedulerOptions = {},3980  ) {3981    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3982    return new UniqueBaseToken(this.tokenId, scheduledCollection);3983  }39843985  getSudo<T extends UniqueHelper>() {3986    return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3987  }3988}398939903991export class UniqueNFToken extends UniqueBaseToken {3992  collection: UniqueNFTCollection;39933994  constructor(tokenId: number, collection: UniqueNFTCollection) {3995    super(tokenId, collection);3996    this.collection = collection;3997  }39983999  async getData(blockHashAt?: string) {4000    return await this.collection.getToken(this.tokenId, blockHashAt);4001  }40024003  async getOwner(blockHashAt?: string) {4004    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);4005  }40064007  async getTopmostOwner(blockHashAt?: string) {4008    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);4009  }40104011  async getChildren(blockHashAt?: string) {4012    return await this.collection.getTokenChildren(this.tokenId, blockHashAt);4013  }40144015  async nest(signer: TSigner, toTokenObj: IToken) {4016    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);4017  }40184019  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4020    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);4021  }40224023  async transfer(signer: TSigner, addressObj: ICrossAccountId) {4024    return await this.collection.transferToken(signer, this.tokenId, addressObj);4025  }40264027  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {4028    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);4029  }40304031  async approve(signer: TSigner, toAddressObj: ICrossAccountId) {4032    return await this.collection.approveToken(signer, this.tokenId, toAddressObj);4033  }40344035  async isApproved(toAddressObj: ICrossAccountId) {4036    return await this.collection.isTokenApproved(this.tokenId, toAddressObj);4037  }40384039  async burn(signer: TSigner) {4040    return await this.collection.burnToken(signer, this.tokenId);4041  }40424043  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {4044    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);4045  }40464047  scheduleAt<T extends UniqueHelper>(4048    executionBlockNumber: number,4049    options: ISchedulerOptions = {},4050  ) {4051    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);4052    return new UniqueNFToken(this.tokenId, scheduledCollection);4053  }40544055  scheduleAfter<T extends UniqueHelper>(4056    blocksBeforeExecution: number,4057    options: ISchedulerOptions = {},4058  ) {4059    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);4060    return new UniqueNFToken(this.tokenId, scheduledCollection);4061  }40624063  getSudo<T extends UniqueHelper>() {4064    return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());4065  }4066}40674068export class UniqueRFToken extends UniqueBaseToken {4069  collection: UniqueRFTCollection;40704071  constructor(tokenId: number, collection: UniqueRFTCollection) {4072    super(tokenId, collection);4073    this.collection = collection;4074  }40754076  async getData(blockHashAt?: string) {4077    return await this.collection.getToken(this.tokenId, blockHashAt);4078  }40794080  async getOwner(blockHashAt?: string) {4081    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);4082  }40834084  async getTop10Owners() {4085    return await this.collection.getTop10TokenOwners(this.tokenId);4086  }40874088  async getTopmostOwner(blockHashAt?: string) {4089    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);4090  }40914092  async nest(signer: TSigner, toTokenObj: IToken) {4093    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);4094  }40954096  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {4097    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);4098  }40994100  async getBalance(addressObj: ICrossAccountId) {4101    return await this.collection.getTokenBalance(this.tokenId, addressObj);4102  }41034104  async getTotalPieces() {4105    return await this.collection.getTokenTotalPieces(this.tokenId);4106  }41074108  async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {4109    return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);4110  }41114112  async transfer(signer: TSigner, addressObj: ICrossAccountId, amount = 1n) {4113    return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);4114  }41154116  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount = 1n) {4117    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);4118  }41194120  async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount = 1n) {4121    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);4122  }41234124  async repartition(signer: TSigner, amount: bigint) {4125    return await this.collection.repartitionToken(signer, this.tokenId, amount);4126  }41274128  async burn(signer: TSigner, amount = 1n) {4129    return await this.collection.burnToken(signer, this.tokenId, amount);4130  }41314132  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount = 1n) {4133    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);4134  }41354136  scheduleAt<T extends UniqueHelper>(4137    executionBlockNumber: number,4138    options: ISchedulerOptions = {},4139  ) {4140    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);4141    return new UniqueRFToken(this.tokenId, scheduledCollection);4142  }41434144  scheduleAfter<T extends UniqueHelper>(4145    blocksBeforeExecution: number,4146    options: ISchedulerOptions = {},4147  ) {4148    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);4149    return new UniqueRFToken(this.tokenId, scheduledCollection);4150  }41514152  getSudo<T extends UniqueHelper>() {4153    return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());4154  }4155}
modifiedtests/src/vesting.test.tsdiffbeforeafterboth
--- a/tests/src/vesting.test.ts
+++ b/tests/src/vesting.test.ts
@@ -103,7 +103,7 @@
     expect(balanceSender.reserved).to.eq(0n);
   });
 
-  itSub.only('cannot send more tokens than have', async ({helper}) => {
+  itSub('cannot send more tokens than have', async ({helper}) => {
     const [sender, receiver] = await helper.arrange.createAccounts([1000n, 1n], donor);
     const schedule = {start: 0n, period: 1n, periodCount: 1n, perPeriod: 100n * nominal};
     const manyPeriodsSchedule = {start: 0n, period: 1n, periodCount: 100n, perPeriod: 10n * nominal};