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

difftreelog

feat add token children

Daniel Shiposha2022-05-26parent: #459d9af.patch.diff
in: master

6 files changed

modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -1237,6 +1237,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/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;
@@ -176,6 +176,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);
 		}
@@ -228,22 +233,17 @@
 		} else {
 			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>>::try_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 {
@@ -306,18 +306,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 +320,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(&user, collection.id, TokenId::default());
 			<PalletEvm<T>>::deposit_log(
 				ERC20Events::Transfer {
 					from: H160::default(),
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
before · pallets/nonfungible/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 frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};20use up_data_structs::{21	TokenId, CreateItemExData, CollectionId, budget::Budget, Property, PropertyKey,22	PropertyKeyPermission, PropertyValue,23};24use pallet_common::{25	CommonCollectionOperations, CommonWeightInfo, with_weight, weights::WeightInfo as _,26};27use sp_runtime::DispatchError;28use sp_std::vec::Vec;2930use crate::{31	AccountBalance, Allowance, Config, CreateItemData, Error, NonfungibleHandle, Owned, Pallet,32	SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted,33};3435pub struct CommonWeights<T: Config>(PhantomData<T>);36impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {37	fn create_item() -> Weight {38		<SelfWeightOf<T>>::create_item()39	}4041	fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {42		match data {43			CreateItemExData::NFT(t) => {44				<SelfWeightOf<T>>::create_multiple_items_ex(t.len() as u32)45					+ t.iter()46						.map(|t| {47							if t.properties.len() > 0 {48								Self::set_token_properties(t.properties.len() as u32)49							} else {50								051							}52						})53						.sum::<u64>()54			}55			_ => 0,56		}57	}5859	fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {60		<SelfWeightOf<T>>::create_multiple_items(data.len() as u32)61			+ data62				.iter()63				.filter_map(|t| match t {64					up_data_structs::CreateItemData::NFT(n) if n.properties.len() > 0 => {65						Some(Self::set_token_properties(n.properties.len() as u32))66					}67					_ => None,68				})69				.sum::<u64>()70	}7172	fn burn_item() -> Weight {73		<SelfWeightOf<T>>::burn_item()74	}7576	fn set_collection_properties(amount: u32) -> Weight {77		<pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)78	}7980	fn delete_collection_properties(amount: u32) -> Weight {81		<pallet_common::SelfWeightOf<T>>::delete_collection_properties(amount)82	}8384	fn set_token_properties(amount: u32) -> Weight {85		<SelfWeightOf<T>>::set_token_properties(amount)86	}8788	fn delete_token_properties(amount: u32) -> Weight {89		<SelfWeightOf<T>>::delete_token_properties(amount)90	}9192	fn set_property_permissions(amount: u32) -> Weight {93		<SelfWeightOf<T>>::set_property_permissions(amount)94	}9596	fn transfer() -> Weight {97		<SelfWeightOf<T>>::transfer()98	}99100	fn approve() -> Weight {101		<SelfWeightOf<T>>::approve()102	}103104	fn transfer_from() -> Weight {105		<SelfWeightOf<T>>::transfer_from()106	}107108	fn burn_from() -> Weight {109		<SelfWeightOf<T>>::burn_from()110	}111}112113fn map_create_data<T: Config>(114	data: up_data_structs::CreateItemData,115	to: &T::CrossAccountId,116) -> Result<CreateItemData<T>, DispatchError> {117	match data {118		up_data_structs::CreateItemData::NFT(data) => Ok(CreateItemData::<T> {119			properties: data.properties,120			owner: to.clone(),121		}),122		_ => fail!(<Error<T>>::NotNonfungibleDataUsedToMintFungibleCollectionToken),123	}124}125126impl<T: Config> CommonCollectionOperations<T> for NonfungibleHandle<T> {127	fn create_item(128		&self,129		sender: T::CrossAccountId,130		to: T::CrossAccountId,131		data: up_data_structs::CreateItemData,132		nesting_budget: &dyn Budget,133	) -> DispatchResultWithPostInfo {134		with_weight(135			<Pallet<T>>::create_item(136				self,137				&sender,138				map_create_data::<T>(data, &to)?,139				nesting_budget,140			),141			<CommonWeights<T>>::create_item(),142		)143	}144145	fn create_multiple_items(146		&self,147		sender: T::CrossAccountId,148		to: T::CrossAccountId,149		data: Vec<up_data_structs::CreateItemData>,150		nesting_budget: &dyn Budget,151	) -> DispatchResultWithPostInfo {152		let weight = <CommonWeights<T>>::create_multiple_items(&data);153		let data = data154			.into_iter()155			.map(|d| map_create_data::<T>(d, &to))156			.collect::<Result<Vec<_>, DispatchError>>()?;157158		with_weight(159			<Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),160			weight,161		)162	}163164	fn create_multiple_items_ex(165		&self,166		sender: <T>::CrossAccountId,167		data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,168		nesting_budget: &dyn Budget,169	) -> DispatchResultWithPostInfo {170		let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);171		let data = match data {172			up_data_structs::CreateItemExData::NFT(nft) => nft,173			_ => fail!(Error::<T>::NotNonfungibleDataUsedToMintFungibleCollectionToken),174		};175176		with_weight(177			<Pallet<T>>::create_multiple_items(self, &sender, data.into_inner(), nesting_budget),178			weight,179		)180	}181182	fn set_collection_properties(183		&self,184		sender: T::CrossAccountId,185		properties: Vec<Property>,186	) -> DispatchResultWithPostInfo {187		let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);188189		with_weight(190			<Pallet<T>>::set_collection_properties(self, &sender, properties),191			weight,192		)193	}194195	fn delete_collection_properties(196		&self,197		sender: &T::CrossAccountId,198		property_keys: Vec<PropertyKey>,199	) -> DispatchResultWithPostInfo {200		let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);201202		with_weight(203			<Pallet<T>>::delete_collection_properties(self, sender, property_keys),204			weight,205		)206	}207208	fn set_token_properties(209		&self,210		sender: T::CrossAccountId,211		token_id: TokenId,212		properties: Vec<Property>,213	) -> DispatchResultWithPostInfo {214		let weight = <CommonWeights<T>>::set_token_properties(properties.len() as u32);215216		with_weight(217			<Pallet<T>>::set_token_properties(self, &sender, token_id, properties),218			weight,219		)220	}221222	fn delete_token_properties(223		&self,224		sender: T::CrossAccountId,225		token_id: TokenId,226		property_keys: Vec<PropertyKey>,227	) -> DispatchResultWithPostInfo {228		let weight = <CommonWeights<T>>::delete_token_properties(property_keys.len() as u32);229230		with_weight(231			<Pallet<T>>::delete_token_properties(self, &sender, token_id, property_keys),232			weight,233		)234	}235236	fn set_property_permissions(237		&self,238		sender: &T::CrossAccountId,239		property_permissions: Vec<PropertyKeyPermission>,240	) -> DispatchResultWithPostInfo {241		let weight =242			<CommonWeights<T>>::set_property_permissions(property_permissions.len() as u32);243244		with_weight(245			<Pallet<T>>::set_property_permissions(self, sender, property_permissions),246			weight,247		)248	}249250	fn burn_item(251		&self,252		sender: T::CrossAccountId,253		token: TokenId,254		amount: u128,255	) -> DispatchResultWithPostInfo {256		ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);257		if amount == 1 {258			with_weight(259				<Pallet<T>>::burn(self, &sender, token),260				<CommonWeights<T>>::burn_item(),261			)262		} else {263			Ok(().into())264		}265	}266267	fn transfer(268		&self,269		from: T::CrossAccountId,270		to: T::CrossAccountId,271		token: TokenId,272		amount: u128,273		nesting_budget: &dyn Budget,274	) -> DispatchResultWithPostInfo {275		ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);276		if amount == 1 {277			with_weight(278				<Pallet<T>>::transfer(self, &from, &to, token, nesting_budget),279				<CommonWeights<T>>::transfer(),280			)281		} else {282			Ok(().into())283		}284	}285286	fn approve(287		&self,288		sender: T::CrossAccountId,289		spender: T::CrossAccountId,290		token: TokenId,291		amount: u128,292	) -> DispatchResultWithPostInfo {293		ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);294295		with_weight(296			if amount == 1 {297				<Pallet<T>>::set_allowance(self, &sender, token, Some(&spender))298			} else {299				<Pallet<T>>::set_allowance(self, &sender, token, None)300			},301			<CommonWeights<T>>::approve(),302		)303	}304305	fn transfer_from(306		&self,307		sender: T::CrossAccountId,308		from: T::CrossAccountId,309		to: T::CrossAccountId,310		token: TokenId,311		amount: u128,312		nesting_budget: &dyn Budget,313	) -> DispatchResultWithPostInfo {314		ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);315316		if amount == 1 {317			with_weight(318				<Pallet<T>>::transfer_from(self, &sender, &from, &to, token, nesting_budget),319				<CommonWeights<T>>::transfer_from(),320			)321		} else {322			Ok(().into())323		}324	}325326	fn burn_from(327		&self,328		sender: T::CrossAccountId,329		from: T::CrossAccountId,330		token: TokenId,331		amount: u128,332		nesting_budget: &dyn Budget,333	) -> DispatchResultWithPostInfo {334		ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);335336		if amount == 1 {337			with_weight(338				<Pallet<T>>::burn_from(self, &sender, &from, token, nesting_budget),339				<CommonWeights<T>>::burn_from(),340			)341		} else {342			Ok(().into())343		}344	}345346	fn check_nesting(347		&self,348		sender: T::CrossAccountId,349		from: (CollectionId, TokenId),350		under: TokenId,351		budget: &dyn Budget,352	) -> sp_runtime::DispatchResult {353		<Pallet<T>>::check_nesting(self, sender, from, under, budget)354	}355356	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {357		<Owned<T>>::iter_prefix((self.id, account))358			.map(|(id, _)| id)359			.collect()360	}361362	fn collection_tokens(&self) -> Vec<TokenId> {363		<TokenData<T>>::iter_prefix((self.id,))364			.map(|(id, _)| id)365			.collect()366	}367368	fn token_exists(&self, token: TokenId) -> bool {369		<Pallet<T>>::token_exists(self, token)370	}371372	fn last_token_id(&self) -> TokenId {373		TokenId(<TokensMinted<T>>::get(self.id))374	}375376	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {377		<TokenData<T>>::get((self.id, token)).map(|t| t.owner)378	}379380	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {381		<Pallet<T>>::token_properties((self.id, token_id))382			.get(key)383			.cloned()384	}385386	fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property> {387		let properties = <Pallet<T>>::token_properties((self.id, token_id));388389		keys.map(|keys| {390			keys.into_iter()391				.filter_map(|key| {392					properties.get(&key).map(|value| Property {393						key,394						value: value.clone(),395					})396				})397				.collect()398		})399		.unwrap_or_else(|| {400			properties401				.into_iter()402				.map(|(key, value)| Property {403					key: key.clone(),404					value: value.clone(),405				})406				.collect()407		})408	}409410	fn total_supply(&self) -> u32 {411		<Pallet<T>>::total_supply(self)412	}413414	fn account_balance(&self, account: T::CrossAccountId) -> u32 {415		<AccountBalance<T>>::get((self.id, account))416	}417418	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {419		if <TokenData<T>>::get((self.id, token))420			.map(|a| a.owner == account)421			.unwrap_or(false)422		{423			1424		} else {425			0426		}427	}428429	fn allowance(430		&self,431		sender: T::CrossAccountId,432		spender: T::CrossAccountId,433		token: TokenId,434	) -> u128 {435		if <TokenData<T>>::get((self.id, token))436			.map(|a| a.owner != sender)437			.unwrap_or(true)438		{439			0440		} else if <Allowance<T>>::get((self.id, token)) == Some(spender) {441			1442		} else {443			0444		}445	}446}
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};
@@ -77,6 +77,8 @@
 		NotNonfungibleDataUsedToMintFungibleCollectionToken,
 		/// Used amount > 1 with NFT
 		NonfungibleItemsHaveNoAmount,
