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
before · pallets/refungible/src/common.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/>.1617use core::marker::PhantomData;1819use sp_std::collections::btree_map::BTreeMap;20use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight};21use up_data_structs::{22	CollectionId, TokenId, CreateItemExData, CreateRefungibleExData, budget::Budget, Property,23	PropertyKey, PropertyValue, PropertyKeyPermission, CreateItemData,24};25use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};26use sp_runtime::DispatchError;27use sp_std::{vec::Vec, vec};2829use crate::{30	AccountBalance, Allowance, Balance, Config, Error, Owned, Pallet, RefungibleHandle,31	SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted,32};3334macro_rules! max_weight_of {35	($($method:ident ($($args:tt)*)),*) => {36		037		$(38			.max(<SelfWeightOf<T>>::$method($($args)*))39		)*40	};41}4243pub struct CommonWeights<T: Config>(PhantomData<T>);44impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {45	fn create_item() -> Weight {46		<SelfWeightOf<T>>::create_item()47	}4849	fn create_multiple_items(data: &[CreateItemData]) -> Weight {50		<SelfWeightOf<T>>::create_multiple_items(data.len() as u32)51	}5253	fn create_multiple_items_ex(call: &CreateItemExData<T::CrossAccountId>) -> Weight {54		match call {55			CreateItemExData::RefungibleMultipleOwners(i) => {56				<SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(i.users.len() as u32)57			}58			CreateItemExData::RefungibleMultipleItems(i) => {59				<SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(i.len() as u32)60			}61			_ => 0,62		}63	}6465	fn burn_item() -> Weight {66		max_weight_of!(burn_item_partial(), burn_item_fully())67	}6869	fn set_collection_properties(_amount: u32) -> Weight {70		// Error71		072	}7374	fn delete_collection_properties(_amount: u32) -> Weight {75		// Error76		077	}7879	fn set_token_properties(amount: u32) -> Weight {80		<SelfWeightOf<T>>::set_token_properties(amount)81	}8283	fn delete_token_properties(amount: u32) -> Weight {84		<SelfWeightOf<T>>::delete_token_properties(amount)85	}8687	fn set_property_permissions(amount: u32) -> Weight {88		<SelfWeightOf<T>>::set_property_permissions(amount)89	}9091	fn transfer() -> Weight {92		max_weight_of!(93			transfer_normal(),94			transfer_creating(),95			transfer_removing(),96			transfer_creating_removing()97		)98	}99100	fn approve() -> Weight {101		<SelfWeightOf<T>>::approve()102	}103104	fn transfer_from() -> Weight {105		max_weight_of!(106			transfer_from_normal(),107			transfer_from_creating(),108			transfer_from_removing(),109			transfer_from_creating_removing()110		)111	}112113	fn burn_from() -> Weight {114		<SelfWeightOf<T>>::burn_from()115	}116}117118fn map_create_data<T: Config>(119	data: up_data_structs::CreateItemData,120	to: &T::CrossAccountId,121) -> Result<CreateRefungibleExData<T::CrossAccountId>, DispatchError> {122	match data {123		up_data_structs::CreateItemData::ReFungible(data) => Ok(CreateRefungibleExData {124			const_data: data.const_data,125			users: {126				let mut out = BTreeMap::new();127				out.insert(to.clone(), data.pieces);128				out.try_into().expect("limit > 0")129			},130		}),131		_ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),132	}133}134135impl<T: Config> CommonCollectionOperations<T> for RefungibleHandle<T> {136	fn create_item(137		&self,138		sender: T::CrossAccountId,139		to: T::CrossAccountId,140		data: up_data_structs::CreateItemData,141		nesting_budget: &dyn Budget,142	) -> DispatchResultWithPostInfo {143		with_weight(144			<Pallet<T>>::create_item(145				self,146				&sender,147				map_create_data::<T>(data, &to)?,148				nesting_budget,149			),150			<CommonWeights<T>>::create_item(),151		)152	}153154	fn create_multiple_items(155		&self,156		sender: T::CrossAccountId,157		to: T::CrossAccountId,158		data: Vec<up_data_structs::CreateItemData>,159		nesting_budget: &dyn Budget,160	) -> DispatchResultWithPostInfo {161		let weight = <CommonWeights<T>>::create_multiple_items(&data);162		let data = data163			.into_iter()164			.map(|d| map_create_data::<T>(d, &to))165			.collect::<Result<Vec<_>, DispatchError>>()?;166167		with_weight(168			<Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),169			weight,170		)171	}172173	fn create_multiple_items_ex(174		&self,175		sender: <T>::CrossAccountId,176		data: CreateItemExData<T::CrossAccountId>,177		nesting_budget: &dyn Budget,178	) -> DispatchResultWithPostInfo {179		let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);180		let data = match data {181			CreateItemExData::RefungibleMultipleOwners(r) => vec![r],182			CreateItemExData::RefungibleMultipleItems(r)183				if r.iter().all(|i| i.users.len() == 1) =>184			{185				r.into_inner()186			}187			_ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),188		};189190		with_weight(191			<Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),192			weight,193		)194	}195196	fn burn_item(197		&self,198		sender: T::CrossAccountId,199		token: TokenId,200		amount: u128,201	) -> DispatchResultWithPostInfo {202		with_weight(203			<Pallet<T>>::burn(self, &sender, token, amount),204			<CommonWeights<T>>::burn_item(),205		)206	}207208	fn transfer(209		&self,210		from: T::CrossAccountId,211		to: T::CrossAccountId,212		token: TokenId,213		amount: u128,214		nesting_budget: &dyn Budget,215	) -> DispatchResultWithPostInfo {216		with_weight(217			<Pallet<T>>::transfer(self, &from, &to, token, amount, nesting_budget),218			<CommonWeights<T>>::transfer(),219		)220	}221222	fn approve(223		&self,224		sender: T::CrossAccountId,225		spender: T::CrossAccountId,226		token: TokenId,227		amount: u128,228	) -> DispatchResultWithPostInfo {229		with_weight(230			<Pallet<T>>::set_allowance(self, &sender, &spender, token, amount),231			<CommonWeights<T>>::approve(),232		)233	}234235	fn transfer_from(236		&self,237		sender: T::CrossAccountId,238		from: T::CrossAccountId,239		to: T::CrossAccountId,240		token: TokenId,241		amount: u128,242		nesting_budget: &dyn Budget,243	) -> DispatchResultWithPostInfo {244		with_weight(245			<Pallet<T>>::transfer_from(self, &sender, &from, &to, token, amount, nesting_budget),246			<CommonWeights<T>>::transfer_from(),247		)248	}249250	fn burn_from(251		&self,252		sender: T::CrossAccountId,253		from: T::CrossAccountId,254		token: TokenId,255		amount: u128,256		nesting_budget: &dyn Budget,257	) -> DispatchResultWithPostInfo {258		with_weight(259			<Pallet<T>>::burn_from(self, &sender, &from, token, amount, nesting_budget),260			<CommonWeights<T>>::burn_from(),261		)262	}263264	fn set_collection_properties(265		&self,266		_sender: T::CrossAccountId,267		_property: Vec<Property>,268	) -> DispatchResultWithPostInfo {269		fail!(<Error<T>>::SettingPropertiesNotAllowed)270	}271272	fn delete_collection_properties(273		&self,274		_sender: &T::CrossAccountId,275		_property_keys: Vec<PropertyKey>,276	) -> DispatchResultWithPostInfo {277		fail!(<Error<T>>::SettingPropertiesNotAllowed)278	}279280	fn set_token_properties(281		&self,282		_sender: T::CrossAccountId,283		_token_id: TokenId,284		_property: Vec<Property>,285	) -> DispatchResultWithPostInfo {286		fail!(<Error<T>>::SettingPropertiesNotAllowed)287	}288289	fn set_property_permissions(290		&self,291		_sender: &T::CrossAccountId,292		_property_permissions: Vec<PropertyKeyPermission>,293	) -> DispatchResultWithPostInfo {294		fail!(<Error<T>>::SettingPropertiesNotAllowed)295	}296297	fn delete_token_properties(298		&self,299		_sender: T::CrossAccountId,300		_token_id: TokenId,301		_property_keys: Vec<PropertyKey>,302	) -> DispatchResultWithPostInfo {303		fail!(<Error<T>>::SettingPropertiesNotAllowed)304	}305306	fn check_nesting(307		&self,308		_sender: <T>::CrossAccountId,309		_from: (CollectionId, TokenId),310		_under: TokenId,311		_budget: &dyn Budget,312	) -> sp_runtime::DispatchResult {313		fail!(<Error<T>>::RefungibleDisallowsNesting)314	}315316	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {317		<Owned<T>>::iter_prefix((self.id, account))318			.map(|(id, _)| id)319			.collect()320	}321322	fn collection_tokens(&self) -> Vec<TokenId> {323		<TokenData<T>>::iter_prefix((self.id,))324			.map(|(id, _)| id)325			.collect()326	}327328	fn token_exists(&self, token: TokenId) -> bool {329		<Pallet<T>>::token_exists(self, token)330	}331332	fn last_token_id(&self) -> TokenId {333		TokenId(<TokensMinted<T>>::get(self.id))334	}335336	fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {337		None338	}339340	fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {341		None342	}343344	fn token_properties(345		&self,346		_token_id: TokenId,347		_keys: Option<Vec<PropertyKey>>,348	) -> Vec<Property> {349		Vec::new()350	}351352	fn total_supply(&self) -> u32 {353		<Pallet<T>>::total_supply(self)354	}355356	fn account_balance(&self, account: T::CrossAccountId) -> u32 {357		<AccountBalance<T>>::get((self.id, account))358	}359360	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {361		<Balance<T>>::get((self.id, token, account))362	}363364	fn allowance(365		&self,366		sender: T::CrossAccountId,367		spender: T::CrossAccountId,368		token: TokenId,369	) -> u128 {370		<Allowance<T>>::get((self.id, token, sender, spender))371	}372}
after · pallets/refungible/src/common.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/>.1617use core::marker::PhantomData;1819use sp_std::collections::btree_map::BTreeMap;20use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight};21use up_data_structs::{22	CollectionId, TokenId, CreateItemExData, CreateRefungibleExData, budget::Budget, Property,23	PropertyKey, PropertyValue, PropertyKeyPermission, CreateItemData,24};25use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};26use sp_runtime::DispatchError;27use sp_std::{vec::Vec, vec};2829use crate::{30	AccountBalance, Allowance, Balance, Config, Error, Owned, Pallet, RefungibleHandle,31	SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted,32};3334macro_rules! max_weight_of {35	($($method:ident ($($args:tt)*)),*) => {36		037		$(38			.max(<SelfWeightOf<T>>::$method($($args)*))39		)*40	};41}4243pub struct CommonWeights<T: Config>(PhantomData<T>);44impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {45	fn create_item() -> Weight {46		<SelfWeightOf<T>>::create_item()47	}4849	fn create_multiple_items(data: &[CreateItemData]) -> Weight {50		<SelfWeightOf<T>>::create_multiple_items(data.len() as u32)51	}5253	fn create_multiple_items_ex(call: &CreateItemExData<T::CrossAccountId>) -> Weight {54		match call {55			CreateItemExData::RefungibleMultipleOwners(i) => {56				<SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(i.users.len() as u32)57			}58			CreateItemExData::RefungibleMultipleItems(i) => {59				<SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(i.len() as u32)60			}61			_ => 0,62		}63	}6465	fn burn_item() -> Weight {66		max_weight_of!(burn_item_partial(), burn_item_fully())67	}6869	fn set_collection_properties(_amount: u32) -> Weight {70		// Error71		072	}7374	fn delete_collection_properties(_amount: u32) -> Weight {75		// Error76		077	}7879	fn set_token_properties(amount: u32) -> Weight {80		<SelfWeightOf<T>>::set_token_properties(amount)81	}8283	fn delete_token_properties(amount: u32) -> Weight {84		<SelfWeightOf<T>>::delete_token_properties(amount)85	}8687	fn set_property_permissions(amount: u32) -> Weight {88		<SelfWeightOf<T>>::set_property_permissions(amount)89	}9091	fn transfer() -> Weight {92		max_weight_of!(93			transfer_normal(),94			transfer_creating(),95			transfer_removing(),96			transfer_creating_removing()97		)98	}99100	fn approve() -> Weight {101		<SelfWeightOf<T>>::approve()102	}103104	fn transfer_from() -> Weight {105		max_weight_of!(106			transfer_from_normal(),107			transfer_from_creating(),108			transfer_from_removing(),109			transfer_from_creating_removing()110		)111	}112113	fn burn_from() -> Weight {114		<SelfWeightOf<T>>::burn_from()115	}116}117118fn map_create_data<T: Config>(119	data: up_data_structs::CreateItemData,120	to: &T::CrossAccountId,121) -> Result<CreateRefungibleExData<T::CrossAccountId>, DispatchError> {122	match data {123		up_data_structs::CreateItemData::ReFungible(data) => Ok(CreateRefungibleExData {124			const_data: data.const_data,125			users: {126				let mut out = BTreeMap::new();127				out.insert(to.clone(), data.pieces);128				out.try_into().expect("limit > 0")129			},130		}),131		_ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),132	}133}134135impl<T: Config> CommonCollectionOperations<T> for RefungibleHandle<T> {136	fn create_item(137		&self,138		sender: T::CrossAccountId,139		to: T::CrossAccountId,140		data: up_data_structs::CreateItemData,141		nesting_budget: &dyn Budget,142	) -> DispatchResultWithPostInfo {143		with_weight(144			<Pallet<T>>::create_item(145				self,146				&sender,147				map_create_data::<T>(data, &to)?,148				nesting_budget,149			),150			<CommonWeights<T>>::create_item(),151		)152	}153154	fn create_multiple_items(155		&self,156		sender: T::CrossAccountId,157		to: T::CrossAccountId,158		data: Vec<up_data_structs::CreateItemData>,159		nesting_budget: &dyn Budget,160	) -> DispatchResultWithPostInfo {161		let weight = <CommonWeights<T>>::create_multiple_items(&data);162		let data = data163			.into_iter()164			.map(|d| map_create_data::<T>(d, &to))165			.collect::<Result<Vec<_>, DispatchError>>()?;166167		with_weight(168			<Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),169			weight,170		)171	}172173	fn create_multiple_items_ex(174		&self,175		sender: <T>::CrossAccountId,176		data: CreateItemExData<T::CrossAccountId>,177		nesting_budget: &dyn Budget,178	) -> DispatchResultWithPostInfo {179		let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);180		let data = match data {181			CreateItemExData::RefungibleMultipleOwners(r) => vec![r],182			CreateItemExData::RefungibleMultipleItems(r)183				if r.iter().all(|i| i.users.len() == 1) =>184			{185				r.into_inner()186			}187			_ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),188		};189190		with_weight(191			<Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),192			weight,193		)194	}195196	fn burn_item(197		&self,198		sender: T::CrossAccountId,199		token: TokenId,200		amount: u128,201	) -> DispatchResultWithPostInfo {202		with_weight(203			<Pallet<T>>::burn(self, &sender, token, amount),204			<CommonWeights<T>>::burn_item(),205		)206	}207208	fn transfer(209		&self,210		from: T::CrossAccountId,211		to: T::CrossAccountId,212		token: TokenId,213		amount: u128,214		nesting_budget: &dyn Budget,215	) -> DispatchResultWithPostInfo {216		with_weight(217			<Pallet<T>>::transfer(self, &from, &to, token, amount, nesting_budget),218			<CommonWeights<T>>::transfer(),219		)220	}221222	fn approve(223		&self,224		sender: T::CrossAccountId,225		spender: T::CrossAccountId,226		token: TokenId,227		amount: u128,228	) -> DispatchResultWithPostInfo {229		with_weight(230			<Pallet<T>>::set_allowance(self, &sender, &spender, token, amount),231			<CommonWeights<T>>::approve(),232		)233	}234235	fn transfer_from(236		&self,237		sender: T::CrossAccountId,238		from: T::CrossAccountId,239		to: T::CrossAccountId,240		token: TokenId,241		amount: u128,242		nesting_budget: &dyn Budget,243	) -> DispatchResultWithPostInfo {244		with_weight(245			<Pallet<T>>::transfer_from(self, &sender, &from, &to, token, amount, nesting_budget),246			<CommonWeights<T>>::transfer_from(),247		)248	}249250	fn burn_from(251		&self,252		sender: T::CrossAccountId,253		from: T::CrossAccountId,254		token: TokenId,255		amount: u128,256		nesting_budget: &dyn Budget,257	) -> DispatchResultWithPostInfo {258		with_weight(259			<Pallet<T>>::burn_from(self, &sender, &from, token, amount, nesting_budget),260			<CommonWeights<T>>::burn_from(),261		)262	}263264	fn set_collection_properties(265		&self,266		_sender: T::CrossAccountId,267		_property: Vec<Property>,268	) -> DispatchResultWithPostInfo {269		fail!(<Error<T>>::SettingPropertiesNotAllowed)270	}271272	fn delete_collection_properties(273		&self,274		_sender: &T::CrossAccountId,275		_property_keys: Vec<PropertyKey>,276	) -> DispatchResultWithPostInfo {277		fail!(<Error<T>>::SettingPropertiesNotAllowed)278	}279280	fn set_token_properties(281		&self,282		_sender: T::CrossAccountId,283		_token_id: TokenId,284		_property: Vec<Property>,285	) -> DispatchResultWithPostInfo {286		fail!(<Error<T>>::SettingPropertiesNotAllowed)287	}288289	fn set_property_permissions(290		&self,291		_sender: &T::CrossAccountId,292		_property_permissions: Vec<PropertyKeyPermission>,293	) -> DispatchResultWithPostInfo {294		fail!(<Error<T>>::SettingPropertiesNotAllowed)295	}296297	fn delete_token_properties(298		&self,299		_sender: T::CrossAccountId,300		_token_id: TokenId,301		_property_keys: Vec<PropertyKey>,302	) -> DispatchResultWithPostInfo {303		fail!(<Error<T>>::SettingPropertiesNotAllowed)304	}305306	fn check_nesting(307		&self,308		_sender: <T>::CrossAccountId,309		_from: (CollectionId, TokenId),310		_under: TokenId,311		_budget: &dyn Budget,312	) -> sp_runtime::DispatchResult {313		fail!(<Error<T>>::RefungibleDisallowsNesting)314	}315316	fn nest(317		&self,318		_under: TokenId,319		_to_nest: (CollectionId, TokenId)320	) {}321322	fn unnest(323		&self,324		_under: TokenId,325		_to_nest: (CollectionId, TokenId)326	) {}327328	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {329		<Owned<T>>::iter_prefix((self.id, account))330			.map(|(id, _)| id)331			.collect()332	}333334	fn collection_tokens(&self) -> Vec<TokenId> {335		<TokenData<T>>::iter_prefix((self.id,))336			.map(|(id, _)| id)337			.collect()338	}339340	fn token_exists(&self, token: TokenId) -> bool {341		<Pallet<T>>::token_exists(self, token)342	}343344	fn last_token_id(&self) -> TokenId {345		TokenId(<TokensMinted<T>>::get(self.id))346	}347348	fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {349		None350	}351352	fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {353		None354	}355356	fn token_properties(357		&self,358		_token_id: TokenId,359		_keys: Option<Vec<PropertyKey>>,360	) -> Vec<Property> {361		Vec::new()362	}363364	fn total_supply(&self) -> u32 {365		<Pallet<T>>::total_supply(self)366	}367368	fn account_balance(&self, account: T::CrossAccountId) -> u32 {369		<AccountBalance<T>>::get((self.id, account))370	}371372	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {373		<Balance<T>>::get((self.id, token, account))374	}375376	fn allowance(377		&self,378		sender: T::CrossAccountId,379		spender: T::CrossAccountId,380		token: TokenId,381	) -> u128 {382		<Allowance<T>>::get((self.id, token, sender, spender))383	}384}
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -23,8 +23,7 @@
 };
 use pallet_evm::account::CrossAccountId;
 use pallet_common::{
-	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, CollectionHandle,
-	dispatch::CollectionDispatch,
+	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
 };
 use pallet_structure::Pallet as PalletStructure;
 use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
@@ -211,6 +210,10 @@
 	) -> DispatchResult {
 		let id = collection.id;
 
+		if Self::collection_has_tokens(id) {
+			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());
+		}
+
 		// =========
 
 		PalletCommon::destroy_collection(collection.0, sender)?;
