git.delta.rocks / unique-network / refs/commits / 24d3f67bfdff

difftreelog

Merge pull request #848 from UniqueNetwork/fix/find-parent

Yaroslav Bolyukin2023-01-19parents: #030bc0d #05c459d.patch.diff
in: master

15 files changed

modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -28,8 +28,8 @@
 use sp_std::{vec, vec::Vec};
 use sp_core::U256;
 use up_data_structs::{
-	AccessMode, CollectionMode, CollectionPermissions, OwnerRestrictedSet, Property,
-	SponsoringRateLimit, SponsorshipState,
+	CollectionMode, CollectionPermissions, OwnerRestrictedSet, Property, SponsoringRateLimit,
+	SponsorshipState,
 };
 
 use crate::{
modifiedpallets/common/src/eth.rsdiffbeforeafterboth
--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -80,10 +80,7 @@
 		if cross_account_id.is_canonical_substrate() {
 			Self::from_sub::<T>(cross_account_id.as_sub())
 		} else {
-			Self {
-				eth: *cross_account_id.as_eth(),
-				sub: Default::default(),
-			}
+			Self::from_eth(*cross_account_id.as_eth())
 		}
 	}
 	/// Creates [`CrossAddress`] from Substrate account.
@@ -97,6 +94,13 @@
 			sub: U256::from_big_endian(account_id.as_ref()),
 		}
 	}
+	/// Creates [`CrossAddress`] from Ethereum account.
+	pub fn from_eth(address: Address) -> Self {
+		Self {
+			eth: address,
+			sub: Default::default(),
+		}
+	}
 	/// Converts [`CrossAddress`] to `CrossAccountId`.
 	pub fn into_sub_cross_account<T>(&self) -> evm_coder::execution::Result<T::CrossAccountId>
 	where
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -100,6 +100,7 @@
 	PropertyValue,
 	PropertyPermission,
 	PropertiesError,
+	TokenOwnerError,
 	PropertyKeyPermission,
 	TokenData,
 	TrySetProperty,
@@ -2134,7 +2135,7 @@
 	/// Get the owner of the token.
 	///
 	/// * `token` - The token for which you need to find out the owner.
