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

difftreelog

Merge pull request #355 from UniqueNetwork/feature/nft-children

Yaroslav Bolyukin2022-05-30parents: #764dfd5 #8cbbfc6.patch.diff
in: master
Structure children map

12 files changed

modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -353,6 +353,8 @@
 		MustBeTokenOwner,
 		/// No permission to perform action
 		NoPermission,
+		/// Destroying only empty collections is allowed
+		CantDestroyNotEmptyCollection,
 		/// Collection is not in mint mode.
 		PublicMintingNotAllowed,
 		/// Address is not in allow list.
@@ -1268,6 +1270,18 @@
 		budget: &dyn Budget,
 	) -> DispatchResult;
 
+	fn nest(
+		&self,
+		under: TokenId,
+		to_nest: (CollectionId, TokenId)
+	);
+
+	fn unnest(
+		&self,
+		under: TokenId,
+		to_nest: (CollectionId, TokenId)
+	);
+
 	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;
 	fn collection_tokens(&self) -> Vec<TokenId>;
 	fn token_exists(&self, token: TokenId) -> bool;
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -298,6 +298,18 @@
 		fail!(<Error<T>>::FungibleDisallowsNesting)
 	}
 
+	fn nest(
+		&self,
+		_under: TokenId,
+		_to_nest: (CollectionId, TokenId)
+	) {}
+
+	fn unnest(
+		&self,
+		_under: TokenId,
+		_to_nest: (CollectionId, TokenId)
+	) {}
+
 	fn collection_tokens(&self) -> Vec<TokenId> {
 		vec![TokenId::default()]
 	}
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -25,8 +25,8 @@
 	budget::Budget,
 };
 use pallet_common::{
-	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, CollectionHandle,
-	dispatch::CollectionDispatch, eth::collection_id_to_address,
+	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
+	eth::collection_id_to_address,
 };
 use pallet_evm::Pallet as PalletEvm;
 use pallet_structure::Pallet as PalletStructure;
@@ -145,6 +145,10 @@
 	) -> DispatchResult {
 		let id = collection.id;
 
+		if Self::collection_has_tokens(id) {
+			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());
+		}
+
 		// =========
 
 		PalletCommon::destroy_collection(collection.0, sender)?;
@@ -155,6 +159,10 @@
 		Ok(())
 	}
 
+	fn collection_has_tokens(collection_id: CollectionId) -> bool {
+		<TotalSupply<T>>::get(collection_id) != 0
+	}
+
 	pub fn burn(
 		collection: &FungibleHandle<T>,
 		owner: &T::CrossAccountId,
@@ -176,6 +184,11 @@
 
 		if balance == 0 {
 			<Balance<T>>::remove((collection.id, owner));
+			<PalletStructure<T>>::unnest_if_nested(
+				owner,
+				collection.id,
+				TokenId::default()
+			);
 		} else {
 			<Balance<T>>::insert((collection.id, owner), balance);
 		}
@@ -229,25 +242,25 @@
 			None
 		};
 
-		if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {
-			let handle = <CollectionHandle<T>>::try_get(target.0)?;
-			let dispatch = T::CollectionDispatch::dispatch(handle);
-			let dispatch = dispatch.as_dyn();
+		// =========
 
-			dispatch.check_nesting(
-				from.clone(),
-				(collection.id, TokenId::default()),
-				target.1,
-				nesting_budget,
-			)?;
-		}
+		<PalletStructure<T>>::nest_if_sent_to_token(
+			from.clone(),
+			to,
+			collection.id,
+			TokenId::default(),
+			nesting_budget
+		)?;
 
-		// =========
-
 		if let Some(balance_to) = balance_to {
 			// from != to
 			if balance_from == 0 {
 				<Balance<T>>::remove((collection.id, from));
+				<PalletStructure<T>>::unnest_if_nested(
+					from,
+					collection.id,
+					TokenId::default()
+				);
 			} else {
 				<Balance<T>>::insert((collection.id, from), balance_from);
 			}
@@ -306,18 +319,13 @@
 		}
 
 		for (to, _) in balances.iter() {
-			if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {
-				let handle = <CollectionHandle<T>>::try_get(target.0)?;
-				let dispatch = T::CollectionDispatch::dispatch(handle);
-				let dispatch = dispatch.as_dyn();
-
-				dispatch.check_nesting(
-					sender.clone(),
-					(collection.id, TokenId::default()),
-					target.1,
-					nesting_budget,
-				)?;
-			}
+			<PalletStructure<T>>::check_nesting(
+				sender.clone(),
+				to,
+				collection.id,
+				TokenId::default(),
+				nesting_budget,
+			)?;
 		}
 
 		// =========
