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
after · pallets/common/src/eth.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/>.1617//! The module contains a number of functions for converting and checking ethereum identifiers.1819use alloc::format;20use sp_std::{vec, vec::Vec};21use evm_coder::{AbiCoder, types::Address};22pub use pallet_evm::{Config, account::CrossAccountId};23use sp_core::{H160, U256};24use up_data_structs::CollectionId;2526// 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection 127// TODO: Unhardcode prefix28const ETH_COLLECTION_PREFIX: [u8; 16] = [29	0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,30];3132/// Maps the ethereum address of the collection in substrate.33pub fn map_eth_to_id(eth: &Address) -> Option<CollectionId> {34	if eth[0..16] != ETH_COLLECTION_PREFIX {35		return None;36	}37	let mut id_bytes = [0; 4];38	id_bytes.copy_from_slice(&eth[16..20]);39	Some(CollectionId(u32::from_be_bytes(id_bytes)))40}4142/// Maps the substrate collection id in ethereum.43pub fn collection_id_to_address(id: CollectionId) -> Address {44	let mut out = [0; 20];45	out[0..16].copy_from_slice(&ETH_COLLECTION_PREFIX);46	out[16..20].copy_from_slice(&u32::to_be_bytes(id.0));47	H160(out)48}4950/// Check if the ethereum address is a collection.51pub fn is_collection(address: &Address) -> bool {52	address[0..16] == ETH_COLLECTION_PREFIX53}5455/// Convert `U256` to `CrossAccountId`.56pub fn convert_uint256_to_cross_account<T: Config>(from: U256) -> T::CrossAccountId57where58	T::AccountId: From<[u8; 32]>,59{60	let mut new_admin_arr = [0_u8; 32];61	from.to_big_endian(&mut new_admin_arr);62	let account_id = T::AccountId::from(new_admin_arr);63	T::CrossAccountId::from_sub(account_id)64}6566/// Cross account struct67#[derive(Debug, Default, AbiCoder)]68pub struct CrossAddress {69	pub(crate) eth: Address,70	pub(crate) sub: U256,71}7273impl CrossAddress {74	/// Converts `CrossAccountId` to [`CrossAddress`] to be correctly usable with Ethereum.75	pub fn from_sub_cross_account<T>(cross_account_id: &T::CrossAccountId) -> Self76	where77		T: pallet_evm::Config,78		T::AccountId: AsRef<[u8; 32]>,79	{80		if cross_account_id.is_canonical_substrate() {81			Self::from_sub::<T>(cross_account_id.as_sub())82		} else {83			Self::from_eth(*cross_account_id.as_eth())84		}85	}86	/// Creates [`CrossAddress`] from Substrate account.87	pub fn from_sub<T>(account_id: &T::AccountId) -> Self88	where89		T: pallet_evm::Config,90		T::AccountId: AsRef<[u8; 32]>,91	{92		Self {93			eth: Default::default(),94			sub: U256::from_big_endian(account_id.as_ref()),95		}96	}97	/// Creates [`CrossAddress`] from Ethereum account.98	pub fn from_eth(address: Address) -> Self {99		Self {100			eth: address,101			sub: Default::default(),102		}103	}104	/// Converts [`CrossAddress`] to `CrossAccountId`.105	pub fn into_sub_cross_account<T>(&self) -> evm_coder::execution::Result<T::CrossAccountId>106	where107		T: pallet_evm::Config,108		T::AccountId: From<[u8; 32]>,109	{110		if self.eth == Default::default() && self.sub == Default::default() {111			Err("All fields of cross account is zeroed".into())112		} else if self.eth == Default::default() {113			Ok(convert_uint256_to_cross_account::<T>(self.sub))114		} else if self.sub == Default::default() {115			Ok(T::CrossAccountId::from_eth(self.eth))116		} else {117			Err("All fields of cross account is non zeroed".into())118		}119	}120}121122/// Ethereum representation of collection [`PropertyKey`](up_data_structs::PropertyKey) and [`PropertyValue`](up_data_structs::PropertyValue).123#[derive(Debug, Default, AbiCoder)]124pub struct Property {125	key: evm_coder::types::String,126	value: evm_coder::types::Bytes,127}128129impl TryFrom<up_data_structs::Property> for Property {130	type Error = evm_coder::execution::Error;131132	fn try_from(from: up_data_structs::Property) -> Result<Self, Self::Error> {133		let key = evm_coder::types::String::from_utf8(from.key.into())134			.map_err(|e| Self::Error::Revert(format!("utf8 conversion error: {}", e)))?;135		let value = evm_coder::types::Bytes(from.value.to_vec());136		Ok(Property { key, value })137	}138}139140impl TryInto<up_data_structs::Property> for Property {141	type Error = evm_coder::execution::Error;142143	fn try_into(self) -> Result<up_data_structs::Property, Self::Error> {144		let key = <Vec<u8>>::from(self.key)145			.try_into()146			.map_err(|_| "key too large")?;147148		let value = self.value.0.try_into().map_err(|_| "value too large")?;149150		Ok(up_data_structs::Property { key, value })151	}152}153154/// [`CollectionLimits`](up_data_structs::CollectionLimits) fields representation for EVM.155#[derive(Debug, Default, Clone, Copy, AbiCoder)]156#[repr(u8)]157pub enum CollectionLimitField {158	/// How many tokens can a user have on one account.159	#[default]160	AccountTokenOwnership,161162	/// How many bytes of data are available for sponsorship.163	SponsoredDataSize,164165	/// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]166	SponsoredDataRateLimit,167168	/// How many tokens can be mined into this collection.169	TokenLimit,170171	/// Timeouts for transfer sponsoring.172	SponsorTransferTimeout,173174	/// Timeout for sponsoring an approval in passed blocks.175	SponsorApproveTimeout,176177	/// Whether the collection owner of the collection can send tokens (which belong to other users).178	OwnerCanTransfer,179180	/// Can the collection owner burn other people's tokens.181	OwnerCanDestroy,182183	/// Is it possible to send tokens from this collection between users.184	TransferEnabled,185}186187/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.188#[derive(Debug, Default, AbiCoder)]189pub struct CollectionLimit {190	field: CollectionLimitField,191	value: Option<U256>,192}193194impl CollectionLimit {195	/// Create [`CollectionLimit`] from field and value.196	pub fn new(field: CollectionLimitField, value: Option<u32>) -> Self {197		Self {198			field,199			value: match value {200				Some(value) => Some(value.into()),201				None => None,202			},203		}204	}205	/// Whether the field contains a value.206	pub fn has_value(&self) -> bool {207		self.value.is_some()208	}209}210211impl TryInto<up_data_structs::CollectionLimits> for CollectionLimit {212	type Error = evm_coder::execution::Error;213214	fn try_into(self) -> Result<up_data_structs::CollectionLimits, Self::Error> {215		let value = self216			.value217			.ok_or::<Self::Error>("can't convert `None` value to boolean".into())?;218		let value = Some(value.try_into().map_err(|error| {219			Self::Error::Revert(format!(220				"can't convert value to u32 \"{}\" because: \"{error}\"",221				value222			))223		})?);224225		let convert_value_to_bool = || match value {226			Some(value) => match value {227				0 => Ok(Some(false)),228				1 => Ok(Some(true)),229				_ => {230					return Err(Self::Error::Revert(format!(231						"can't convert value to boolean \"{value}\""232					)))233				}234			},235			None => Ok(None),236		};237238		let mut limits = up_data_structs::CollectionLimits::default();239		match self.field {240			CollectionLimitField::AccountTokenOwnership => {241				limits.account_token_ownership_limit = value;242			}243			CollectionLimitField::SponsoredDataSize => {244				limits.sponsored_data_size = value;245			}246			CollectionLimitField::SponsoredDataRateLimit => {247				limits.sponsored_data_rate_limit = match value {248					Some(value) => Some(up_data_structs::SponsoringRateLimit::Blocks(value)),249					None => None,250				};251			}252			CollectionLimitField::TokenLimit => {253				limits.token_limit = value;254			}255			CollectionLimitField::SponsorTransferTimeout => {256				limits.sponsor_transfer_timeout = value;257			}258			CollectionLimitField::SponsorApproveTimeout => {259				limits.sponsor_approve_timeout = value;260			}261			CollectionLimitField::OwnerCanTransfer => {262				limits.owner_can_transfer = convert_value_to_bool()?;263			}264			CollectionLimitField::OwnerCanDestroy => {265				limits.owner_can_destroy = convert_value_to_bool()?;266			}267			CollectionLimitField::TransferEnabled => {268				limits.transfers_enabled = convert_value_to_bool()?;269			}270		};271		Ok(limits)272	}273}274275/// Ethereum representation of `NestingPermissions` (see [`up_data_structs::NestingPermissions`]) fields as an enumeration.276#[derive(Default, Debug, Clone, Copy, AbiCoder)]277#[repr(u8)]278pub enum CollectionPermissionField {279	/// Owner of token can nest tokens under it.280	#[default]281	TokenOwner,282283	/// Admin of token collection can nest tokens under token.284	CollectionAdmin,285}286287/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) fields as an enumeration.288#[derive(AbiCoder, Copy, Clone, Default, Debug)]289#[repr(u8)]290pub enum TokenPermissionField {291	/// Permission to change the property and property permission. See [`up_data_structs::PropertyPermission::mutable`]292	#[default]293	Mutable,294295	/// Change permission for the collection administrator. See [`up_data_structs::PropertyPermission::token_owner`]296	TokenOwner,297298	/// Permission to change the property for the owner of the token. See [`up_data_structs::PropertyPermission::collection_admin`]299	CollectionAdmin,300}301302/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) as an key and value.303#[derive(Debug, Default, AbiCoder)]304pub struct PropertyPermission {305	/// TokenPermission field.306	code: TokenPermissionField,307	/// TokenPermission value.308	value: bool,309}310311impl PropertyPermission {312	/// Make vector of [`PropertyPermission`] from [`up_data_structs::PropertyPermission`].313	pub fn into_vec(pp: up_data_structs::PropertyPermission) -> Vec<Self> {314		vec![315			PropertyPermission {316				code: TokenPermissionField::Mutable,317				value: pp.mutable,318			},319			PropertyPermission {320				code: TokenPermissionField::TokenOwner,321				value: pp.token_owner,322			},323			PropertyPermission {324				code: TokenPermissionField::CollectionAdmin,325				value: pp.collection_admin,326			},327		]328	}329330	/// Make [`up_data_structs::PropertyPermission`] from vector of [`PropertyPermission`].331	pub fn from_vec(permission: Vec<Self>) -> up_data_structs::PropertyPermission {332		let mut token_permission = up_data_structs::PropertyPermission::default();333334		for PropertyPermission { code, value } in permission {335			match code {336				TokenPermissionField::Mutable => token_permission.mutable = value,337				TokenPermissionField::TokenOwner => token_permission.token_owner = value,338				TokenPermissionField::CollectionAdmin => token_permission.collection_admin = value,339			}340		}341		token_permission342	}343}344345/// Ethereum representation of Token Property Permissions.346#[derive(Debug, Default, AbiCoder)]347pub struct TokenPropertyPermission {348	/// Token property key.349	key: evm_coder::types::String,350	/// Token property permissions.351	permissions: Vec<PropertyPermission>,352}353354impl355	From<(356		up_data_structs::PropertyKey,357		up_data_structs::PropertyPermission,358	)> for TokenPropertyPermission359{360	fn from(361		value: (362			up_data_structs::PropertyKey,363			up_data_structs::PropertyPermission,364		),365	) -> Self {366		let (key, permission) = value;367		let key = evm_coder::types::String::from_utf8(key.into_inner())368			.expect("Stored key must be valid");369		let permissions = PropertyPermission::into_vec(permission);370		Self { key, permissions }371	}372}373374impl TokenPropertyPermission {375	/// Convert vector of [`TokenPropertyPermission`] into vector of [`up_data_structs::PropertyKeyPermission`].376	pub fn into_property_key_permissions(377		permissions: Vec<TokenPropertyPermission>,378	) -> evm_coder::execution::Result<Vec<up_data_structs::PropertyKeyPermission>> {379		let mut perms = Vec::new();380381		for TokenPropertyPermission { key, permissions } in permissions {382			let token_permission = PropertyPermission::from_vec(permissions);383384			perms.push(up_data_structs::PropertyKeyPermission {385				key: key.into_bytes().try_into().map_err(|_| "too long key")?,386				permission: token_permission,387			});388		}389		Ok(perms)390	}391}392393/// Nested collections.394#[derive(Debug, Default, AbiCoder)]395pub struct CollectionNesting {396	token_owner: bool,397	ids: Vec<U256>,398}399400impl CollectionNesting {401	/// Create [`CollectionNesting`].402	pub fn new(token_owner: bool, ids: Vec<U256>) -> Self {403		Self { token_owner, ids }404	}405}406407/// Ethereum representation of `NestingPermissions` (see [`up_data_structs::NestingPermissions`]) field.408#[derive(Debug, Default, AbiCoder)]409pub struct CollectionNestingPermission {410	field: CollectionPermissionField,411	value: bool,412}413414impl CollectionNestingPermission {415	/// Create [`CollectionNestingPermission`].416	pub fn new(field: CollectionPermissionField, value: bool) -> Self {417		Self { field, value }418	}419}420421/// Ethereum representation of `AccessMode` (see [`up_data_structs::AccessMode`]).422#[derive(AbiCoder, Copy, Clone, Default, Debug)]423#[repr(u8)]424pub enum AccessMode {425	/// Access grant for owner and admins. Used as default.426	#[default]427	Normal,428	/// Like a [`Normal`](AccessMode::Normal) but also users in allow list.429	AllowList,430}431432impl From<up_data_structs::AccessMode> for AccessMode {433	fn from(value: up_data_structs::AccessMode) -> Self {434		match value {435			up_data_structs::AccessMode::Normal => AccessMode::Normal,436			up_data_structs::AccessMode::AllowList => AccessMode::AllowList,437		}438	}439}440441impl Into<up_data_structs::AccessMode> for AccessMode {442	fn into(self) -> up_data_structs::AccessMode {443		match self {444			AccessMode::Normal => up_data_structs::AccessMode::Normal,445			AccessMode::AllowList => up_data_structs::AccessMode::AllowList,446		}447	}448}
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
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -17,7 +17,9 @@
 use core::marker::PhantomData;
 
 use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, traits::Get};
-use up_data_structs::{TokenId, CollectionId, CreateItemExData, budget::Budget, CreateItemData};
+use up_data_structs::{
+	TokenId, CollectionId, CreateItemExData, budget::Budget, CreateItemData, TokenOwnerError,
+};
 use pallet_common::{
 	CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
 	weights::WeightInfo as _,
@@ -404,8 +406,8 @@
 		TokenId::default()
 	}
 
-	fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {
-		None
+	fn token_owner(&self, _token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError> {
+		Err(TokenOwnerError::MultipleOwners)
 	}
 
 	/// Returns 10 tokens owners in no particular order.
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', () => {