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

difftreelog

feat prevent ouroboros creation during nest

Yaroslav Bolyukin2022-04-19parent: #07a6969.patch.diff
in: master

11 files changed

modifiedclient/rpc/src/lib.rsdiffbeforeafterboth
--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -77,11 +77,7 @@
 	) -> Result<Vec<u8>>;
 
 	#[rpc(name = "unique_totalSupply")]
-	fn total_supply(
-		&self,
-		collection: CollectionId,
-		at: Option<BlockHash>,
-	) -> Result<u32>;
+	fn total_supply(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<u32>;
 	#[rpc(name = "unique_accountBalance")]
 	fn account_balance(
 		&self,
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -918,7 +918,7 @@
 	fn check_nesting(
 		&self,
 		sender: T::CrossAccountId,
-		from: CollectionId,
+		from: (CollectionId, TokenId),
 		under: TokenId,
 		budget: &dyn Budget,
 	) -> DispatchResult;
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
before · pallets/fungible/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, BoundedVec};20use up_data_structs::{TokenId, CollectionId, CreateItemExData, budget::Budget};21use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};22use sp_runtime::ArithmeticError;23use sp_std::{vec::Vec, vec};24use up_data_structs::CustomDataLimit;2526use crate::{27	Allowance, Balance, Config, Error, FungibleHandle, Pallet, SelfWeightOf, weights::WeightInfo,28};2930pub struct CommonWeights<T: Config>(PhantomData<T>);31impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {32	fn create_item() -> Weight {33		<SelfWeightOf<T>>::create_item()34	}3536	fn create_multiple_items(_amount: u32) -> Weight {37		Self::create_item()38	}3940	fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {41		match data {42			CreateItemExData::Fungible(f) => {43				<SelfWeightOf<T>>::create_multiple_items_ex(f.len() as u32)44			}45			_ => 0,46		}47	}4849	fn burn_item() -> Weight {50		<SelfWeightOf<T>>::burn_item()51	}5253	fn transfer() -> Weight {54		<SelfWeightOf<T>>::transfer()55	}5657	fn approve() -> Weight {58		<SelfWeightOf<T>>::approve()59	}6061	fn transfer_from() -> Weight {62		<SelfWeightOf<T>>::transfer_from()63	}6465	fn burn_from() -> Weight {66		<SelfWeightOf<T>>::burn_from()67	}6869	fn set_variable_metadata(_bytes: u32) -> Weight {70		// Error71		072	}73}7475impl<T: Config> CommonCollectionOperations<T> for FungibleHandle<T> {76	fn create_item(77		&self,78		sender: T::CrossAccountId,79		to: T::CrossAccountId,80		data: up_data_structs::CreateItemData,81		nesting_budget: &dyn Budget,82	) -> DispatchResultWithPostInfo {83		match data {84			up_data_structs::CreateItemData::Fungible(data) => with_weight(85				<Pallet<T>>::create_item(self, &sender, (to, data.value), nesting_budget),86				<CommonWeights<T>>::create_item(),87			),88			_ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),89		}90	}9192	fn create_multiple_items(93		&self,94		sender: T::CrossAccountId,95		to: T::CrossAccountId,96		data: Vec<up_data_structs::CreateItemData>,97		nesting_budget: &dyn Budget,98	) -> DispatchResultWithPostInfo {99		let mut sum: u128 = 0;100		for data in data {101			match data {102				up_data_structs::CreateItemData::Fungible(data) => {103					sum = sum104						.checked_add(data.value)105						.ok_or(ArithmeticError::Overflow)?;106				}107				_ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),108			}109		}110111		with_weight(112			<Pallet<T>>::create_item(self, &sender, (to, sum), nesting_budget),113			<CommonWeights<T>>::create_item(),114		)115	}116117	fn create_multiple_items_ex(118		&self,119		sender: <T>::CrossAccountId,120		data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,121		nesting_budget: &dyn Budget,122	) -> DispatchResultWithPostInfo {123		let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);124		let data = match data {125			up_data_structs::CreateItemExData::Fungible(f) => f,126			_ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),127		};128129		with_weight(130			<Pallet<T>>::create_multiple_items(self, &sender, data.into_inner(), nesting_budget),131			weight,132		)133	}134135	fn burn_item(136		&self,137		sender: T::CrossAccountId,138		token: TokenId,139		amount: u128,140	) -> DispatchResultWithPostInfo {141		ensure!(142			token == TokenId::default(),143			<Error<T>>::FungibleItemsHaveNoId144		);145146		with_weight(147			<Pallet<T>>::burn(self, &sender, amount),148			<CommonWeights<T>>::burn_item(),149		)150	}151152	fn transfer(153		&self,154		from: T::CrossAccountId,155		to: T::CrossAccountId,156		token: TokenId,157		amount: u128,158		nesting_budget: &dyn Budget,159	) -> DispatchResultWithPostInfo {160		ensure!(161			token == TokenId::default(),162			<Error<T>>::FungibleItemsHaveNoId163		);164165		with_weight(166			<Pallet<T>>::transfer(self, &from, &to, amount, nesting_budget),167			<CommonWeights<T>>::transfer(),168		)169	}170171	fn approve(172		&self,173		sender: T::CrossAccountId,174		spender: T::CrossAccountId,175		token: TokenId,176		amount: u128,177	) -> DispatchResultWithPostInfo {178		ensure!(179			token == TokenId::default(),180			<Error<T>>::FungibleItemsHaveNoId181		);182183		with_weight(184			<Pallet<T>>::set_allowance(self, &sender, &spender, amount),185			<CommonWeights<T>>::approve(),186		)187	}188189	fn transfer_from(190		&self,191		sender: T::CrossAccountId,192		from: T::CrossAccountId,193		to: T::CrossAccountId,194		token: TokenId,195		amount: u128,196		nesting_budget: &dyn Budget,197	) -> DispatchResultWithPostInfo {198		ensure!(199			token == TokenId::default(),200			<Error<T>>::FungibleItemsHaveNoId201		);202203		with_weight(204			<Pallet<T>>::transfer_from(self, &sender, &from, &to, amount, nesting_budget),205			<CommonWeights<T>>::transfer_from(),206		)207	}208209	fn burn_from(210		&self,211		sender: T::CrossAccountId,212		from: T::CrossAccountId,213		token: TokenId,214		amount: u128,215		nesting_budget: &dyn Budget,216	) -> DispatchResultWithPostInfo {217		ensure!(218			token == TokenId::default(),219			<Error<T>>::FungibleItemsHaveNoId220		);221222		with_weight(223			<Pallet<T>>::burn_from(self, &sender, &from, amount, nesting_budget),224			<CommonWeights<T>>::burn_from(),225		)226	}227228	fn set_variable_metadata(229		&self,230		_sender: T::CrossAccountId,231		_token: TokenId,232		_data: BoundedVec<u8, CustomDataLimit>,233	) -> DispatchResultWithPostInfo {234		fail!(<Error<T>>::FungibleItemsDontHaveData)235	}236237	fn check_nesting(238		&self,239		_sender: <T>::CrossAccountId,240		_from: CollectionId,241		_under: TokenId,242		_budget: &dyn Budget,243	) -> sp_runtime::DispatchResult {244		fail!(<Error<T>>::FungibleDisallowsNesting)245	}246247	fn collection_tokens(&self) -> Vec<TokenId> {248		vec![TokenId::default()]249	}250251	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {252		if <Balance<T>>::get((self.id, account)) != 0 {253			vec![TokenId::default()]254		} else {255			vec![]256		}257	}258259	fn token_exists(&self, token: TokenId) -> bool {260		token == TokenId::default()261	}262263	fn last_token_id(&self) -> TokenId {264		TokenId::default()265	}266267	fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {268		None269	}270	fn const_metadata(&self, _token: TokenId) -> Vec<u8> {271		Vec::new()272	}273	fn variable_metadata(&self, _token: TokenId) -> Vec<u8> {274		Vec::new()275	}276277	fn total_supply(&self) -> u32 {278		1279	}280281	fn account_balance(&self, account: T::CrossAccountId) -> u32 {282		if <Balance<T>>::get((self.id, account)) != 0 {283			1284		} else {285			0286		}287	}288289	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {290		if token != TokenId::default() {291			return 0;292		}293		<Balance<T>>::get((self.id, account))294	}295296	fn allowance(297		&self,298		sender: T::CrossAccountId,299		spender: T::CrossAccountId,300		token: TokenId,301	) -> u128 {302		if token != TokenId::default() {303			return 0;304		}305		<Allowance<T>>::get((self.id, sender, spender))306	}307}
after · pallets/fungible/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, BoundedVec};20use up_data_structs::{TokenId, CollectionId, CreateItemExData, budget::Budget};21use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};22use sp_runtime::ArithmeticError;23use sp_std::{vec::Vec, vec};24use up_data_structs::CustomDataLimit;2526use crate::{27	Allowance, Balance, Config, Error, FungibleHandle, Pallet, SelfWeightOf, weights::WeightInfo,28};2930pub struct CommonWeights<T: Config>(PhantomData<T>);31impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {32	fn create_item() -> Weight {33		<SelfWeightOf<T>>::create_item()34	}3536	fn create_multiple_items(_amount: u32) -> Weight {37		Self::create_item()38	}3940	fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {41		match data {42			CreateItemExData::Fungible(f) => {43				<SelfWeightOf<T>>::create_multiple_items_ex(f.len() as u32)44			}45			_ => 0,46		}47	}4849	fn burn_item() -> Weight {50		<SelfWeightOf<T>>::burn_item()51	}5253	fn transfer() -> Weight {54		<SelfWeightOf<T>>::transfer()55	}5657	fn approve() -> Weight {58		<SelfWeightOf<T>>::approve()59	}6061	fn transfer_from() -> Weight {62		<SelfWeightOf<T>>::transfer_from()63	}6465	fn burn_from() -> Weight {66		<SelfWeightOf<T>>::burn_from()67	}6869	fn set_variable_metadata(_bytes: u32) -> Weight {70		// Error71		072	}73}7475impl<T: Config> CommonCollectionOperations<T> for FungibleHandle<T> {76	fn create_item(77		&self,78		sender: T::CrossAccountId,79		to: T::CrossAccountId,80		data: up_data_structs::CreateItemData,81		nesting_budget: &dyn Budget,82	) -> DispatchResultWithPostInfo {83		match data {84			up_data_structs::CreateItemData::Fungible(data) => with_weight(85				<Pallet<T>>::create_item(self, &sender, (to, data.value), nesting_budget),86				<CommonWeights<T>>::create_item(),87			),88			_ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),89		}90	}9192	fn create_multiple_items(93		&self,94		sender: T::CrossAccountId,95		to: T::CrossAccountId,96		data: Vec<up_data_structs::CreateItemData>,97		nesting_budget: &dyn Budget,98	) -> DispatchResultWithPostInfo {99		let mut sum: u128 = 0;100		for data in data {101			match data {102				up_data_structs::CreateItemData::Fungible(data) => {103					sum = sum104						.checked_add(data.value)105						.ok_or(ArithmeticError::Overflow)?;106				}107				_ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),108			}109		}110111		with_weight(112			<Pallet<T>>::create_item(self, &sender, (to, sum), nesting_budget),113			<CommonWeights<T>>::create_item(),114		)115	}116117	fn create_multiple_items_ex(118		&self,119		sender: <T>::CrossAccountId,120		data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,121		nesting_budget: &dyn Budget,122	) -> DispatchResultWithPostInfo {123		let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);124		let data = match data {125			up_data_structs::CreateItemExData::Fungible(f) => f,126			_ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),127		};128129		with_weight(130			<Pallet<T>>::create_multiple_items(self, &sender, data.into_inner(), nesting_budget),131			weight,132		)133	}134135	fn burn_item(136		&self,137		sender: T::CrossAccountId,138		token: TokenId,139		amount: u128,140	) -> DispatchResultWithPostInfo {141		ensure!(142			token == TokenId::default(),143			<Error<T>>::FungibleItemsHaveNoId144		);145146		with_weight(147			<Pallet<T>>::burn(self, &sender, amount),148			<CommonWeights<T>>::burn_item(),149		)150	}151152	fn transfer(153		&self,154		from: T::CrossAccountId,155		to: T::CrossAccountId,156		token: TokenId,157		amount: u128,158		nesting_budget: &dyn Budget,159	) -> DispatchResultWithPostInfo {160		ensure!(161			token == TokenId::default(),162			<Error<T>>::FungibleItemsHaveNoId163		);164165		with_weight(166			<Pallet<T>>::transfer(self, &from, &to, amount, nesting_budget),167			<CommonWeights<T>>::transfer(),168		)169	}170171	fn approve(172		&self,173		sender: T::CrossAccountId,174		spender: T::CrossAccountId,175		token: TokenId,176		amount: u128,177	) -> DispatchResultWithPostInfo {178		ensure!(179			token == TokenId::default(),180			<Error<T>>::FungibleItemsHaveNoId181		);182183		with_weight(184			<Pallet<T>>::set_allowance(self, &sender, &spender, amount),185			<CommonWeights<T>>::approve(),186		)187	}188189	fn transfer_from(190		&self,191		sender: T::CrossAccountId,192		from: T::CrossAccountId,193		to: T::CrossAccountId,194		token: TokenId,195		amount: u128,196		nesting_budget: &dyn Budget,197	) -> DispatchResultWithPostInfo {198		ensure!(199			token == TokenId::default(),200			<Error<T>>::FungibleItemsHaveNoId201		);202203		with_weight(204			<Pallet<T>>::transfer_from(self, &sender, &from, &to, amount, nesting_budget),205			<CommonWeights<T>>::transfer_from(),206		)207	}208209	fn burn_from(210		&self,211		sender: T::CrossAccountId,212		from: T::CrossAccountId,213		token: TokenId,214		amount: u128,215		nesting_budget: &dyn Budget,216	) -> DispatchResultWithPostInfo {217		ensure!(218			token == TokenId::default(),219			<Error<T>>::FungibleItemsHaveNoId220		);221222		with_weight(223			<Pallet<T>>::burn_from(self, &sender, &from, amount, nesting_budget),224			<CommonWeights<T>>::burn_from(),225		)226	}227228	fn set_variable_metadata(229		&self,230		_sender: T::CrossAccountId,231		_token: TokenId,232		_data: BoundedVec<u8, CustomDataLimit>,233	) -> DispatchResultWithPostInfo {234		fail!(<Error<T>>::FungibleItemsDontHaveData)235	}236237	fn check_nesting(238		&self,239		_sender: <T>::CrossAccountId,240		_from: (CollectionId, TokenId),241		_under: TokenId,242		_budget: &dyn Budget,243	) -> sp_runtime::DispatchResult {244		fail!(<Error<T>>::FungibleDisallowsNesting)245	}246247	fn collection_tokens(&self) -> Vec<TokenId> {248		vec![TokenId::default()]249	}250251	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {252		if <Balance<T>>::get((self.id, account)) != 0 {253			vec![TokenId::default()]254		} else {255			vec![]256		}257	}258259	fn token_exists(&self, token: TokenId) -> bool {260		token == TokenId::default()261	}262263	fn last_token_id(&self) -> TokenId {264		TokenId::default()265	}266267	fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {268		None269	}270	fn const_metadata(&self, _token: TokenId) -> Vec<u8> {271		Vec::new()272	}273	fn variable_metadata(&self, _token: TokenId) -> Vec<u8> {274		Vec::new()275	}276277	fn total_supply(&self) -> u32 {278		1279	}280281	fn account_balance(&self, account: T::CrossAccountId) -> u32 {282		if <Balance<T>>::get((self.id, account)) != 0 {283			1284		} else {285			0286		}287	}288289	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {290		if token != TokenId::default() {291			return 0;292		}293		<Balance<T>>::get((self.id, account))294	}295296	fn allowance(297		&self,298		sender: T::CrossAccountId,299		spender: T::CrossAccountId,300		token: TokenId,301	) -> u128 {302		if token != TokenId::default() {303			return 0;304		}305		<Allowance<T>>::get((self.id, sender, spender))306	}307}
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -224,7 +224,12 @@
 			let dispatch = T::CollectionDispatch::dispatch(handle);
 			let dispatch = dispatch.as_dyn();
 
-			dispatch.check_nesting(from.clone(), collection.id, target.1, nesting_budget)?;
+			dispatch.check_nesting(
+				from.clone(),
+				(collection.id, TokenId::default()),
+				target.1,
+				nesting_budget,
+			)?;
 		}
 
 		// =========
@@ -293,7 +298,12 @@
 				let dispatch = T::CollectionDispatch::dispatch(handle);
 				let dispatch = dispatch.as_dyn();
 
-				dispatch.check_nesting(sender.clone(), collection.id, target.1, nesting_budget)?;
+				dispatch.check_nesting(
+					sender.clone(),
+					(collection.id, TokenId::default()),
+					target.1,
+					nesting_budget,
+				)?;
 			}
 		}
 