@@ -325,7 +333,7 @@
 		<TotalSupply<T>>::insert(collection.id, total_supply);
 		for (user, amount) in balances {
 			<Balance<T>>::insert((collection.id, &user), amount);
-
+			<PalletStructure<T>>::nest_if_sent_to_token_unchecked(&user, collection.id, TokenId::default());
 			<PalletEvm<T>>::deposit_log(
 				ERC20Events::Transfer {
 					from: H160::default(),
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -353,6 +353,22 @@
 		<Pallet<T>>::check_nesting(self, sender, from, under, budget)
 	}
 
+	fn nest(
+		&self,
+		under: TokenId,
+		to_nest: (CollectionId, TokenId)
+	) {
+		<Pallet<T>>::nest((self.id, under), to_nest);
+	}
+
+	fn unnest(
+		&self,
+		under: TokenId,
+		to_unnest: (CollectionId, TokenId)
+	) {
+		<Pallet<T>>::unnest((self.id, under), to_unnest);
+	}
+
 	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
 		<Owned<T>>::iter_prefix((self.id, account))
 			.map(|(id, _)| id)
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -27,7 +27,7 @@
 use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
 use pallet_common::{
 	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,
-	dispatch::CollectionDispatch, eth::collection_id_to_address,
+	eth::collection_id_to_address,
 };
 use pallet_structure::Pallet as PalletStructure;
 use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
@@ -76,6 +76,8 @@
 		NotNonfungibleDataUsedToMintFungibleCollectionToken,
 		/// Used amount > 1 with NFT
 		NonfungibleItemsHaveNoAmount,
+		/// Unable to burn NFT with children
+		CantBurnNftWithChildren,
 	}
 
 	#[pallet::config]
@@ -127,7 +129,20 @@
 		QueryKind = ValueQuery,
 	>;
 
+	/// Used to enumerate token's children
 	#[pallet::storage]
+	#[pallet::getter(fn token_children)]
+	pub type TokenChildren<T: Config> = StorageNMap<
+		Key = (
+			Key<Twox64Concat, CollectionId>,
+			Key<Twox64Concat, TokenId>,
+			Key<Twox64Concat, (CollectionId, TokenId)>,
+		),
+		Value = bool,
+		QueryKind = ValueQuery,
+	>;
+
+	#[pallet::storage]
 	pub type AccountBalance<T: Config> = StorageNMap<
 		Key = (
 			Key<Twox64Concat, CollectionId>,
@@ -277,11 +292,16 @@
 	) -> DispatchResult {
 		let id = collection.id;
 
+		if Self::collection_has_tokens(id) {
+			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());
+		}
+
 		// =========
 
 		PalletCommon::destroy_collection(collection.0, sender)?;
 
 		<TokenData<T>>::remove_prefix((id,), None);
+		<TokenChildren<T>>::remove_prefix((id,), None);
 		<Owned<T>>::remove_prefix((id,), None);
 		<TokensMinted<T>>::remove(id);
 		<TokensBurnt<T>>::remove(id);
@@ -307,6 +327,10 @@
 			collection.check_allowlist(sender)?;
 		}
 
+		if Self::token_has_children(collection.id, token) {
+			return Err(<Error<T>>::CantBurnNftWithChildren.into());
+		}
+
 		let burnt = <TokensBurnt<T>>::get(collection.id)
 			.checked_add(1)
 			.ok_or(ArithmeticError::Overflow)?;
@@ -315,13 +339,20 @@
 			.checked_sub(1)
 			.ok_or(ArithmeticError::Overflow)?;
 
+		// =========
+
 		if balance == 0 {
 			<AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));
 		} else {
 			<AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);
 		}
-		// =========
 
+		<PalletStructure<T>>::unnest_if_nested(
+			&token_data.owner,
+			collection.id,
+			token
+		);
+
 		<Owned<T>>::remove((collection.id, &token_data.owner, token));
 		<TokensBurnt<T>>::insert(collection.id, burnt);
 		<TokenData<T>>::remove((collection.id, token));
@@ -553,20 +584,21 @@
 			None
 		};
 
-		if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {
-			let handle = <CollectionHandle<T>>::try_get(target.0)?;
-			let dispatch = T::CollectionDispatch::dispatch(handle);
-			let dispatch = dispatch.as_dyn();
+		<PalletStructure<T>>::nest_if_sent_to_token(
+			from.clone(),
+			to,
+			collection.id,
+			token,
+			nesting_budget
+		)?;
 
-			dispatch.check_nesting(
-				from.clone(),
-				(collection.id, token),
-				target.1,
-				nesting_budget,
-			)?;
-		}
+		// =========
 
-		// =========
+		<PalletStructure<T>>::unnest_if_nested(
+			from,
+			collection.id,
+			token
+		);
 
 		<TokenData<T>>::insert(
 			(collection.id, token),
@@ -653,17 +685,14 @@
 
 		for (i, data) in data.iter().enumerate() {
 			let token = TokenId(first_token + i as u32 + 1);
-			if let Some(target) = T::CrossTokenAddressMapping::address_to_token(&data.owner) {
-				let handle = <CollectionHandle<T>>::try_get(target.0)?;
-				let dispatch = T::CollectionDispatch::dispatch(handle);
-				let dispatch = dispatch.as_dyn();
-				dispatch.check_nesting(
-					sender.clone(),
-					(collection.id, token),
-					target.1,
-					nesting_budget,
-				)?;
-			}
+
+			<PalletStructure<T>>::check_nesting(
+				sender.clone(),
+				&data.owner,
+				collection.id,
+				token,
+				nesting_budget,
+			)?;
 		}
 
 		// =========
@@ -680,6 +709,8 @@
 					},
 				);
 
+				<PalletStructure<T>>::nest_if_sent_to_token_unchecked(&data.owner, collection.id, TokenId(token));
+
 				if let Err(e) = Self::set_token_properties(
 					collection,
 					sender,
@@ -927,6 +958,33 @@
 		Ok(())
 	}
 
+	fn nest(
+		under: (CollectionId, TokenId),
+		to_nest: (CollectionId, TokenId),
+	) {
+		<TokenChildren<T>>::insert(
+			(under.0, under.1, (to_nest.0, to_nest.1)),
+			true
+		);
+	}
+
+	fn unnest(
+		under: (CollectionId, TokenId),
+		to_unnest: (CollectionId, TokenId),
+	) {
+		<TokenChildren<T>>::remove(
+			(under.0, under.1, to_unnest)
+		);
+	}
+
+	fn collection_has_tokens(collection_id: CollectionId) -> bool {
+		<TokenData<T>>::iter_prefix((collection_id,)).next().is_some()
+	}
+
+	fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {
+		<TokenChildren<T>>::iter_prefix((collection_id, token_id)).next().is_some()
+	}
+
 	/// Delegated to `create_multiple_items`
 	pub fn create_item(
 		collection: &NonfungibleHandle<T>,
modifiedpallets/proxy-rmrk-core/src/misc.rsdiffbeforeafterboth
--- a/pallets/proxy-rmrk-core/src/misc.rs
+++ b/pallets/proxy-rmrk-core/src/misc.rs
@@ -26,6 +26,18 @@
     }
 }
 