@@ -226,6 +229,10 @@
 		Ok(())
 	}
 
+	fn collection_has_tokens(collection_id: CollectionId) -> bool {
+		<TokenData<T>>::iter_prefix((collection_id,)).next().is_some()
+	}
+
 	pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {
 		let burnt = <TokensBurnt<T>>::get(collection.id)
 			.checked_add(1)
@@ -265,6 +272,7 @@
 			// =========
 
 			<Owned<T>>::remove((collection.id, owner, token));
+			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);
 			<AccountBalance<T>>::insert((collection.id, owner), account_balance);
 			Self::burn_token(collection, token)?;
 			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(
@@ -292,6 +300,7 @@
 
 		if balance == 0 {
 			<Owned<T>>::remove((collection.id, owner, token));
+			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);
 			<Balance<T>>::remove((collection.id, token, owner));
 			<AccountBalance<T>>::insert((collection.id, owner), account_balance);
 		} else {
@@ -372,25 +381,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, token),
-				target.1,
-				nesting_budget,
-			)?;
-		}
-
-		// =========
+		<PalletStructure<T>>::nest_if_sent_to_token(
+			from.clone(),
+			to,
+			collection.id,
+			token,
+			nesting_budget
+		)?;
 
 		if let Some(balance_to) = balance_to {
 			// from != to
 			if balance_from == 0 {
 				<Balance<T>>::remove((collection.id, token, from));
+				<PalletStructure<T>>::unnest_if_nested(
+					from,
+					collection.id,
+					token
+				);
 			} else {
 				<Balance<T>>::insert((collection.id, token, from), balance_from);
 			}
@@ -488,18 +497,14 @@
 		for (i, token) in data.iter().enumerate() {
 			let token_id = TokenId(first_token_id + i as u32 + 1);
 			for (to, _) in token.users.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, token_id),
-						target.1,
-						nesting_budget,
-					)?;
-				}
+				<PalletStructure<T>>::check_nesting(
+					sender.clone(),
+					to,
+					collection.id,
+					token_id,
+					nesting_budget,
+				)?;
 			}
 		}
 
@@ -519,12 +524,15 @@
 					const_data: token.const_data,
 				},
 			);
+
 			for (user, amount) in token.users.into_iter() {
 				if amount == 0 {
 					continue;
 				}
 				<Balance<T>>::insert((collection.id, token_id, &user), amount);
 				<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);
+				<PalletStructure<T>>::nest_if_sent_to_token_unchecked(&user, collection.id, TokenId(token_id));
+
 				// TODO: ERC20 transfer event
 				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(
 					collection.id,
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/);