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
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -237,7 +237,7 @@
 	fn check_nesting(
 		&self,
 		_sender: <T>::CrossAccountId,
-		_from: CollectionId,
+		_from: (CollectionId, TokenId),
 		_under: TokenId,
 		_budget: &dyn Budget,
 	) -> sp_runtime::DispatchResult {
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
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, BoundedVec};21use up_data_structs::{22	CollectionId, TokenId, CustomDataLimit, CreateItemExData, CreateRefungibleExData,23	budget::Budget,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(amount: u32) -> Weight {50		<SelfWeightOf<T>>::create_multiple_items(amount)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 transfer() -> Weight {70		max_weight_of!(71			transfer_normal(),72			transfer_creating(),73			transfer_removing(),74			transfer_creating_removing()75		)76	}7778	fn approve() -> Weight {79		<SelfWeightOf<T>>::approve()80	}8182	fn transfer_from() -> Weight {83		max_weight_of!(84			transfer_from_normal(),85			transfer_from_creating(),86			transfer_from_removing(),87			transfer_from_creating_removing()88		)89	}9091	fn burn_from() -> Weight {92		<SelfWeightOf<T>>::burn_from()93	}9495	fn set_variable_metadata(bytes: u32) -> Weight {96		<SelfWeightOf<T>>::set_variable_metadata(bytes)97	}98}99100fn map_create_data<T: Config>(101	data: up_data_structs::CreateItemData,102	to: &T::CrossAccountId,103) -> Result<CreateRefungibleExData<T::CrossAccountId>, DispatchError> {104	match data {105		up_data_structs::CreateItemData::ReFungible(data) => Ok(CreateRefungibleExData {106			const_data: data.const_data,107			variable_data: data.variable_data,108			users: {109				let mut out = BTreeMap::new();110				out.insert(to.clone(), data.pieces);111				out.try_into().expect("limit > 0")112			},113		}),114		_ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),115	}116}117118impl<T: Config> CommonCollectionOperations<T> for RefungibleHandle<T> {119	fn create_item(120		&self,121		sender: T::CrossAccountId,122		to: T::CrossAccountId,123		data: up_data_structs::CreateItemData,124		nesting_budget: &dyn Budget,125	) -> DispatchResultWithPostInfo {126		with_weight(127			<Pallet<T>>::create_item(128				self,129				&sender,130				map_create_data::<T>(data, &to)?,131				nesting_budget,132			),133			<CommonWeights<T>>::create_item(),134		)135	}136137	fn create_multiple_items(138		&self,139		sender: T::CrossAccountId,140		to: T::CrossAccountId,141		data: Vec<up_data_structs::CreateItemData>,142		nesting_budget: &dyn Budget,143	) -> DispatchResultWithPostInfo {144		let data = data145			.into_iter()146			.map(|d| map_create_data::<T>(d, &to))147			.collect::<Result<Vec<_>, DispatchError>>()?;148149		let amount = data.len();150		with_weight(151			<Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),152			<CommonWeights<T>>::create_multiple_items(amount as u32),153		)154	}155156	fn create_multiple_items_ex(157		&self,158		sender: <T>::CrossAccountId,159		data: CreateItemExData<T::CrossAccountId>,160		nesting_budget: &dyn Budget,161	) -> DispatchResultWithPostInfo {162		let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);163		let data = match data {164			CreateItemExData::RefungibleMultipleOwners(r) => vec![r],165			CreateItemExData::RefungibleMultipleItems(r)166				if r.iter().all(|i| i.users.len() == 1) =>167			{168				r.into_inner()169			}170			_ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),171		};172173		with_weight(174			<Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),175			weight,176		)177	}178179	fn burn_item(180		&self,181		sender: T::CrossAccountId,182		token: TokenId,183		amount: u128,184	) -> DispatchResultWithPostInfo {185		with_weight(186			<Pallet<T>>::burn(self, &sender, token, amount),187			<CommonWeights<T>>::burn_item(),188		)189	}190191	fn transfer(192		&self,193		from: T::CrossAccountId,194		to: T::CrossAccountId,195		token: TokenId,196		amount: u128,197		nesting_budget: &dyn Budget,198	) -> DispatchResultWithPostInfo {199		with_weight(200			<Pallet<T>>::transfer(self, &from, &to, token, amount, nesting_budget),201			<CommonWeights<T>>::transfer(),202		)203	}204205	fn approve(206		&self,207		sender: T::CrossAccountId,208		spender: T::CrossAccountId,209		token: TokenId,210		amount: u128,211	) -> DispatchResultWithPostInfo {212		with_weight(213			<Pallet<T>>::set_allowance(self, &sender, &spender, token, amount),214			<CommonWeights<T>>::approve(),215		)216	}217218	fn transfer_from(219		&self,220		sender: T::CrossAccountId,221		from: T::CrossAccountId,222		to: T::CrossAccountId,223		token: TokenId,224		amount: u128,225		nesting_budget: &dyn Budget,226	) -> DispatchResultWithPostInfo {227		with_weight(228			<Pallet<T>>::transfer_from(self, &sender, &from, &to, token, amount, nesting_budget),229			<CommonWeights<T>>::transfer_from(),230		)231	}232233	fn burn_from(234		&self,235		sender: T::CrossAccountId,236		from: T::CrossAccountId,237		token: TokenId,238		amount: u128,239		nesting_budget: &dyn Budget,240	) -> DispatchResultWithPostInfo {241		with_weight(242			<Pallet<T>>::burn_from(self, &sender, &from, token, amount, nesting_budget),243			<CommonWeights<T>>::burn_from(),244		)245	}246247	fn set_variable_metadata(248		&self,249		sender: T::CrossAccountId,250		token: TokenId,251		data: BoundedVec<u8, CustomDataLimit>,252	) -> DispatchResultWithPostInfo {253		let len = data.len();254		with_weight(255			<Pallet<T>>::set_variable_metadata(self, &sender, token, data),256			<CommonWeights<T>>::set_variable_metadata(len as u32),257		)258	}259260	fn check_nesting(261		&self,262		_sender: <T>::CrossAccountId,263		_from: CollectionId,264		_under: TokenId,265		_budget: &dyn Budget,266	) -> sp_runtime::DispatchResult {267		fail!(<Error<T>>::RefungibleDisallowsNesting)268	}269270	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {271		<Owned<T>>::iter_prefix((self.id, account))272			.map(|(id, _)| id)273			.collect()274	}275276	fn collection_tokens(&self) -> Vec<TokenId> {277		<TokenData<T>>::iter_prefix((self.id,))278			.map(|(id, _)| id)279			.collect()280	}281282	fn token_exists(&self, token: TokenId) -> bool {283		<Pallet<T>>::token_exists(self, token)284	}285286	fn last_token_id(&self) -> TokenId {287		TokenId(<TokensMinted<T>>::get(self.id))288	}289290	fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {291		None292	}293	fn const_metadata(&self, token: TokenId) -> Vec<u8> {294		<TokenData<T>>::get((self.id, token))295			.const_data296			.into_inner()297	}298	fn variable_metadata(&self, token: TokenId) -> Vec<u8> {299		<TokenData<T>>::get((self.id, token))300			.variable_data301			.into_inner()302	}303304	fn total_supply(&self) -> u32 {305		<Pallet<T>>::total_supply(self)306	}307308	fn account_balance(&self, account: T::CrossAccountId) -> u32 {309		<AccountBalance<T>>::get((self.id, account))310	}311312	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {313		<Balance<T>>::get((self.id, token, account))314	}315316	fn allowance(317		&self,318		sender: T::CrossAccountId,319		spender: T::CrossAccountId,320		token: TokenId,321	) -> u128 {322		<Allowance<T>>::get((self.id, token, sender, spender))323	}324}
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, BoundedVec};21use up_data_structs::{22	CollectionId, TokenId, CustomDataLimit, CreateItemExData, CreateRefungibleExData,23	budget::Budget,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(amount: u32) -> Weight {50		<SelfWeightOf<T>>::create_multiple_items(amount)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 transfer() -> Weight {70		max_weight_of!(71			transfer_normal(),72			transfer_creating(),73			transfer_removing(),74			transfer_creating_removing()75		)76	}7778	fn approve() -> Weight {79		<SelfWeightOf<T>>::approve()80	}8182	fn transfer_from() -> Weight {83		max_weight_of!(84			transfer_from_normal(),85			transfer_from_creating(),86			transfer_from_removing(),87			transfer_from_creating_removing()88		)89	}9091	fn burn_from() -> Weight {92		<SelfWeightOf<T>>::burn_from()93	}9495	fn set_variable_metadata(bytes: u32) -> Weight {96		<SelfWeightOf<T>>::set_variable_metadata(bytes)97	}98}99100fn map_create_data<T: Config>(101	data: up_data_structs::CreateItemData,102	to: &T::CrossAccountId,103) -> Result<CreateRefungibleExData<T::CrossAccountId>, DispatchError> {104	match data {105		up_data_structs::CreateItemData::ReFungible(data) => Ok(CreateRefungibleExData {106			const_data: data.const_data,107			variable_data: data.variable_data,108			users: {109				let mut out = BTreeMap::new();110				out.insert(to.clone(), data.pieces);111				out.try_into().expect("limit > 0")112			},113		}),114		_ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),115	}116}117118impl<T: Config> CommonCollectionOperations<T> for RefungibleHandle<T> {119	fn create_item(120		&self,121		sender: T::CrossAccountId,122		to: T::CrossAccountId,123		data: up_data_structs::CreateItemData,124		nesting_budget: &dyn Budget,125	) -> DispatchResultWithPostInfo {126		with_weight(127			<Pallet<T>>::create_item(128				self,129				&sender,130				map_create_data::<T>(data, &to)?,131				nesting_budget,132			),133			<CommonWeights<T>>::create_item(),134		)135	}136137	fn create_multiple_items(138		&self,139		sender: T::CrossAccountId,140		to: T::CrossAccountId,141		data: Vec<up_data_structs::CreateItemData>,142		nesting_budget: &dyn Budget,143	) -> DispatchResultWithPostInfo {144		let data = data145			.into_iter()146			.map(|d| map_create_data::<T>(d, &to))147			.collect::<Result<Vec<_>, DispatchError>>()?;148149		let amount = data.len();150		with_weight(151			<Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),152			<CommonWeights<T>>::create_multiple_items(amount as u32),153		)154	}155156	fn create_multiple_items_ex(157		&self,158		sender: <T>::CrossAccountId,159		data: CreateItemExData<T::CrossAccountId>,160		nesting_budget: &dyn Budget,161	) -> DispatchResultWithPostInfo {162		let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);163		let data = match data {164			CreateItemExData::RefungibleMultipleOwners(r) => vec![r],165			CreateItemExData::RefungibleMultipleItems(r)166				if r.iter().all(|i| i.users.len() == 1) =>167			{168				r.into_inner()169			}170			_ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),171		};172173		with_weight(174			<Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),175			weight,176		)177	}178179	fn burn_item(180		&self,181		sender: T::CrossAccountId,182		token: TokenId,183		amount: u128,184	) -> DispatchResultWithPostInfo {185		with_weight(186			<Pallet<T>>::burn(self, &sender, token, amount),187			<CommonWeights<T>>::burn_item(),188		)189	}190191	fn transfer(192		&self,193		from: T::CrossAccountId,194		to: T::CrossAccountId,195		token: TokenId,196		amount: u128,197		nesting_budget: &dyn Budget,198	) -> DispatchResultWithPostInfo {199		with_weight(200			<Pallet<T>>::transfer(self, &from, &to, token, amount, nesting_budget),201			<CommonWeights<T>>::transfer(),202		)203	}204205	fn approve(206		&self,207		sender: T::CrossAccountId,208		spender: T::CrossAccountId,209		token: TokenId,210		amount: u128,211	) -> DispatchResultWithPostInfo {212		with_weight(213			<Pallet<T>>::set_allowance(self, &sender, &spender, token, amount),214			<CommonWeights<T>>::approve(),215		)216	}217218	fn transfer_from(219		&self,220		sender: T::CrossAccountId,221		from: T::CrossAccountId,222		to: T::CrossAccountId,223		token: TokenId,224		amount: u128,225		nesting_budget: &dyn Budget,226	) -> DispatchResultWithPostInfo {227		with_weight(228			<Pallet<T>>::transfer_from(self, &sender, &from, &to, token, amount, nesting_budget),229			<CommonWeights<T>>::transfer_from(),230		)231	}232233	fn burn_from(234		&self,235		sender: T::CrossAccountId,236		from: T::CrossAccountId,237		token: TokenId,238		amount: u128,239		nesting_budget: &dyn Budget,240	) -> DispatchResultWithPostInfo {241		with_weight(242			<Pallet<T>>::burn_from(self, &sender, &from, token, amount, nesting_budget),243			<CommonWeights<T>>::burn_from(),244		)245	}246247	fn set_variable_metadata(248		&self,249		sender: T::CrossAccountId,250		token: TokenId,251		data: BoundedVec<u8, CustomDataLimit>,252	) -> DispatchResultWithPostInfo {253		let len = data.len();254		with_weight(255			<Pallet<T>>::set_variable_metadata(self, &sender, token, data),256			<CommonWeights<T>>::set_variable_metadata(len as u32),257		)258	}259260	fn check_nesting(261		&self,262		_sender: <T>::CrossAccountId,263		_from: (CollectionId, TokenId),264		_under: TokenId,265		_budget: &dyn Budget,266	) -> sp_runtime::DispatchResult {267		fail!(<Error<T>>::RefungibleDisallowsNesting)268	}269270	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {271		<Owned<T>>::iter_prefix((self.id, account))272			.map(|(id, _)| id)273			.collect()274	}275276	fn collection_tokens(&self) -> Vec<TokenId> {277		<TokenData<T>>::iter_prefix((self.id,))278			.map(|(id, _)| id)279			.collect()280	}281282	fn token_exists(&self, token: TokenId) -> bool {283		<Pallet<T>>::token_exists(self, token)284	}285286	fn last_token_id(&self) -> TokenId {287		TokenId(<TokensMinted<T>>::get(self.id))288	}289290	fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {291		None292	}293	fn const_metadata(&self, token: TokenId) -> Vec<u8> {294		<TokenData<T>>::get((self.id, token))295			.const_data296			.into_inner()297	}298	fn variable_metadata(&self, token: TokenId) -> Vec<u8> {299		<TokenData<T>>::get((self.id, token))300			.variable_data301			.into_inner()302	}303304	fn total_supply(&self) -> u32 {305		<Pallet<T>>::total_supply(self)306	}307308	fn account_balance(&self, account: T::CrossAccountId) -> u32 {309		<AccountBalance<T>>::get((self.id, account))310	}311312	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {313		<Balance<T>>::get((self.id, token, account))314	}315316	fn allowance(317		&self,318		sender: T::CrossAccountId,319		spender: T::CrossAccountId,320		token: TokenId,321	) -> u128 {322		<Allowance<T>>::get((self.id, token, sender, spender))323	}324}
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/);
+    });
+  });
+});