+pub trait RmrkRebind<T, S> {
+    fn rebind(&self) -> BoundedVec<u8, S>;
+}
+
+impl<T, S> RmrkRebind<T, S> for BoundedVec<u8, T> where BoundedVec<u8, S>: TryFrom<Vec<u8>> {
+    fn rebind(&self) -> BoundedVec<u8, S> {
+        BoundedVec::<u8, S>::try_from(
+            self.clone().into_inner()
+        ).unwrap_or_default()
+    }
+}
+
 #[derive(Encode, Decode, PartialEq, Eq)]
 pub enum CollectionType {
     Regular,
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -313,6 +313,18 @@
 		fail!(<Error<T>>::RefungibleDisallowsNesting)
 	}
 
+	fn nest(
+		&self,
+		_under: TokenId,
+		_to_nest: (CollectionId, TokenId)
+	) {}
+
+	fn unnest(
+		&self,
+		_under: TokenId,
+		_to_nest: (CollectionId, TokenId)
+	) {}
+
 	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
 		<Owned<T>>::iter_prefix((self.id, account))
 			.map(|(id, _)| id)
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
after · pallets/refungible/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use frame_support::{ensure, BoundedVec};20use up_data_structs::{21	AccessMode, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,22	CreateCollectionData, CreateRefungibleExData, mapping::TokenAddressMapping, budget::Budget,23};24use pallet_evm::account::CrossAccountId;25use pallet_common::{26	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,27};28use pallet_structure::Pallet as PalletStructure;29use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};30use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};31use core::ops::Deref;32use codec::{Encode, Decode, MaxEncodedLen};33use scale_info::TypeInfo;3435pub use pallet::*;36#[cfg(feature = "runtime-benchmarks")]37pub mod benchmarking;38pub mod common;39pub mod erc;40pub mod weights;41pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4243#[struct_versioning::versioned(version = 2, upper)]44#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]45pub struct ItemData {46	pub const_data: BoundedVec<u8, CustomDataLimit>,4748	#[version(..2)]49	pub variable_data: BoundedVec<u8, CustomDataLimit>,50}5152#[frame_support::pallet]53pub mod pallet {54	use super::*;55	use frame_support::{56		Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,57		traits::StorageVersion,58	};59	use frame_system::pallet_prelude::*;60	use up_data_structs::{CollectionId, TokenId};61	use super::weights::WeightInfo;6263	#[pallet::error]64	pub enum Error<T> {65		/// Not Refungible item data used to mint in Refungible collection.66		NotRefungibleDataUsedToMintFungibleCollectionToken,67		/// Maximum refungibility exceeded68		WrongRefungiblePieces,69		/// Refungible token can't nest other tokens70		RefungibleDisallowsNesting,71		/// Setting item properties is not allowed72		SettingPropertiesNotAllowed,73	}7475	#[pallet::config]76	pub trait Config:77		frame_system::Config + pallet_common::Config + pallet_structure::Config78	{79		type WeightInfo: WeightInfo;80	}8182	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);8384	#[pallet::pallet]85	#[pallet::storage_version(STORAGE_VERSION)]86	#[pallet::generate_store(pub(super) trait Store)]87	pub struct Pallet<T>(_);8889	#[pallet::storage]90	pub type TokensMinted<T: Config> =91		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;92	#[pallet::storage]93	pub type TokensBurnt<T: Config> =94		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;9596	#[pallet::storage]97	pub type TokenData<T: Config> = StorageNMap<98		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),99		Value = ItemData,100		QueryKind = ValueQuery,101	>;102103	#[pallet::storage]104	pub type TotalSupply<T: Config> = StorageNMap<105		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),106		Value = u128,107		QueryKind = ValueQuery,108	>;109110	/// Used to enumerate tokens owned by account111	#[pallet::storage]112	pub type Owned<T: Config> = StorageNMap<113		Key = (114			Key<Twox64Concat, CollectionId>,115			Key<Blake2_128Concat, T::CrossAccountId>,116			Key<Twox64Concat, TokenId>,117		),118		Value = bool,119		QueryKind = ValueQuery,120	>;121122	#[pallet::storage]123	pub type AccountBalance<T: Config> = StorageNMap<124		Key = (125			Key<Twox64Concat, CollectionId>,126			// Owner127			Key<Blake2_128Concat, T::CrossAccountId>,128		),129		Value = u32,130		QueryKind = ValueQuery,131	>;132133	#[pallet::storage]134	pub type Balance<T: Config> = StorageNMap<135		Key = (136			Key<Twox64Concat, CollectionId>,137			Key<Twox64Concat, TokenId>,138			// Owner139			Key<Blake2_128Concat, T::CrossAccountId>,140		),141		Value = u128,142		QueryKind = ValueQuery,143	>;144145	#[pallet::storage]146	pub type Allowance<T: Config> = StorageNMap<147		Key = (148			Key<Twox64Concat, CollectionId>,149			Key<Twox64Concat, TokenId>,150			// Owner151			Key<Blake2_128, T::CrossAccountId>,152			// Spender153			Key<Blake2_128Concat, T::CrossAccountId>,154		),155		Value = u128,156		QueryKind = ValueQuery,157	>;158159	#[pallet::hooks]160	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {161		fn on_runtime_upgrade() -> Weight {162			if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {163				<TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {164					Some(<ItemDataVersion2>::from(v))165				})166			}167168			0169		}170	}171}172173pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);174impl<T: Config> RefungibleHandle<T> {175	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {176		Self(inner)177	}178	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {179		self.0180	}181}182impl<T: Config> Deref for RefungibleHandle<T> {183	type Target = pallet_common::CollectionHandle<T>;184185	fn deref(&self) -> &Self::Target {186		&self.0187	}188}189190impl<T: Config> Pallet<T> {191	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {192		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)193	}194	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {195		<TotalSupply<T>>::contains_key((collection.id, token))196	}197}198199// unchecked calls skips any permission checks200impl<T: Config> Pallet<T> {201	pub fn init_collection(202		owner: T::AccountId,203		data: CreateCollectionData<T::AccountId>,204	) -> Result<CollectionId, DispatchError> {205		<PalletCommon<T>>::init_collection(owner, data)206	}207	pub fn destroy_collection(208		collection: RefungibleHandle<T>,209		sender: &T::CrossAccountId,210	) -> DispatchResult {211		let id = collection.id;212213		if Self::collection_has_tokens(id) {214			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());215		}216217		// =========218219		PalletCommon::destroy_collection(collection.0, sender)?;220221		<TokensMinted<T>>::remove(id);222		<TokensBurnt<T>>::remove(id);223		<TokenData<T>>::remove_prefix((id,), None);224		<TotalSupply<T>>::remove_prefix((id,), None);225		<Balance<T>>::remove_prefix((id,), None);226		<Allowance<T>>::remove_prefix((id,), None);227		<Owned<T>>::remove_prefix((id,), None);228		<AccountBalance<T>>::remove_prefix((id,), None);229		Ok(())230	}231232	fn collection_has_tokens(collection_id: CollectionId) -> bool {233		<TokenData<T>>::iter_prefix((collection_id,)).next().is_some()234	}235236	pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {237		let burnt = <TokensBurnt<T>>::get(collection.id)238			.checked_add(1)239			.ok_or(ArithmeticError::Overflow)?;240241		<TokensBurnt<T>>::insert(collection.id, burnt);242		<TokenData<T>>::remove((collection.id, token_id));243		<TotalSupply<T>>::remove((collection.id, token_id));244		<Balance<T>>::remove_prefix((collection.id, token_id), None);245		<Allowance<T>>::remove_prefix((collection.id, token_id), None);246		// TODO: ERC721 transfer event247		Ok(())248	}249250	pub fn burn(251		collection: &RefungibleHandle<T>,252		owner: &T::CrossAccountId,253		token: TokenId,254		amount: u128,255	) -> DispatchResult {256		let total_supply = <TotalSupply<T>>::get((collection.id, token))257			.checked_sub(amount)258			.ok_or(<CommonError<T>>::TokenValueTooLow)?;259260		// This was probally last owner of this token?261		if total_supply == 0 {262			// Ensure user actually owns this amount263			ensure!(264				<Balance<T>>::get((collection.id, token, owner)) == amount,265				<CommonError<T>>::TokenValueTooLow266			);267			let account_balance = <AccountBalance<T>>::get((collection.id, owner))268				.checked_sub(1)269				// Should not occur270				.ok_or(ArithmeticError::Underflow)?;271272			// =========273274			<Owned<T>>::remove((collection.id, owner, token));275			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);276			<AccountBalance<T>>::insert((collection.id, owner), account_balance);277			Self::burn_token(collection, token)?;278			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(279				collection.id,280				token,281				owner.clone(),282				amount,283			));284			return Ok(());285		}286287		let balance = <Balance<T>>::get((collection.id, token, owner))288			.checked_sub(amount)289			.ok_or(<CommonError<T>>::TokenValueTooLow)?;290		let account_balance = if balance == 0 {291			<AccountBalance<T>>::get((collection.id, owner))292				.checked_sub(1)293				// Should not occur294				.ok_or(ArithmeticError::Underflow)?295		} else {296			0297		};298299		// =========300301		if balance == 0 {302			<Owned<T>>::remove((collection.id, owner, token));303			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);304			<Balance<T>>::remove((collection.id, token, owner));305			<AccountBalance<T>>::insert((collection.id, owner), account_balance);306		} else {307			<Balance<T>>::insert((collection.id, token, owner), balance);308		}309		<TotalSupply<T>>::insert((collection.id, token), total_supply);310		// TODO: ERC20 transfer event311		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(312			collection.id,313			token,314			owner.clone(),315			amount,316		));317		Ok(())318	}319320	pub fn transfer(321		collection: &RefungibleHandle<T>,322		from: &T::CrossAccountId,323		to: &T::CrossAccountId,324		token: TokenId,325		amount: u128,326		nesting_budget: &dyn Budget,327	) -> DispatchResult {328		ensure!(329			collection.limits.transfers_enabled(),330			<CommonError<T>>::TransferNotAllowed331		);332333		if collection.permissions.access() == AccessMode::AllowList {334			collection.check_allowlist(from)?;335			collection.check_allowlist(to)?;336		}337		<PalletCommon<T>>::ensure_correct_receiver(to)?;338339		let balance_from = <Balance<T>>::get((collection.id, token, from))340			.checked_sub(amount)341			.ok_or(<CommonError<T>>::TokenValueTooLow)?;342		let mut create_target = false;343		let from_to_differ = from != to;344		let balance_to = if from != to {345			let old_balance = <Balance<T>>::get((collection.id, token, to));346			if old_balance == 0 {347				create_target = true;348			}349			Some(350				old_balance351					.checked_add(amount)352					.ok_or(ArithmeticError::Overflow)?,353			)354		} else {355			None356		};357358		let account_balance_from = if balance_from == 0 {359			Some(360				<AccountBalance<T>>::get((collection.id, from))361					.checked_sub(1)362					// Should not occur363					.ok_or(ArithmeticError::Underflow)?,364			)365		} else {366			None367		};368		// Account data is created in token, AccountBalance should be increased369		// But only if from != to as we shouldn't check overflow in this case370		let account_balance_to = if create_target && from_to_differ {371			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))372				.checked_add(1)373				.ok_or(ArithmeticError::Overflow)?;374			ensure!(375				account_balance_to < collection.limits.account_token_ownership_limit(),376				<CommonError<T>>::AccountTokenLimitExceeded,377			);378379			Some(account_balance_to)380		} else {381			None382		};383384		// =========385386		<PalletStructure<T>>::nest_if_sent_to_token(387			from.clone(),388			to,389			collection.id,390			token,391			nesting_budget392		)?;393394		if let Some(balance_to) = balance_to {395			// from != to396			if balance_from == 0 {397				<Balance<T>>::remove((collection.id, token, from));398				<PalletStructure<T>>::unnest_if_nested(399					from,400					collection.id,401					token402				);403			} else {404				<Balance<T>>::insert((collection.id, token, from), balance_from);405			}406			<Balance<T>>::insert((collection.id, token, to), balance_to);407			if let Some(account_balance_from) = account_balance_from {408				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);409				<Owned<T>>::remove((collection.id, from, token));410			}411			if let Some(account_balance_to) = account_balance_to {412				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);413				<Owned<T>>::insert((collection.id, to, token), true);414			}415		}416417		// TODO: ERC20 transfer event418		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(419			collection.id,420			token,421			from.clone(),422			to.clone(),423			amount,424		));425		Ok(())426	}427428	pub fn create_multiple_items(429		collection: &RefungibleHandle<T>,430		sender: &T::CrossAccountId,431		data: Vec<CreateRefungibleExData<T::CrossAccountId>>,432		nesting_budget: &dyn Budget,433	) -> DispatchResult {434		if !collection.is_owner_or_admin(sender) {435			ensure!(436				collection.permissions.mint_mode(),437				<CommonError<T>>::PublicMintingNotAllowed438			);439			collection.check_allowlist(sender)?;440441			for item in data.iter() {442				for user in item.users.keys() {443					collection.check_allowlist(user)?;444				}445			}446		}447448		for item in data.iter() {449			for (owner, _) in item.users.iter() {450				<PalletCommon<T>>::ensure_correct_receiver(owner)?;451			}452		}453454		// Total pieces per tokens455		let totals = data456			.iter()457			.map(|data| {458				Ok(data459					.users460					.iter()461					.map(|u| u.1)462					.try_fold(0u128, |acc, v| acc.checked_add(*v))463					.ok_or(ArithmeticError::Overflow)?)464			})465			.collect::<Result<Vec<_>, DispatchError>>()?;466		for total in &totals {467			ensure!(468				*total <= MAX_REFUNGIBLE_PIECES,469				<Error<T>>::WrongRefungiblePieces470			);471		}472473		let first_token_id = <TokensMinted<T>>::get(collection.id);474		let tokens_minted = first_token_id475			.checked_add(data.len() as u32)476			.ok_or(ArithmeticError::Overflow)?;477		ensure!(478			tokens_minted < collection.limits.token_limit(),479			<CommonError<T>>::CollectionTokenLimitExceeded480		);481482		let mut balances = BTreeMap::new();483		for data in &data {484			for owner in data.users.keys() {485				let balance = balances486					.entry(owner)487					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));488				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;489490				ensure!(491					*balance <= collection.limits.account_token_ownership_limit(),492					<CommonError<T>>::AccountTokenLimitExceeded,493				);494			}495		}496497		for (i, token) in data.iter().enumerate() {498			let token_id = TokenId(first_token_id + i as u32 + 1);499			for (to, _) in token.users.iter() {500501				<PalletStructure<T>>::check_nesting(502					sender.clone(),503					to,504					collection.id,505					token_id,506					nesting_budget,507				)?;508			}509		}510511		// =========512513		<TokensMinted<T>>::insert(collection.id, tokens_minted);514		for (account, balance) in balances {515			<AccountBalance<T>>::insert((collection.id, account), balance);516		}517		for (i, token) in data.into_iter().enumerate() {518			let token_id = first_token_id + i as u32 + 1;519			<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);520521			<TokenData<T>>::insert(522				(collection.id, token_id),523				ItemData {524					const_data: token.const_data,525				},526			);527528			for (user, amount) in token.users.into_iter() {529				if amount == 0 {530					continue;531				}532				<Balance<T>>::insert((collection.id, token_id, &user), amount);533				<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);534				<PalletStructure<T>>::nest_if_sent_to_token_unchecked(&user, collection.id, TokenId(token_id));535536				// TODO: ERC20 transfer event537				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(538					collection.id,539					TokenId(token_id),540					user,541					amount,542				));543			}544		}545		Ok(())546	}547548	pub fn set_allowance_unchecked(549		collection: &RefungibleHandle<T>,550		sender: &T::CrossAccountId,551		spender: &T::CrossAccountId,552		token: TokenId,553		amount: u128,554	) {555		if amount == 0 {556			<Allowance<T>>::remove((collection.id, token, sender, spender));557		} else {558			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);559		}560		// TODO: ERC20 approval event561		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(562			collection.id,563			token,564			sender.clone(),565			spender.clone(),566			amount,567		))568	}569570	pub fn set_allowance(571		collection: &RefungibleHandle<T>,572		sender: &T::CrossAccountId,573		spender: &T::CrossAccountId,574		token: TokenId,575		amount: u128,576	) -> DispatchResult {577		if collection.permissions.access() == AccessMode::AllowList {578			collection.check_allowlist(sender)?;579			collection.check_allowlist(spender)?;580		}581582		<PalletCommon<T>>::ensure_correct_receiver(spender)?;583584		if <Balance<T>>::get((collection.id, token, sender)) < amount {585			ensure!(586				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),587				<CommonError<T>>::CantApproveMoreThanOwned588			);589		}590591		// =========592593		Self::set_allowance_unchecked(collection, sender, spender, token, amount);594		Ok(())595	}596597	/// Returns allowance, which should be set after transaction598	fn check_allowed(599		collection: &RefungibleHandle<T>,600		spender: &T::CrossAccountId,601		from: &T::CrossAccountId,602		token: TokenId,603		amount: u128,604		nesting_budget: &dyn Budget,605	) -> Result<Option<u128>, DispatchError> {606		if spender.conv_eq(from) {607			return Ok(None);608		}609		if collection.permissions.access() == AccessMode::AllowList {610			// `from`, `to` checked in [`transfer`]611			collection.check_allowlist(spender)?;612		}613		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {614			// TODO: should collection owner be allowed to perform this transfer?615			ensure!(616				<PalletStructure<T>>::check_indirectly_owned(617					spender.clone(),618					source.0,619					source.1,620					None,621					nesting_budget622				)?,623				<CommonError<T>>::ApprovedValueTooLow,624			);625			return Ok(None);626		}627		let allowance =628			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);629		if allowance.is_none() {630			ensure!(631				collection.ignores_allowance(spender),632				<CommonError<T>>::ApprovedValueTooLow633			);634		}635		Ok(allowance)636	}637638	pub fn transfer_from(639		collection: &RefungibleHandle<T>,640		spender: &T::CrossAccountId,641		from: &T::CrossAccountId,642		to: &T::CrossAccountId,643		token: TokenId,644		amount: u128,645		nesting_budget: &dyn Budget,646	) -> DispatchResult {647		let allowance =648			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;649650		// =========651652		Self::transfer(collection, from, to, token, amount, nesting_budget)?;653		if let Some(allowance) = allowance {654			Self::set_allowance_unchecked(collection, from, spender, token, allowance);655		}656		Ok(())657	}658659	pub fn burn_from(660		collection: &RefungibleHandle<T>,661		spender: &T::CrossAccountId,662		from: &T::CrossAccountId,663		token: TokenId,664		amount: u128,665		nesting_budget: &dyn Budget,666	) -> DispatchResult {667		let allowance =668			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;669670		// =========671672		Self::burn(collection, from, token, amount)?;673		if let Some(allowance) = allowance {674			Self::set_allowance_unchecked(collection, from, spender, token, allowance);675		}676		Ok(())677	}678679	/// Delegated to `create_multiple_items`680	pub fn create_item(681		collection: &RefungibleHandle<T>,682		sender: &T::CrossAccountId,683		data: CreateRefungibleExData<T::CrossAccountId>,684		nesting_budget: &dyn Budget,685	) -> DispatchResult {686		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)687	}688}
modifiedpallets/structure/src/lib.rsdiffbeforeafterboth
--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -1,8 +1,9 @@
 #![cfg_attr(not(feature = "std"), no_std)]
 