@@ -386,10 +396,11 @@
 		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {
 			// TODO: should collection owner be allowed to perform this transfer?
 			ensure!(
-				<PalletStructure<T>>::indirectly_owned(
+				<PalletStructure<T>>::check_indirectly_owned(
 					spender.clone(),
 					source.0,
 					source.1,
+					None,
 					nesting_budget
 				)?,
 				<CommonError<T>>::ApprovedValueTooLow,
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -251,7 +251,7 @@
 	fn check_nesting(
 		&self,
 		sender: T::CrossAccountId,
-		from: CollectionId,
+		from: (CollectionId, TokenId),
 		under: TokenId,
 		budget: &dyn Budget,
 	) -> sp_runtime::DispatchResult {
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -296,7 +296,12 @@
 			let dispatch = T::CollectionDispatch::dispatch(handle);
 			let dispatch = dispatch.as_dyn();
 
-			dispatch.check_nesting(from.clone(), collection.id, target.1, nesting_budget)?;
+			dispatch.check_nesting(
+				from.clone(),
+				(collection.id, token),
+				target.1,
+				nesting_budget,
+			)?;
 		}
 
 		// =========
@@ -381,13 +386,18 @@
 			);
 		}
 
-		for (to, _) in balances.iter() {
-			if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {
+		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, target.1, nesting_budget)?;
+				dispatch.check_nesting(
+					sender.clone(),
+					(collection.id, token),
+					target.1,
+					nesting_budget,
+				)?;
 			}
 		}
 
