difftreelog
Merge pull request #848 from UniqueNetwork/fix/find-parent
in: master
15 files changed
pallets/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::{
pallets/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
pallets/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.
///
pallets/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.
pallets/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> {
pallets/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.
pallets/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 {
pallets/proxy-rmrk-core/src/rpc.rsdiffbeforeafterboth1// 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//! Realizations of RMRK RPCs (remote procedure calls) related to the Core pallet.1819use super::*;2021/// Get the latest created collection ID.22pub fn last_collection_idx<T: Config>() -> Result<RmrkCollectionId, DispatchError> {23 Ok(<Pallet<T>>::last_collection_idx())24}2526/// Get collection info by ID.27pub fn collection_by_id<T: Config>(28 collection_id: RmrkCollectionId,29) -> Result<Option<RmrkCollectionInfo<T::AccountId>>, DispatchError> {30 let (collection, collection_id) = match <Pallet<T>>::get_typed_nft_collection_mapped(31 collection_id,32 misc::CollectionType::Regular,33 ) {34 Ok(c) => c,35 Err(_) => return Ok(None),36 };3738 let nfts_count = collection.total_supply();3940 Ok(Some(RmrkCollectionInfo {41 issuer: collection.owner.clone(),42 metadata: <Pallet<T>>::get_collection_property_decoded(43 collection_id,44 RmrkProperty::Metadata,45 )?,46 max: collection.limits.token_limit,47 symbol: <Pallet<T>>::rebind(&collection.token_prefix)?,48 nfts_count,49 }))50}5152/// Get NFT info by collection and NFT IDs.53pub fn nft_by_id<T: Config>(54 collection_id: RmrkCollectionId,55 nft_by_id: RmrkNftId,56) -> Result<Option<RmrkInstanceInfo<T::AccountId>>, DispatchError> {57 let (collection, collection_id) = match <Pallet<T>>::get_typed_nft_collection_mapped(58 collection_id,59 misc::CollectionType::Regular,60 ) {61 Ok(c) => c,62 Err(_) => return Ok(None),63 };6465 let nft_id = TokenId(nft_by_id);66 if !<Pallet<T>>::nft_exists(collection_id, nft_id) {67 return Ok(None);68 }6970 let owner = match collection.token_owner(nft_id) {71 Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {72 Some((col, tok)) => {73 let rmrk_collection = <Pallet<T>>::rmrk_collection_id(col)?;7475 RmrkAccountIdOrCollectionNftTuple::CollectionAndNftTuple(rmrk_collection, tok.0)76 }77 None => RmrkAccountIdOrCollectionNftTuple::AccountId(owner.as_sub().clone()),78 },79 None => return Ok(None),80 };8182 Ok(Some(RmrkInstanceInfo {83 owner: owner,84 royalty: <Pallet<T>>::get_nft_property_decoded(85 collection_id,86 nft_id,87 RmrkProperty::RoyaltyInfo,88 )?,89 metadata: <Pallet<T>>::get_nft_property_decoded(90 collection_id,91 nft_id,92 RmrkProperty::Metadata,93 )?,94 equipped: <Pallet<T>>::get_nft_property_decoded(95 collection_id,96 nft_id,97 RmrkProperty::Equipped,98 )?,99 pending: <Pallet<T>>::get_nft_property_decoded(100 collection_id,101 nft_id,102 RmrkProperty::PendingNftAccept,103 )?,104 }))105}106107/// Get tokens owned by an account in a collection.108pub fn account_tokens<T: Config>(109 account_id: T::AccountId,110 collection_id: RmrkCollectionId,111) -> Result<Vec<RmrkNftId>, DispatchError> {112 let cross_account_id = CrossAccountId::from_sub(account_id);113114 let (collection, collection_id) = match <Pallet<T>>::get_typed_nft_collection_mapped(115 collection_id,116 misc::CollectionType::Regular,117 ) {118 Ok(c) => c,119 Err(_) => return Ok(Vec::new()),120 };121122 let tokens = collection123 .account_tokens(cross_account_id)124 .into_iter()125 .filter(|token| {126 let is_pending = <Pallet<T>>::get_nft_property_decoded(127 collection_id,128 *token,129 RmrkProperty::PendingNftAccept,130 )131 .unwrap_or(true);132133 !is_pending134 })135 .map(|token| token.0)136 .collect();137138 Ok(tokens)139}140141/// Get tokens nested in an NFT - its direct children (not the children's children).142pub fn nft_children<T: Config>(143 collection_id: RmrkCollectionId,144 nft_id: RmrkNftId,145) -> Result<Vec<RmrkNftChild>, DispatchError> {146 let collection_id = match <Pallet<T>>::unique_collection_id(collection_id) {147 Ok(id) => id,148 Err(_) => return Ok(Vec::new()),149 };150 let nft_id = TokenId(nft_id);151 if !<Pallet<T>>::nft_exists(collection_id, nft_id) {152 return Ok(Vec::new());153 }154155 Ok(156 pallet_nonfungible::TokenChildren::<T>::iter_prefix((collection_id, nft_id))157 .filter_map(|((child_collection, child_token), _)| {158 let rmrk_child_collection =159 <Pallet<T>>::rmrk_collection_id(child_collection).ok()?;160161 Some(RmrkNftChild {162 collection_id: rmrk_child_collection,163 nft_id: child_token.0,164 })165 })166 .chain(167 <Pallet<T>>::iterate_pending_children(collection_id, nft_id)?.map(168 |(child_collection, child_nft_id)| RmrkNftChild {169 collection_id: child_collection,170 nft_id: child_nft_id,171 },172 ),173 )174 .collect(),175 )176}177178/// Get collection properties, created by the user - not the proxy-specific properties.179pub fn collection_properties<T: Config>(180 collection_id: RmrkCollectionId,181 filter_keys: Option<Vec<RmrkPropertyKey>>,182) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {183 let collection_id = match <Pallet<T>>::unique_collection_id(collection_id) {184 Ok(id) => id,185 Err(_) => return Ok(Vec::new()),186 };187 if <Pallet<T>>::ensure_collection_type(collection_id, misc::CollectionType::Regular).is_err() {188 return Ok(Vec::new());189 }190191 let properties = <Pallet<T>>::filter_user_properties(192 collection_id,193 /* token_id = */ None,194 filter_keys,195 |key, value| RmrkPropertyInfo { key, value },196 )?;197198 Ok(properties)199}200201/// Get NFT properties, created by the user - not the proxy-specific properties.202pub fn nft_properties<T: Config>(203 collection_id: RmrkCollectionId,204 nft_id: RmrkNftId,205 filter_keys: Option<Vec<RmrkPropertyKey>>,206) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {207 let collection_id = match <Pallet<T>>::unique_collection_id(collection_id) {208 Ok(id) => id,209 Err(_) => return Ok(Vec::new()),210 };211 let token_id = TokenId(nft_id);212213 if <Pallet<T>>::ensure_nft_type(collection_id, token_id, NftType::Regular).is_err() {214 return Ok(Vec::new());215 }216217 let properties = <Pallet<T>>::filter_user_properties(218 collection_id,219 Some(token_id),220 filter_keys,221 |key, value| RmrkPropertyInfo { key, value },222 )?;223224 Ok(properties)225}226227/// Get full information on each resource of an NFT, including pending.228pub fn nft_resources<T: Config>(229 collection_id: RmrkCollectionId,230 nft_id: RmrkNftId,231) -> Result<Vec<RmrkResourceInfo>, DispatchError> {232 let collection_id = match <Pallet<T>>::unique_collection_id(collection_id) {233 Ok(id) => id,234 Err(_) => return Ok(Vec::new()),235 };236 if <Pallet<T>>::ensure_collection_type(collection_id, misc::CollectionType::Regular).is_err() {237 return Ok(Vec::new());238 }239240 let nft_id = TokenId(nft_id);241 if <Pallet<T>>::ensure_nft_type(collection_id, nft_id, NftType::Regular).is_err() {242 return Ok(Vec::new());243 }244245 let resources = <pallet_nonfungible::Pallet<T>>::iterate_token_aux_properties(246 collection_id,247 nft_id,248 PropertyScope::Rmrk,249 )250 .filter_map(|(key, value)| {251 if !is_valid_key_prefix(&key, RESOURCE_ID_PREFIX) {252 return None;253 }254255 let resource_info: RmrkResourceInfo = <Pallet<T>>::decode_property_value(&value).ok()?;256257 Some(resource_info)258 })259 .collect();260261 Ok(resources)262}263264/// Get the priority of a resource in an NFT.265pub fn nft_resource_priority<T: Config>(266 collection_id: RmrkCollectionId,267 nft_id: RmrkNftId,268 resource_id: RmrkResourceId,269) -> Result<Option<u32>, DispatchError> {270 let collection_id = match <Pallet<T>>::unique_collection_id(collection_id) {271 Ok(id) => id,272 Err(_) => return Ok(None),273 };274 if <Pallet<T>>::ensure_collection_type(collection_id, misc::CollectionType::Regular).is_err() {275 return Ok(None);276 }277278 let nft_id = TokenId(nft_id);279 if <Pallet<T>>::ensure_nft_type(collection_id, nft_id, NftType::Regular).is_err() {280 return Ok(None);281 }282283 let priorities: Vec<_> = <Pallet<T>>::get_nft_property_decoded(284 collection_id,285 nft_id,286 RmrkProperty::ResourcePriorities,287 )?;288 Ok(priorities289 .into_iter()290 .enumerate()291 .find(|(_, id)| *id == resource_id)292 .map(|(priority, _): (usize, RmrkResourceId)| priority as u32))293}pallets/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)
}
pallets/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.
pallets/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> {
pallets/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
primitives/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.
runtime/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))
tests/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', () => {