+use pallet_common::CommonCollectionOperations;
 use sp_std::collections::btree_set::BTreeSet;
 
-use frame_support::dispatch::DispatchError;
+use frame_support::dispatch::{DispatchError, DispatchResult};
 use frame_support::fail;
 pub use pallet::*;
 use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};
@@ -155,8 +156,8 @@
 		budget: &dyn Budget,
 	) -> Result<bool, DispatchError> {
 		let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {
-			Some((collection, token)) => Parent::Token(collection, token),
-			None => Parent::User(user),
+			Some((collection, token)) => Self::find_topmost_owner(collection, token, budget)?,
+			None => user,
 		};
 
 		// Tried to nest token in itself
@@ -171,10 +172,10 @@
 					return Err(<Error<T>>::OuroborosDetected.into())
 				}
 				// Found needed parent, token is indirecty owned
-				v if v == target_parent => return Ok(true),
+				Parent::User(user) if user == target_parent => return Ok(true),
 				// Token is owned by other user
 				Parent::User(_) => return Ok(false),
-				Parent::TokenNotFound => return Ok(false),
+				Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),
 				// Continue parent chain
 				Parent::Token(_, _) => {}
 			}
@@ -182,4 +183,113 @@
 
 		Err(<Error<T>>::DepthLimit.into())
 	}