@@ -535,10 +545,11 @@
 		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {
 			// TODO: should collection owner be allowed to perform this transfer?
 			ensure!(
-				<PalletStructure<T>>::indirectly_owned(
+				<PalletStructure<T>>::check_indirectly_owned(
 					spender.clone(),
 					source.0,
 					source.1,
+					None,
 					nesting_budget
 				)?,
 				<CommonError<T>>::ApprovedValueTooLow,
@@ -610,31 +621,40 @@
 	pub fn check_nesting(
 		handle: &NonfungibleHandle<T>,
 		sender: T::CrossAccountId,
-		from: CollectionId,
+		from: (CollectionId, TokenId),
 		under: TokenId,
 		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
 		fn ensure_sender_allowed<T: Config>(
 			collection: CollectionId,
 			token: TokenId,
+			for_nest: (CollectionId, TokenId),
 			sender: T::CrossAccountId,
 			budget: &dyn Budget,
 		) -> DispatchResult {
 			ensure!(
-				<PalletStructure<T>>::indirectly_owned(sender, collection, token, budget)?,
+				<PalletStructure<T>>::check_indirectly_owned(
+					sender,
+					collection,
+					token,
+					Some(for_nest),
+					budget
+				)?,
 				<CommonError<T>>::OnlyOwnerAllowedToNest,
 			);
 			Ok(())
 		}
 		match handle.limits.nesting_rule() {
 			NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),
-			NestingRule::Owner => ensure_sender_allowed::<T>(handle.id, under, sender, nesting_budget)?,
+			NestingRule::Owner => {
+				ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?
+			}
 			NestingRule::OwnerRestricted(whitelist) => {
 				ensure!(
-					whitelist.contains(&from),
+					whitelist.contains(&from.0),
 					<CommonError<T>>::SourceCollectionIsNotAllowedToNest
 				);
-				ensure_sender_allowed::<T>(handle.id, under, sender, nesting_budget)?
+				ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?
 			}
 		}
 		Ok(())
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -260,7 +260,7 @@
 	fn check_nesting(
 		&self,
 		_sender: <T>::CrossAccountId,
-		_from: CollectionId,
+		_from: (CollectionId, TokenId),
 		_under: TokenId,
 		_budget: &dyn Budget,
 	) -> sp_runtime::DispatchResult {
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -352,7 +352,12 @@
 			let dispatch = T::CollectionDispatch::dispatch(handle);
 			let dispatch = dispatch.as_dyn();
 
-			dispatch.check_nesting(from.clone(), collection.id, target.1, nesting_budget)?;
+			dispatch.check_nesting(
+				from.clone(),
+				(collection.id, token),
+				target.1,
+				nesting_budget,
+			)?;
 		}
 
 		// =========
@@ -455,7 +460,8 @@
 			}
 		}
 
-		for token in data.iter() {
+		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)?;
@@ -464,7 +470,7 @@
 
 					dispatch.check_nesting(
 						sender.clone(),
-						collection.id,
+						(collection.id, token_id),
 						target.1,
 						nesting_budget,
 					)?;
@@ -575,10 +581,11 @@
 		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {
 			// TODO: should collection owner be allowed to perform this transfer?
 			ensure!(
-				<PalletStructure<T>>::indirectly_owned(
+				<PalletStructure<T>>::check_indirectly_owned(
 					spender.clone(),
 					source.0,
 					source.1,
+					None,
 					nesting_budget
 				)?,
 				<CommonError<T>>::ApprovedValueTooLow,
modifiedpallets/structure/src/lib.rsdiffbeforeafterboth
--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -71,7 +71,7 @@
 #[derive(PartialEq)]
 pub enum Parent<CrossAccountId> {
 	/// Token owned by normal account
-	Normal(CrossAccountId),
+	User(CrossAccountId),
 	/// Passed token not found
 	TokenNotFound,
 	/// Token owner is another token (target token still may not exist)
@@ -94,7 +94,7 @@
 		Ok(match handle.token_owner(token) {
 			Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {
 				Some((collection, token)) => Parent::Token(collection, token),
-				None => Parent::Normal(owner),
+				None => Parent::User(owner),
 			},
 			None => Parent::TokenNotFound,
 		})
@@ -137,29 +137,46 @@
 	) -> Result<T::CrossAccountId, DispatchError> {
 		let owner = Self::parent_chain(collection, token)
 			.take_while(|_| budget.consume())
-			.find(|p| matches!(p, Ok(Parent::Normal(_) | Parent::TokenNotFound)))
+			.find(|p| matches!(p, Ok(Parent::User(_) | Parent::TokenNotFound)))
 			.ok_or(<Error<T>>::DepthLimit)??;
 
 		Ok(match owner {
-			Parent::Normal(v) => v,
+			Parent::User(v) => v,
 			_ => fail!(<Error<T>>::TokenNotFound),
 		})
 	}
 
 	/// Check if token indirectly owned by specified user
-	pub fn indirectly_owned(
+	pub fn check_indirectly_owned(
 		user: T::CrossAccountId,
 		collection: CollectionId,
 		token: TokenId,
+		for_nest: Option<(CollectionId, TokenId)>,
 		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::Normal(user),
+			None => Parent::User(user),
 		};
 
-		Ok(Self::parent_chain(collection, token)
-			.take_while(|_| budget.consume())
-			.any(|parent| Ok(&target_parent) == parent.as_ref()))
+		// Tried to nest token in itself
+		if Some((collection, token)) == for_nest {
+			return Err(<Error<T>>::OuroborosDetected.into());
+		}
+
+		for parent in Self::parent_chain(collection, token).take_while(|_| budget.consume()) {
+			match parent? {
+				// Tried to nest token in chain, which has this token as one of parents
+				Parent::Token(collection, token) if Some((collection, token)) == for_nest => {
+					return Err(<Error<T>>::OuroborosDetected.into())
+				}
+				// Found needed parent, token is indirecty owned
+				v if v == target_parent => return Ok(true),
+				Parent::TokenNotFound => return Ok(false),
+				_ => {}
+			}
+		}
+
+		Err(<Error<T>>::DepthLimit.into())
 	}
 }
modifiedtests/src/eth/util/helpers.tsdiffbeforeafterboth
--- a/tests/src/eth/util/helpers.ts
+++ b/tests/src/eth/util/helpers.ts
@@ -23,7 +23,7 @@
 import usingApi, {submitTransactionAsync} from '../../substrate/substrate-api';
 import {IKeyringPair} from '@polkadot/types/types';
 import {expect} from 'chai';
-import {getGenericResult, UNIQUE} from '../../util/helpers';
+import {CrossAccountId, getGenericResult, UNIQUE} from '../../util/helpers';
 import * as solc from 'solc';
 import config from '../../config';
 import privateKey from '../../substrate/privateKey';
@@ -80,6 +80,11 @@
   ]);
   return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));
 }