+		/// Unable to burn NFT with children
+		CantBurnNftWithChildren,
 	}
 
 	#[pallet::config]
@@ -128,7 +130,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>,
@@ -283,6 +298,7 @@
 		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);
@@ -308,6 +324,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)?;
@@ -321,6 +341,11 @@
 		} else {
 			<AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);
 		}
+
+		if let Some(owner) = T::CrossTokenAddressMapping::address_to_token(&token_data.owner) {
+			Self::unnest(owner, (collection.id, token));
+		}
+
 		// =========
 
 		<Owned<T>>::remove((collection.id, &token_data.owner, token));
@@ -554,18 +579,13 @@
 			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>>::try_nest_if_sent_to_token(
+			from.clone(),
+			to,
+			collection.id,
+			token,
+			nesting_budget
+		)?;
 
 		// =========
 
@@ -654,17 +674,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,
+			)?;
 		}
 
 		// =========
@@ -681,6 +698,8 @@
 					},
 				);
 
+				<PalletStructure<T>>::nest_if_sent_to_token(&data.owner, collection.id, TokenId(token));
+
 				if let Err(e) = Self::set_token_properties(
 					collection,
 					sender,
@@ -928,6 +947,29 @@
 		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 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/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};
@@ -265,6 +264,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 +292,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 {
@@ -371,22 +372,17 @@
 		} else {
 			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>>::try_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 {
@@ -488,18 +484,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 +511,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(&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};
@@ -174,7 +175,7 @@
 				v if v == 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_dispatched(
+			under,
+			|d, parent_id| d.check_nesting(
+				from,
+				(collection_id, token_id),
+				parent_id,
+				nesting_budget
+			)
+		)
+	}
+
+	pub fn try_nest_if_sent_to_token(
+		from: T::CrossAccountId,
+		under: &T::CrossAccountId,
+		collection_id: CollectionId,
+		token_id: TokenId,
+		nesting_budget: &dyn Budget
+	) -> DispatchResult {
+		Self::try_dispatched(
+			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(
+		owner: &T::CrossAccountId,
+		collection_id: CollectionId,
+		token_id: TokenId
+	) {
+		Self::dispatched(
+			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::dispatched(
+			owner,
+			|d, parent_id| d.unnest(
+			parent_id,
+			(collection_id, token_id)
+			)
+		);
+	}
+
+	fn dispatched(
+		account: &T::CrossAccountId,
+		action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId)
+	) {
+		Self::try_dispatched(
+			account,
+			|d, id| {
+				action(d, id);
+				Ok(())
+			}
+		).unwrap();
+	}
+
+	fn try_dispatched(
+		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)
+	}
 }