+
+	pub fn check_nesting(
+		from: T::CrossAccountId,
+		under: &T::CrossAccountId,
+		collection_id: CollectionId,
+		token_id: TokenId,
+		nesting_budget: &dyn Budget
+	) -> DispatchResult {
+		Self::try_exec_if_owner_is_valid_nft(
+			under,
+			|d, parent_id| d.check_nesting(
+				from,
+				(collection_id, token_id),
+				parent_id,
+				nesting_budget
+			)
+		)
+	}
+
+	pub fn nest_if_sent_to_token(
+		from: T::CrossAccountId,
+		under: &T::CrossAccountId,
+		collection_id: CollectionId,
+		token_id: TokenId,
+		nesting_budget: &dyn Budget
+	) -> DispatchResult {
+		Self::try_exec_if_owner_is_valid_nft(
+			under,
+			|d, parent_id| {
+				d.check_nesting(
+					from,
+					(collection_id, token_id),
+					parent_id,
+					nesting_budget
+				)?;
+
+				d.nest(parent_id, (collection_id, token_id));
+
+				Ok(())
+			}
+		)
+	}
+
+	pub fn nest_if_sent_to_token_unchecked(
+		owner: &T::CrossAccountId,
+		collection_id: CollectionId,
+		token_id: TokenId
+	) {
+		Self::exec_if_owner_is_valid_nft(
+			owner,
+			|d, parent_id| d.nest(
+				parent_id,
+				(collection_id, token_id)
+			)
+		);
+	}
+
+	pub fn unnest_if_nested(
+		owner: &T::CrossAccountId,
+		collection_id: CollectionId,
+		token_id: TokenId
+	) {
+		Self::exec_if_owner_is_valid_nft(
+			owner,
+			|d, parent_id| d.unnest(
+			parent_id,
+			(collection_id, token_id)
+			)
+		);
+	}
+
+	fn exec_if_owner_is_valid_nft(
+		account: &T::CrossAccountId,
+		action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId)
+	) {
+		Self::try_exec_if_owner_is_valid_nft(
+			account,
+			|d, id| {
+				action(d, id);
+				Ok(())
+			}
+		).unwrap();
+	}
+
+	fn try_exec_if_owner_is_valid_nft(
+		account: &T::CrossAccountId,
+		action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult
+	) -> DispatchResult {
+		let account = T::CrossTokenAddressMapping::address_to_token(account);
+
+		if account.is_none() {
+			return Ok(());
+		}
+
+		let account = account.unwrap();
+
+		let handle = <CollectionHandle<T>>::try_get(account.0);
+
+		if handle.is_err() {
+			return Ok(());
+		}
+
+		let handle = handle.unwrap();
+
+		let dispatch = T::CollectionDispatch::dispatch(handle);
+		let dispatch = dispatch.as_dyn();
+
+		action(dispatch, account.1)
+	}
 }
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -55,6 +55,8 @@
 pub mod weights;
 use weights::WeightInfo;
 