-	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;
+	fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;
 
 	/// Returns 10 tokens owners in no particular order.
 	///
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
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, traits::Get};20use up_data_structs::{21	TokenId, CollectionId, CreateItemExData, budget::Budget, CreateItemData, TokenOwnerError,22};23use pallet_common::{24	CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,25	weights::WeightInfo as _,26};27use pallet_structure::Error as StructureError;28use sp_runtime::ArithmeticError;29use sp_std::{vec::Vec, vec};30use up_data_structs::{Property, PropertyKey, PropertyValue, PropertyKeyPermission};3132use crate::{33	Allowance, TotalSupply, Balance, Config, Error, FungibleHandle, Pallet, SelfWeightOf,34	weights::WeightInfo,35};3637pub struct CommonWeights<T: Config>(PhantomData<T>);38impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {39	fn create_item() -> Weight {40		<SelfWeightOf<T>>::create_item()41	}4243	fn create_multiple_items(_data: &[CreateItemData]) -> Weight {44		// All items minted for the same user, so it works same as create_item45		Self::create_item()46	}4748	fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {49		match data {50			CreateItemExData::Fungible(f) => {51				<SelfWeightOf<T>>::create_multiple_items_ex(f.len() as u32)52			}53			_ => Weight::zero(),54		}55	}5657	fn burn_item() -> Weight {58		<SelfWeightOf<T>>::burn_item()59	}6061	fn set_collection_properties(amount: u32) -> Weight {62		<pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)63	}6465	fn delete_collection_properties(amount: u32) -> Weight {66		<pallet_common::SelfWeightOf<T>>::delete_collection_properties(amount)67	}6869	fn set_token_properties(_amount: u32) -> Weight {70		// Error71		Weight::zero()72	}7374	fn delete_token_properties(_amount: u32) -> Weight {75		// Error76		Weight::zero()77	}7879	fn set_token_property_permissions(_amount: u32) -> Weight {80		// Error81		Weight::zero()82	}8384	fn transfer() -> Weight {85		<SelfWeightOf<T>>::transfer()86	}8788	fn approve() -> Weight {89		<SelfWeightOf<T>>::approve()90	}9192	fn approve_from() -> Weight {93		<SelfWeightOf<T>>::approve_from()94	}9596	fn transfer_from() -> Weight {97		<SelfWeightOf<T>>::transfer_from()98	}99100	fn burn_from() -> Weight {101		<SelfWeightOf<T>>::burn_from()102	}103104	fn burn_recursively_self_raw() -> Weight {105		// Read to get total balance106		Self::burn_item() + T::DbWeight::get().reads(1)107	}108109	fn burn_recursively_breadth_raw(_amount: u32) -> Weight {110		// Fungible tokens can't have children111		Weight::zero()112	}113114	fn token_owner() -> Weight {115		Weight::zero()116	}117118	fn set_allowance_for_all() -> Weight {119		Weight::zero()120	}121122	fn force_repair_item() -> Weight {123		Weight::zero()124	}125}126127/// Implementation of `CommonCollectionOperations` for `FungibleHandle`. It wraps FungibleHandle Pallete128/// methods and adds weight info.129impl<T: Config> CommonCollectionOperations<T> for FungibleHandle<T> {130	fn create_item(131		&self,132		sender: T::CrossAccountId,133		to: T::CrossAccountId,134		data: up_data_structs::CreateItemData,135		nesting_budget: &dyn Budget,136	) -> DispatchResultWithPostInfo {137		match data {138			up_data_structs::CreateItemData::Fungible(data) => with_weight(139				<Pallet<T>>::create_item(self, &sender, (to, data.value), nesting_budget),140				<CommonWeights<T>>::create_item(),141			),142			_ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),143		}144	}145146	fn create_multiple_items(147		&self,148		sender: T::CrossAccountId,149		to: T::CrossAccountId,150		data: Vec<up_data_structs::CreateItemData>,151		nesting_budget: &dyn Budget,152	) -> DispatchResultWithPostInfo {153		let mut sum: u128 = 0;154		for data in data {155			match data {156				up_data_structs::CreateItemData::Fungible(data) => {157					sum = sum158						.checked_add(data.value)159						.ok_or(ArithmeticError::Overflow)?;160				}161				_ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),162			}163		}164165		with_weight(166			<Pallet<T>>::create_item(self, &sender, (to, sum), nesting_budget),167			<CommonWeights<T>>::create_item(),168		)169	}170171	fn create_multiple_items_ex(172		&self,173		sender: <T>::CrossAccountId,174		data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,175		nesting_budget: &dyn Budget,176	) -> DispatchResultWithPostInfo {177		let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);178		let data = match data {179			up_data_structs::CreateItemExData::Fungible(f) => f,180			_ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),181		};182183		with_weight(184			<Pallet<T>>::create_multiple_items(self, &sender, data.into_inner(), nesting_budget),185			weight,186		)187	}188189	fn burn_item(190		&self,191		sender: T::CrossAccountId,192		token: TokenId,193		amount: u128,194	) -> DispatchResultWithPostInfo {195		ensure!(196			token == TokenId::default(),197			<Error<T>>::FungibleItemsHaveNoId198		);199200		with_weight(201			<Pallet<T>>::burn(self, &sender, amount),202			<CommonWeights<T>>::burn_item(),203		)204	}205206	fn burn_item_recursively(207		&self,208		sender: T::CrossAccountId,209		token: TokenId,210		self_budget: &dyn Budget,211		_breadth_budget: &dyn Budget,212	) -> DispatchResultWithPostInfo {213		// Should not happen?214		ensure!(215			token == TokenId::default(),216			<Error<T>>::FungibleItemsHaveNoId217		);218		ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);219220		with_weight(221			<Pallet<T>>::burn(self, &sender, <Balance<T>>::get((self.id, &sender))),222			<CommonWeights<T>>::burn_recursively_self_raw(),223		)224	}225226	fn transfer(227		&self,228		from: T::CrossAccountId,229		to: T::CrossAccountId,230		token: TokenId,231		amount: u128,232		nesting_budget: &dyn Budget,233	) -> DispatchResultWithPostInfo {234		ensure!(235			token == TokenId::default(),236			<Error<T>>::FungibleItemsHaveNoId237		);238239		with_weight(240			<Pallet<T>>::transfer(self, &from, &to, amount, nesting_budget),241			<CommonWeights<T>>::transfer(),242		)243	}244245	fn approve(246		&self,247		sender: T::CrossAccountId,248		spender: T::CrossAccountId,249		token: TokenId,250		amount: u128,251	) -> DispatchResultWithPostInfo {252		ensure!(253			token == TokenId::default(),254			<Error<T>>::FungibleItemsHaveNoId255		);256257		with_weight(258			<Pallet<T>>::set_allowance(self, &sender, &spender, amount),259			<CommonWeights<T>>::approve(),260		)261	}262263	fn approve_from(264		&self,265		sender: T::CrossAccountId,266		from: T::CrossAccountId,267		to: T::CrossAccountId,268		token: TokenId,269		amount: u128,270	) -> DispatchResultWithPostInfo {271		ensure!(272			token == TokenId::default(),273			<Error<T>>::FungibleItemsHaveNoId274		);275276		with_weight(277			<Pallet<T>>::set_allowance_from(self, &sender, &from, &to, amount),278			<CommonWeights<T>>::approve_from(),279		)280	}281282	fn transfer_from(283		&self,284		sender: T::CrossAccountId,285		from: T::CrossAccountId,286		to: T::CrossAccountId,287		token: TokenId,288		amount: u128,289		nesting_budget: &dyn Budget,290	) -> DispatchResultWithPostInfo {291		ensure!(292			token == TokenId::default(),293			<Error<T>>::FungibleItemsHaveNoId294		);295296		with_weight(297			<Pallet<T>>::transfer_from(self, &sender, &from, &to, amount, nesting_budget),298			<CommonWeights<T>>::transfer_from(),299		)300	}301302	fn burn_from(303		&self,304		sender: T::CrossAccountId,305		from: T::CrossAccountId,306		token: TokenId,307		amount: u128,308		nesting_budget: &dyn Budget,309	) -> DispatchResultWithPostInfo {310		ensure!(311			token == TokenId::default(),312			<Error<T>>::FungibleItemsHaveNoId313		);314315		with_weight(316			<Pallet<T>>::burn_from(self, &sender, &from, amount, nesting_budget),317			<CommonWeights<T>>::burn_from(),318		)319	}320321	fn set_collection_properties(322		&self,323		sender: T::CrossAccountId,324		properties: Vec<Property>,325	) -> DispatchResultWithPostInfo {326		let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);327328		with_weight(329			<Pallet<T>>::set_collection_properties(self, &sender, properties),330			weight,331		)332	}333334	fn delete_collection_properties(335		&self,336		sender: &T::CrossAccountId,337		property_keys: Vec<PropertyKey>,338	) -> DispatchResultWithPostInfo {339		let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);340341		with_weight(342			<Pallet<T>>::delete_collection_properties(self, sender, property_keys),343			weight,344		)345	}346347	fn set_token_properties(348		&self,349		_sender: T::CrossAccountId,350		_token_id: TokenId,351		_property: Vec<Property>,352		_nesting_budget: &dyn Budget,353	) -> DispatchResultWithPostInfo {354		fail!(<Error<T>>::SettingPropertiesNotAllowed)355	}356357	fn set_token_property_permissions(358		&self,359		_sender: &T::CrossAccountId,360		_property_permissions: Vec<PropertyKeyPermission>,361	) -> DispatchResultWithPostInfo {362		fail!(<Error<T>>::SettingPropertiesNotAllowed)363	}364365	fn delete_token_properties(366		&self,367		_sender: T::CrossAccountId,368		_token_id: TokenId,369		_property_keys: Vec<PropertyKey>,370		_nesting_budget: &dyn Budget,371	) -> DispatchResultWithPostInfo {372		fail!(<Error<T>>::SettingPropertiesNotAllowed)373	}374375	fn check_nesting(376		&self,377		_sender: <T>::CrossAccountId,378		_from: (CollectionId, TokenId),379		_under: TokenId,380		_nesting_budget: &dyn Budget,381	) -> sp_runtime::DispatchResult {382		fail!(<Error<T>>::FungibleDisallowsNesting)383	}384385	fn nest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}386387	fn unnest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}388389	fn collection_tokens(&self) -> Vec<TokenId> {390		vec![TokenId::default()]391	}392393	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {394		if <Balance<T>>::get((self.id, account)) != 0 {395			vec![TokenId::default()]396		} else {397			vec![]398		}399	}400401	fn token_exists(&self, token: TokenId) -> bool {402		token == TokenId::default()403	}404405	fn last_token_id(&self) -> TokenId {406		TokenId::default()407	}408409	fn token_owner(&self, _token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError> {410		Err(TokenOwnerError::MultipleOwners)411	}412413	/// Returns 10 tokens owners in no particular order.414	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {415		<Pallet<T>>::token_owners(self.id, token).unwrap_or_default()416	}417418	fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {419		None420	}421422	fn token_properties(423		&self,424		_token_id: TokenId,425		_keys: Option<Vec<PropertyKey>>,426	) -> Vec<Property> {427		Vec::new()428	}429430	fn total_supply(&self) -> u32 {431		1432	}433434	fn account_balance(&self, account: T::CrossAccountId) -> u32 {435		if <Balance<T>>::get((self.id, account)) != 0 {436			1437		} else {438			0439		}440	}441442	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {443		if token != TokenId::default() {444			return 0;445		}446		<Balance<T>>::get((self.id, account))447	}448449	fn allowance(450		&self,451		sender: T::CrossAccountId,452		spender: T::CrossAccountId,453		token: TokenId,454	) -> u128 {455		if token != TokenId::default() {456			return 0;457		}458		<Allowance<T>>::get((self.id, sender, spender))459	}460461	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {462		None463	}464465	fn total_pieces(&self, token: TokenId) -> Option<u128> {466		if token != TokenId::default() {467			return None;468		}469		<TotalSupply<T>>::try_get(self.id).ok()470	}471472	fn set_allowance_for_all(473		&self,474		_owner: T::CrossAccountId,475		_operator: T::CrossAccountId,476		_approve: bool,477	) -> DispatchResultWithPostInfo {478		fail!(<Error<T>>::SettingAllowanceForAllNotAllowed)479	}480481	fn allowance_for_all(&self, _owner: T::CrossAccountId, _operator: T::CrossAccountId) -> bool {482		false483	}484485	/// Repairs a possibly broken item.486	fn repair_item(&self, _token: TokenId) -> DispatchResultWithPostInfo {487		fail!(<Error<T>>::FungibleTokensAreAlwaysValid)488	}489}
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -19,7 +19,7 @@
 use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};
 use up_data_structs::{
 	TokenId, CreateItemExData, CollectionId, budget::Budget, Property, PropertyKey,
-	PropertyKeyPermission, PropertyValue,
+	PropertyKeyPermission, PropertyValue, TokenOwnerError,
 };
 use pallet_common::{
 	CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
@@ -460,13 +460,15 @@
 		TokenId(<TokensMinted<T>>::get(self.id))
 	}
 
-	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {
-		<TokenData<T>>::get((self.id, token)).map(|t| t.owner)
+	fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError> {
+		<TokenData<T>>::get((self.id, token))
+			.map(|t| t.owner)
+			.ok_or(TokenOwnerError::NotFound)
 	}
 
 	/// Returns token owners.
 	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {
-		self.token_owner(token).map_or_else(|| vec![], |t| vec![t])
+		self.token_owner(token).map_or_else(|_| vec![], |t| vec![t])
 	}
 
 	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -728,7 +728,7 @@
 	fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {
 		Self::token_owner(&self, token_id.try_into()?)
 			.map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))
-			.ok_or(Error::Revert("key too large".into()))
+			.map_err(|_| Error::Revert("token not found".into()))
 	}
 
 	/// Returns the token properties.
modifiedpallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth
--- a/pallets/proxy-rmrk-core/src/lib.rs
+++ b/pallets/proxy-rmrk-core/src/lib.rs
@@ -741,7 +741,8 @@
 						Some((collection_id, nft_id)),
 						&target_nft_budget,
 					)
-					.map_err(Self::map_unique_err_to_proxy)?;
+					.map_err(Self::map_unique_err_to_proxy)?
+					.ok_or::<DispatchError>(<Error<T>>::NoPermission.into())?;
 
 					approval_required = cross_sender != target_nft_owner;
 
@@ -989,7 +990,8 @@
 
 			let nft_owner =
 				<PalletStructure<T>>::find_topmost_owner(collection_id, nft_id, &budget)
-					.map_err(|_| <Error<T>>::ResourceDoesntExist)?;
+					.map_err(|_| <Error<T>>::ResourceDoesntExist)?
+					.ok_or::<DispatchError>(<Error<T>>::NoPermission.into())?;
 
 			Self::try_mutate_resource_info(collection_id, nft_id, resource_id, |res| {
 				ensure!(res.pending, <Error<T>>::ResourceNotPending);
@@ -1044,7 +1046,8 @@
 
 			let nft_owner =
 				<PalletStructure<T>>::find_topmost_owner(collection_id, nft_id, &budget)
-					.map_err(|_| <Error<T>>::ResourceDoesntExist)?;
+					.map_err(|_| <Error<T>>::ResourceDoesntExist)?
+					.ok_or::<DispatchError>(<Error<T>>::NoPermission.into())?;
 
 			ensure!(cross_sender == nft_owner, <Error<T>>::NoPermission);
 
@@ -1666,7 +1669,8 @@
 		let budget = budget::Value::new(NESTING_BUDGET);
 
 		let nft_owner = <PalletStructure<T>>::find_topmost_owner(collection_id, nft_id, &budget)
-			.map_err(Self::map_unique_err_to_proxy)?;
+			.map_err(Self::map_unique_err_to_proxy)?
+			.ok_or::<DispatchError>(<Error<T>>::NoPermission.into())?;
 
 		let pending = sender != nft_owner;
 
@@ -1720,7 +1724,8 @@
 
 		let budget = up_data_structs::budget::Value::new(NESTING_BUDGET);
 		let topmost_owner =
-			<PalletStructure<T>>::find_topmost_owner(collection_id, nft_id, &budget)?;
+			<PalletStructure<T>>::find_topmost_owner(collection_id, nft_id, &budget)?
+				.ok_or::<DispatchError>(<Error<T>>::NoPermission.into())?;
 
 		let sender = T::CrossAccountId::from_sub(sender);
 		if topmost_owner == sender {
modifiedpallets/proxy-rmrk-core/src/rpc.rsdiffbeforeafterboth
--- a/pallets/proxy-rmrk-core/src/rpc.rs
+++ b/pallets/proxy-rmrk-core/src/rpc.rs
@@ -68,7 +68,7 @@
 	}
 
 	let owner = match collection.token_owner(nft_id) {
-		Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {
+		Ok(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {
 			Some((col, tok)) => {
 				let rmrk_collection = <Pallet<T>>::rmrk_collection_id(col)?;
 
@@ -76,7 +76,7 @@
 			}
 			None => RmrkAccountIdOrCollectionNftTuple::AccountId(owner.as_sub().clone()),
 		},
-		None => return Ok(None),
+		_ => return Ok(None),
 	};
 
 	Ok(Some(RmrkInstanceInfo {
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -21,7 +21,7 @@
 use up_data_structs::{
 	CollectionId, TokenId, CreateItemExData, budget::Budget, Property, PropertyKey, PropertyValue,
 	PropertyKeyPermission, CollectionPropertiesVec, CreateRefungibleExMultipleOwners,
-	CreateRefungibleExSingleOwner,
+	CreateRefungibleExSingleOwner, TokenOwnerError,
 };
 use pallet_common::{
 	CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
@@ -478,7 +478,7 @@
 		TokenId(<TokensMinted<T>>::get(self.id))
 	}
 
-	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {
+	fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError> {
 		<Pallet<T>>::token_owner(self.id, token)
 	}
 
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -43,7 +43,7 @@
 use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};
 use up_data_structs::{
 	CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,
-	PropertyKeyPermission, PropertyPermission, TokenId,
+	PropertyKeyPermission, PropertyPermission, TokenId, TokenOwnerError,
 };
 
 use crate::{
@@ -411,9 +411,12 @@
 		self.consume_store_reads(2)?;
 		let token = token_id.try_into()?;
 		let owner = <Pallet<T>>::token_owner(self.id, token);
-		Ok(owner
+		owner
 			.map(|address| *address.as_eth())
-			.unwrap_or_else(|| ADDRESS_FOR_PARTIALLY_OWNED_TOKENS))
+			.or_else(|err| match err {
+				TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),
+				TokenOwnerError::MultipleOwners => Ok(ADDRESS_FOR_PARTIALLY_OWNED_TOKENS),
+			})
 	}
 
 	/// @dev Not implemented
@@ -766,7 +769,12 @@
 	fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {
 		Self::token_owner(&self, token_id.try_into()?)
 			.map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))
-			.ok_or(Error::Revert("key too large".into()))
+			.or_else(|err| match err {
+				TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),
+				TokenOwnerError::MultipleOwners => Ok(eth::CrossAddress::from_eth(
+					ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,
+				)),
+			})
 	}
 
 	/// Returns the token properties.
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -107,7 +107,7 @@
 	AccessMode, budget::Budget, CollectionId, CollectionFlags, CreateCollectionData,
 	mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, Property, PropertyKey,
 	PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue, TokenId,
-	TrySetProperty, PropertiesPermissionMap, CreateRefungibleExMultipleOwners,
+	TrySetProperty, PropertiesPermissionMap, CreateRefungibleExMultipleOwners, TokenOwnerError,
 };
 
 pub use pallet::*;
@@ -480,7 +480,7 @@
 			<Balance<T>>::remove((collection.id, token, owner));
 			<AccountBalance<T>>::insert((collection.id, owner), account_balance);
 
-			if let Some(user) = Self::token_owner(collection.id, token) {
+			if let Ok(user) = Self::token_owner(collection.id, token) {
 				<PalletEvm<T>>::deposit_log(
 					ERC721Events::Transfer {
 						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,
@@ -1365,17 +1365,20 @@
 		Ok(())
 	}
 
-	fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {
+	fn token_owner(
+		collection_id: CollectionId,
+		token_id: TokenId,
+	) -> Result<T::CrossAccountId, TokenOwnerError> {
 		let mut owner = None;
 		let mut count = 0;
 		for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {
 			count += 1;
 			if count > 1 {
-				return None;
+				return Err(TokenOwnerError::MultipleOwners);
 			}
 			owner = Some(key);
 		}
-		owner
+		owner.ok_or(TokenOwnerError::NotFound)
 	}
 
 	fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {
modifiedpallets/structure/src/lib.rsdiffbeforeafterboth
--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -61,7 +61,9 @@
 use frame_support::fail;
 pub use pallet::*;
 use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};
-use up_data_structs::{CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget};
+use up_data_structs::{
+	CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget, TokenOwnerError,
+};
 
 #[cfg(feature = "runtime-benchmarks")]
 pub mod benchmarking;
@@ -135,6 +137,8 @@
 	User(CrossAccountId),
 	/// Could not find the token provided as the owner.
 	TokenNotFound,
+	/// Nested token has multiple owners.
+	MultipleOwners,
 	/// Token owner is another token (still, the target token may not exist).
 	Token(CollectionId, TokenId),
 }
@@ -159,11 +163,12 @@
 		let handle = handle.as_dyn();
 
 		Ok(match handle.token_owner(token) {
-			Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {
+			Ok(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {
 				Some((collection, token)) => Parent::Token(collection, token),
 				None => Parent::User(owner),
 			},
-			None => Parent::TokenNotFound,
+			Err(TokenOwnerError::MultipleOwners) => Parent::MultipleOwners,
+			Err(TokenOwnerError::NotFound) => Parent::TokenNotFound,
 		})
 	}
 
@@ -203,19 +208,27 @@
 	///
 	/// May return token address if parent token not yet exists
 	///
+	/// Returns `None` if the token has multiple owners.
+	///
 	/// - `budget`: Limit for searching parents in depth.
 	pub fn find_topmost_owner(
 		collection: CollectionId,
 		token: TokenId,
 		budget: &dyn Budget,
-	) -> Result<T::CrossAccountId, DispatchError> {
+	) -> Result<Option<T::CrossAccountId>, DispatchError> {
 		let owner = Self::parent_chain(collection, token)
 			.take_while(|_| budget.consume())
-			.find(|p| matches!(p, Ok(Parent::User(_) | Parent::TokenNotFound)))
+			.find(|p| {
+				matches!(
+					p,
+					Ok(Parent::User(_) | Parent::TokenNotFound | Parent::MultipleOwners)
+				)
+			})
 			.ok_or(<Error<T>>::DepthLimit)??;
 
 		Ok(match owner {
-			Parent::User(v) => v,
+			Parent::User(v) => Some(v),
+			Parent::MultipleOwners => None,
 			_ => fail!(<Error<T>>::TokenNotFound),
 		})
 	}
@@ -223,13 +236,15 @@
 	/// Find the topmost parent and check that assigning `for_nest` token as a child for
 	/// `token` wouldn't create a cycle.
 	///
+	/// Returns `None` if the token has multiple owners.
+	///
 	/// - `budget`: Limit for searching parents in depth.
 	pub fn get_checked_topmost_owner(
 		collection: CollectionId,
 		token: TokenId,
 		for_nest: Option<(CollectionId, TokenId)>,
 		budget: &dyn Budget,
-	) -> Result<T::CrossAccountId, DispatchError> {
+	) -> Result<Option<T::CrossAccountId>, DispatchError> {
 		// Tried to nest token in itself
 		if Some((collection, token)) == for_nest {
 			return Err(<Error<T>>::OuroborosDetected.into());
@@ -242,8 +257,9 @@
 					return Err(<Error<T>>::OuroborosDetected.into())
 				}
 				// Token is owned by other user
-				Parent::User(user) => return Ok(user),
+				Parent::User(user) => return Ok(Some(user)),
 				Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),
+				Parent::MultipleOwners => return Ok(None),
 				// Continue parent chain
 				Parent::Token(_, _) => {}
 			}
@@ -284,12 +300,17 @@
 		budget: &dyn Budget,
 	) -> Result<bool, DispatchError> {
 		let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {
-			Some((collection, token)) => Self::find_topmost_owner(collection, token, budget)?,
+			Some((collection, token)) => match Self::find_topmost_owner(collection, token, budget)?
+			{
+				Some(topmost_owner) => topmost_owner,
+				None => return Ok(false),
+			},
 			None => user,
 		};
 
-		Self::get_checked_topmost_owner(collection, token, for_nest, budget)
-			.map(|indirect_owner| indirect_owner == target_parent)
+		Self::get_checked_topmost_owner(collection, token, for_nest, budget).map(|indirect_owner| {
+			indirect_owner.map_or(false, |indirect_owner| indirect_owner == target_parent)
+		})
 	}
 
 	/// Checks that `under` is valid token and that `token_id` could be nested under it
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -1099,6 +1099,13 @@
 	EmptyPropertyKey,
 }
 
+/// Token owner error: it could be either `NotFound` ot `MultipleOwners`.
+#[derive(Debug)]
+pub enum TokenOwnerError {
+	NotFound,
+	MultipleOwners,
+}
+
 /// Marker for scope of property.
 ///
 /// Scoped property can't be changed by user. Used for external collections.
modifiedruntime/common/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -16,11 +16,11 @@
 
 #[macro_export]
 macro_rules! dispatch_unique_runtime {
-	($collection:ident.$method:ident($($name:ident),*)) => {{
+	($collection:ident.$method:ident($($name:ident),*) $($rest:tt)*) => {{
 		let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);
 		let dispatch = collection.as_dyn();
 
-		Ok::<_, DispatchError>(dispatch.$method($($name),*))
+		Ok::<_, DispatchError>(dispatch.$method($($name),*) $($rest)*)
 	}};
 }
 
@@ -73,7 +73,7 @@
                 }
 
                 fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {
-                    dispatch_unique_runtime!(collection.token_owner(token))
+                    dispatch_unique_runtime!(collection.token_owner(token).ok())
                 }
 
                 fn token_owners(collection: CollectionId, token: TokenId) -> Result<Vec::<CrossAccountId>, DispatchError>  {
@@ -83,7 +83,7 @@
                 fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {
                     let budget = up_data_structs::budget::Value::new(10);
 
-                    Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))
+                    Ok(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?)
                 }
                 fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {
                     Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))
modifiedtests/src/nesting/nest.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/nest.test.ts
+++ b/tests/src/nesting/nest.test.ts
@@ -15,7 +15,7 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 import {IKeyringPair} from '@polkadot/types/types';
-import {expect, itSub, usingPlaygrounds} from '../util';
+import {expect, itSub, Pallets, usingPlaygrounds} from '../util';
 
 describe('Integration Test: Composite nesting tests', () => {
   let alice: IKeyringPair;
@@ -138,7 +138,7 @@
   before(async () => {
     await usingPlaygrounds(async (helper, privateKey) => {
       const donor = await privateKey({filename: __filename});
-      [alice, bob, charlie] = await helper.arrange.createAccounts([50n, 10n, 10n], donor);
+      [alice, bob, charlie] = await helper.arrange.createAccounts([200n, 10n, 10n], donor);
     });
   });
 
@@ -288,6 +288,38 @@
     await collectionFT.transfer(charlie, targetToken.nestingAccount(), 2n);
     expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(7n);
   });
+
+  itSub.ifWithPallets('ReFungible: getTopmostOwner works correctly with Nesting', [Pallets.ReFungible], async({helper}) => {
+    const collectionNFT = await helper.nft.mintCollection(alice, {
+      permissions: {
+        nesting: {
+          tokenOwner: true,
+        },
+      },
+    });
+    const collectionRFT = await helper.rft.mintCollection(alice);
+
+    const nft = await collectionNFT.mintToken(alice, {Substrate: alice.address});
+    const rft = await collectionRFT.mintToken(alice, 100n, {Substrate: alice.address});
+
+    expect(await rft.getTopmostOwner()).deep.equal({Substrate: alice.address});
+
+    await rft.transfer(alice, nft.nestingAccount(), 40n);
+
+    expect(await rft.getTopmostOwner()).deep.equal(null);
+
+    await rft.transfer(alice, nft.nestingAccount(), 60n);
+
+    expect(await rft.getTopmostOwner()).deep.equal({Substrate: alice.address});
+
+    await rft.transferFrom(alice, nft.nestingAccount(), {Substrate: alice.address}, 30n);
+
+    expect(await rft.getTopmostOwner()).deep.equal(null);
+
+    await rft.transferFrom(alice, nft.nestingAccount(), {Substrate: alice.address}, 70n);
+
+    expect(await rft.getTopmostOwner()).deep.equal({Substrate: alice.address});
+  });
 });
 
 describe('Negative Test: Nesting', () => {