+export function tokenIdToCross(collection: number, token: number): CrossAccountId {
+  return {
+    Ethereum: tokenIdToAddress(collection, token),
+  };
+}
 
 export function createEthAccount(web3: Web3) {
   const account = web3.eth.accounts.create();
addedtests/src/nesting/graphs.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/nesting/graphs.test.ts
@@ -0,0 +1,51 @@
+import {ApiPromise} from '@polkadot/api';
+import {IKeyringPair} from '@polkadot/types/types';
+import {expect} from 'chai';
+import {tokenIdToCross} from '../eth/util/helpers';
+import privateKey from '../substrate/privateKey';
+import usingApi, {executeTransaction} from '../substrate/substrate-api';
+import {getCreateCollectionResult, transferExpectSuccess} from '../util/helpers';
+
+/**
+ * ```dot
+ * 4 -> 3 -> 2 -> 1
+ * 7 -> 6 -> 5 -> 2
+ * 8 -> 5
+ * ```
+ */
+async function buildComplexObjectGraph(api: ApiPromise, sender: IKeyringPair): Promise<number> {
+  const events = await executeTransaction(api, sender, api.tx.unique.createCollectionEx({mode: 'NFT'}));
+  const {collectionId} = getCreateCollectionResult(events);
+
+  await executeTransaction(api, sender, api.tx.unique.createMultipleItemsEx(collectionId, {NFT: Array(8).fill({owner: {Substrate: sender.address}})}));
+
+  await transferExpectSuccess(collectionId, 8, sender, tokenIdToCross(collectionId, 5));
+
+  await transferExpectSuccess(collectionId, 7, sender, tokenIdToCross(collectionId, 6));
+  await transferExpectSuccess(collectionId, 6, sender, tokenIdToCross(collectionId, 5));
+  await transferExpectSuccess(collectionId, 5, sender, tokenIdToCross(collectionId, 2));
+
+  await transferExpectSuccess(collectionId, 4, sender, tokenIdToCross(collectionId, 3));
+  await transferExpectSuccess(collectionId, 3, sender, tokenIdToCross(collectionId, 2));
+  await transferExpectSuccess(collectionId, 2, sender, tokenIdToCross(collectionId, 1));
+
+  return collectionId;
+}
+
+describe('graphs', () => {
+  it('ouroboros can\'t be created in graph', async () => {
+    await usingApi(async api => {
+      const alice = privateKey('//Alice');
+      const collection = await buildComplexObjectGraph(api, alice);
+
+      // to self
+      await expect(executeTransaction(api, alice, api.tx.unique.transfer(tokenIdToCross(collection, 1), collection, 1, 1)))
+        .to.be.rejectedWith(/structure\.OuroborosDetected/);
+      // to nested part of graph
+      await expect(executeTransaction(api, alice, api.tx.unique.transfer(tokenIdToCross(collection, 5), collection, 1, 1)))
+        .to.be.rejectedWith(/structure\.OuroborosDetected/);
+      await expect(executeTransaction(api, alice, api.tx.unique.transfer(tokenIdToCross(collection, 8), collection, 2, 1)))
+        .to.be.rejectedWith(/structure\.OuroborosDetected/);
+    });
+  });
+});