+const NESTING_BUDGET: u32 = 5;
+
 decl_error! {
 	/// Error for non-fungible-token module.
 	pub enum Error for Module<T: Config> {
@@ -569,7 +571,7 @@
 		#[transactional]
 		pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResultWithPostInfo {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-			let budget = budget::Value::new(2);
+			let budget = budget::Value::new(NESTING_BUDGET);
 
 			dispatch_call::<T, _>(collection_id, |d| d.create_item(sender, owner, data, &budget))
 		}
@@ -597,7 +599,7 @@
 		pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResultWithPostInfo {
 			ensure!(!items_data.is_empty(), Error::<T>::EmptyArgument);
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-			let budget = budget::Value::new(2);
+			let budget = budget::Value::new(NESTING_BUDGET);
 
 			dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items(sender, owner, items_data, &budget))
 		}
@@ -678,7 +680,7 @@
 		#[transactional]
 		pub fn create_multiple_items_ex(origin, collection_id: CollectionId, data: CreateItemExData<T::CrossAccountId>) -> DispatchResultWithPostInfo {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-			let budget = budget::Value::new(2);
+			let budget = budget::Value::new(NESTING_BUDGET);
 
 			dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items_ex(sender, data, &budget))
 		}
@@ -758,7 +760,7 @@
 		#[transactional]
 		pub fn burn_from(origin, collection_id: CollectionId, from: T::CrossAccountId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-			let budget = budget::Value::new(2);
+			let budget = budget::Value::new(NESTING_BUDGET);
 
 			dispatch_call::<T, _>(collection_id, |d| d.burn_from(sender, from, item_id, value, &budget))
 		}
@@ -790,7 +792,7 @@
 		#[transactional]
 		pub fn transfer(origin, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-			let budget = budget::Value::new(2);
+			let budget = budget::Value::new(NESTING_BUDGET);
 
 			dispatch_call::<T, _>(collection_id, |d| d.transfer(sender, recipient, item_id, value, &budget))
 		}
@@ -841,7 +843,7 @@
 		#[transactional]
 		pub fn transfer_from(origin, from: T::CrossAccountId, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResultWithPostInfo {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-			let budget = budget::Value::new(2);
+			let budget = budget::Value::new(NESTING_BUDGET);
 
 			dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value, &budget))
 		}
modifiedruntime/common/src/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/src/runtime_apis.rs
+++ b/runtime/common/src/runtime_apis.rs
@@ -25,7 +25,7 @@
                     dispatch_unique_runtime!(collection.token_owner(token))
                 }
                 fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {
-                    let budget = up_data_structs::budget::Value::new(5);
+                    let budget = up_data_structs::budget::Value::new(10);
 
                     Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))
                 }
@@ -142,7 +142,7 @@
                 }
 
                 fn collection_by_id(collection_id: RmrkCollectionId) -> Result<Option<RmrkCollectionInfo<AccountId>>, DispatchError> {
-                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkDecode}};
+                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkDecode, RmrkRebind}};
 
                     let collection_id = CollectionId(collection_id);
                     let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Regular) {
@@ -156,7 +156,7 @@
                         issuer: collection.owner.clone(),
                         metadata: RmrkCore::get_collection_property(collection_id, RmrkProperty::Metadata)?.decode_or_default(),
                         max: collection.limits.token_limit,
-                        symbol: collection.token_prefix.decode_or_default(),
+                        symbol: collection.token_prefix.rebind(),
                         nfts_count
                     }))
                 }
@@ -204,22 +204,21 @@
                 }
 
                 fn nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkNftChild>, DispatchError> {
-                    use up_data_structs::mapping::TokenAddressMapping;
-
                     let collection_id = CollectionId(collection_id);
                     let nft_id = TokenId(nft_id);
                     if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(Vec::new()); }
 
-                    let cross_account_id = CrossAccountId::from_eth(
-                        EvmTokenAddressMapping::token_to_address(collection_id, nft_id)
-                    );
-
                     Ok(
-                        pallet_nonfungible::Owned::<Runtime>::iter_prefix((collection_id, cross_account_id))
-                            .map(|(child_id, _)| RmrkNftChild {
-                                collection_id: collection_id.0, // todo make sure they're always from this collection // spoiler: they're not
-                                nft_id: child_id.0,
-                            }).collect()
+                        pallet_nonfungible::TokenChildren::<Runtime>::iter_prefix((collection_id, nft_id))
+                            .filter_map(|(child_id, is_child)|
+                                match is_child {
+                                    true => Some(RmrkNftChild {
+                                        collection_id: child_id.0.0,
+                                        nft_id: child_id.1.0,
+                                    }),
+                                    false => None,
+                                }
+                            ).collect()
                     )
                 }
 
@@ -332,7 +331,7 @@
 
                 fn base(base_id: RmrkBaseId) -> Result<Option<RmrkBaseInfo<AccountId>>, DispatchError> {
                     use pallet_proxy_rmrk_core::{
-                        RmrkProperty, misc::{CollectionType, RmrkDecode},
+                        RmrkProperty, misc::{CollectionType, RmrkDecode, RmrkRebind},
                     };
 
                     let collection_id = CollectionId(base_id);
@@ -344,7 +343,7 @@
                     Ok(Some(RmrkBaseInfo {
                         issuer: collection.owner.clone(),
                         base_type: RmrkCore::get_collection_property(collection_id, RmrkProperty::BaseType)?.decode_or_default(),
-                        symbol: collection.token_prefix.decode_or_default(),
+                        symbol: collection.token_prefix.rebind(),
                     }))
                 }
 
modifiedtests/src/nesting/nest.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/nest.test.ts
+++ b/tests/src/nesting/nest.test.ts
@@ -41,7 +41,7 @@
 
       // Create a token to be nested
       const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
-      
+
       // Nest
       await transferExpectSuccess(collection, newToken, alice, {Ethereum: tokenIdToAddress(collection, targetToken)});
       expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
@@ -111,8 +111,8 @@
 
       // Create a nested token
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionFT, 
-        targetAddress, 
+        collectionFT,
+        targetAddress,
         {Fungible: {Value: 10}},
       ))).to.not.be.rejected;
 
@@ -134,8 +134,8 @@
 
       // Create a nested token
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionFT, 
-        targetAddress, 
+        collectionFT,
+        targetAddress,
         {Fungible: {Value: 10}},
       ))).to.not.be.rejected;
 
@@ -158,8 +158,8 @@
 
       // Create a nested token
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionRFT, 
-        targetAddress, 
+        collectionRFT,
+        targetAddress,
         {ReFungible: {const_data: [], pieces: 100}},
       ))).to.not.be.rejected;
 
@@ -181,7 +181,7 @@
 
       // Create a nested token
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionRFT, 
+        collectionRFT,
         targetAddress,
         {ReFungible: {const_data: [], pieces: 100}},
       ))).to.not.be.rejected;
@@ -207,17 +207,29 @@
       await setCollectionPermissionsExceptSuccess(alice, collection, {nesting: 'Owner'});
       const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
 
+      const maxNestingLevel = 5;
+      let prevToken = targetToken;
+
       // Create a nested-token matryoshka
-      const nestedToken1 = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});
-      const nestedToken2 = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, nestedToken1)});
-      // The nesting depth is limited by 2
+      for (let i = 0; i < maxNestingLevel; i++) {
+        const nestedToken = await createItemExpectSuccess(
+          alice,
+          collection,
+          'NFT',
+          {Ethereum: tokenIdToAddress(collection, prevToken)},
+        );
+
+        prevToken = nestedToken;
+      }
+
+      // The nesting depth is limited by `maxNestingLevel`
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collection, 
-        {Ethereum: tokenIdToAddress(collection, nestedToken2)}, 
+        collection,
+        {Ethereum: tokenIdToAddress(collection, prevToken)},
           {nft: {const_data: [], variable_data: []}} as any,
       )), 'while creating nested token').to.be.rejectedWith(/^structure\.DepthLimit$/);
 
-      expect(await getTopmostTokenOwner(api, collection, nestedToken2)).to.be.deep.equal({Substrate: alice.address});
+      expect(await getTopmostTokenOwner(api, collection, prevToken)).to.be.deep.equal({Substrate: alice.address});
     });
   });
 
@@ -231,8 +243,8 @@
 
       // Try to create a nested token
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collection, 
-        {Ethereum: tokenIdToAddress(collection, targetToken)}, 
+        collection,
+        {Ethereum: tokenIdToAddress(collection, targetToken)},
           {nft: {const_data: [], variable_data: []}} as any,
       )), 'while creating nested token').to.be.rejectedWith(/^common\.NestingIsDisabled$/);
 
@@ -259,8 +271,8 @@
 
       // Try to create a nested token in the wrong collection
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collection, 
-        {Ethereum: tokenIdToAddress(collection, targetToken)}, 
+        collection,
+        {Ethereum: tokenIdToAddress(collection, targetToken)},
           {nft: {const_data: [], variable_data: []}} as any,
       )), 'while creating nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
 
@@ -285,8 +297,8 @@
 
       // Try to create a nested token in the wrong collection
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collection, 
-        {Ethereum: tokenIdToAddress(collection, targetToken)}, 
+        collection,
+        {Ethereum: tokenIdToAddress(collection, targetToken)},
           {nft: {const_data: [], variable_data: []}} as any,
       )), 'while creating nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
 
@@ -307,8 +319,8 @@
 
       // Try to create a nested token in the wrong collection
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collection, 
-        {Ethereum: tokenIdToAddress(collection, targetToken)}, 
+        collection,
+        {Ethereum: tokenIdToAddress(collection, targetToken)},
           {nft: {const_data: [], variable_data: []}} as any,
       )), 'while creating nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
 
@@ -332,11 +344,11 @@
 
       // Try to create a nested token
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionFT, 
-        targetAddress, 
+        collectionFT,
+        targetAddress,
         {Fungible: {Value: 10}},
       )), 'while creating nested token').to.be.rejectedWith(/^common\.NestingIsDisabled$/);
-      
+
       // Create a token to be nested
       const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
       // Try to nest
@@ -366,8 +378,8 @@
 
       // Try to create a nested token in the wrong collection
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionFT, 
-        targetAddress, 
+        collectionFT,
+        targetAddress,
         {Fungible: {Value: 10}},
       )), 'while creating nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
 
@@ -393,8 +405,8 @@
 
       // Try to create a nested token in the wrong collection
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionFT, 
-        targetAddress, 
+        collectionFT,
+        targetAddress,
         {Fungible: {Value: 10}},
       )), 'while creating nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
 
@@ -417,8 +429,8 @@
 
       // Try to create a nested token in the wrong collection
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionFT, 
-        targetAddress, 
+        collectionFT,
+        targetAddress,
         {Fungible: {Value: 10}},
       )), 'while creating a nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
 
@@ -441,8 +453,8 @@
 
       // Create a nested token
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionRFT, 
-        targetAddress, 
+        collectionRFT,
+        targetAddress,
         {ReFungible: {const_data: [], pieces: 100}},
       )), 'while creating a nested token').to.be.rejectedWith(/^common\.NestingIsDisabled$/);
 
@@ -477,8 +489,8 @@
 
       // Try to create a nested token in the wrong collection
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionRFT, 
-        targetAddress, 
+        collectionRFT,
+        targetAddress,
         {ReFungible: {const_data: [], pieces: 100}},
       )), 'while creating a nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
 
@@ -504,8 +516,8 @@
 
       // Try to create a nested token in the wrong collection
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionRFT, 
-        targetAddress, 
+        collectionRFT,
+        targetAddress,
         {ReFungible: {const_data: [], pieces: 100}},
       )), 'while creating a nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
 
@@ -528,8 +540,8 @@
 
       // Try to create a nested token in the wrong collection
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionRFT, 
-        targetAddress, 
+        collectionRFT,
+        targetAddress,
         {ReFungible: {const_data: [], pieces: 100}},
       )), 'while creating a nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);