difftreelog
fix find_parent
in: master
14 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.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 {
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.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//! # Structure Pallet18//!19//! The Structure pallet provides functionality for handling tokens nesting an unnesting.20//!21//! - [`Config`]22//! - [`Pallet`]23//!24//! ## Overview25//!26//! The Structure pallet provides functions for:27//!28//! - Searching for token parents, children and owners. Actual implementation of searching for29//! parent/child is done by pallets corresponding to token's collection type.30//! - Nesting and unnesting tokens. Actual implementation of nesting is done by pallets corresponding31//! to token's collection type.32//!33//! ### Terminology34//!35//! - **Nesting:** Setting up parent-child relationship between tokens. Nested tokens are inhereting36//! owner from their parent. There could be multiple levels of nesting. Token couldn't be nested in37//! it's child token i.e. parent-child relationship graph shouldn't have38//!39//! - **Parent:** Token that current token is nested in.40//!41//! - **Owner:** Account that owns the token and all nested tokens.42//!43//! ## Interface44//!45//! ### Available Functions46//!47//! - `find_parent` - Find parent of the token. It could be an account or another token.48//! - `parent_chain` - Find chain of parents of the token.49//! - `find_topmost_owner` - Find account or token in the end of the chain of parents.50//! - `check_nesting` - Check if the token could be nested in the other token51//! - `nest_if_sent_to_token` - Nest the token in the other token52//! - `unnest_if_nested` - Unnest the token from the other token5354#![cfg_attr(not(feature = "std"), no_std)]5556use pallet_common::CommonCollectionOperations;57use pallet_common::{erc::CrossAccountId, eth::is_collection};58use sp_std::collections::btree_set::BTreeSet;5960use frame_support::dispatch::{DispatchError, DispatchResult, DispatchResultWithPostInfo};61use frame_support::fail;62pub use pallet::*;63use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};64use up_data_structs::{CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget};6566#[cfg(feature = "runtime-benchmarks")]67pub mod benchmarking;68pub mod weights;6970pub type SelfWeightOf<T> = <T as crate::Config>::WeightInfo;7172#[frame_support::pallet]73pub mod pallet {74 use frame_support::Parameter;75 use frame_support::dispatch::{GetDispatchInfo, UnfilteredDispatchable};76 use frame_support::pallet_prelude::*;7778 use super::*;7980 #[pallet::error]81 pub enum Error<T> {82 /// While nesting, encountered an already checked account, detecting a loop.83 OuroborosDetected,84 /// While nesting, reached the depth limit of nesting, exceeding the provided budget.85 DepthLimit,86 /// While nesting, reached the breadth limit of nesting, exceeding the provided budget.87 BreadthLimit,88 /// Couldn't find the token owner that is itself a token.89 TokenNotFound,90 /// Tried to nest token under collection contract address, instead of token address91 CantNestTokenUnderCollection,92 }9394 #[pallet::event]95 pub enum Event<T> {96 /// Executed call on behalf of the token.97 Executed(DispatchResult),98 }99100 #[pallet::config]101 pub trait Config: frame_system::Config + pallet_common::Config {102 type WeightInfo: weights::WeightInfo;103 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;104 type RuntimeCall: Parameter105 + UnfilteredDispatchable<RuntimeOrigin = Self::RuntimeOrigin>106 + GetDispatchInfo;107 }108109 #[pallet::pallet]110 pub struct Pallet<T>(_);111112 #[pallet::call]113 impl<T: Config> Pallet<T> {114 // #[pallet::weight({115 // let dispatch_info = call.get_dispatch_info();116117 // (118 // dispatch_info.weight119 // // Cost of dereferencing parent120 // .saturating_add(T::DbWeight::get().reads(2 * *max_depth as Weight))121 // .saturating_add(4000 * *max_depth as Weight),122 // dispatch_info.class)123 // })]124 // pub fn execute(125 // origin: OriginFor<T>,126 // call: Box<<T as Config>::Call>,127 // max_depth: u32,128 // ) -> DispatchResult {129 }130}131132#[derive(PartialEq)]133pub enum Parent<CrossAccountId> {134 /// Token owned by a normal account.135 User(CrossAccountId),136 /// Could not find the token provided as the owner.137 TokenNotFound,138 /// Token owner is another token (still, the target token may not exist).139 Token(CollectionId, TokenId),140}141142impl<T: Config> Pallet<T> {143 /// Find account owning the `token` or a token that the `token` is nested in.144 ///145 /// Returns the enum that have three variants:146 /// - [`User`](crate::Parent<T>::User): Contains account.147 /// - [`Token`](crate::Parent<T>::Token): Contains token id and collection id.148 /// - [`TokenNotFound`](crate::Parent<T>::TokenNotFound): Indicates that parent was not found149 pub fn find_parent(150 collection: CollectionId,151 token: TokenId,152 ) -> Result<Parent<T::CrossAccountId>, DispatchError> {153 // TODO: Reduce cost by not reading collection config154 let handle = match CollectionHandle::try_get(collection) {155 Ok(v) => v,156 Err(_) => return Ok(Parent::TokenNotFound),157 };158 let handle = T::CollectionDispatch::dispatch(handle);159 let handle = handle.as_dyn();160161 Ok(match handle.token_owner(token) {162 Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {163 Some((collection, token)) => Parent::Token(collection, token),164 None => Parent::User(owner),165 },166 None => Parent::TokenNotFound,167 })168 }169170 /// Get the chain of parents of a token in the nesting hierarchy171 ///172 /// Returns an iterator of addresses of the owning tokens and the owning account,173 /// starting from the immediate parent token, ending with the account.174 /// Returns error if cycle is detected.175 pub fn parent_chain(176 mut collection: CollectionId,177 mut token: TokenId,178 ) -> impl Iterator<Item = Result<Parent<T::CrossAccountId>, DispatchError>> {179 let mut finished = false;180 let mut visited = BTreeSet::new();181 visited.insert((collection, token));182 core::iter::from_fn(move || {183 if finished {184 return None;185 }186 let parent = Self::find_parent(collection, token);187 match parent {188 Ok(Parent::Token(new_collection, new_token)) => {189 collection = new_collection;190 token = new_token;191 if !visited.insert((new_collection, new_token)) {192 finished = true;193 return Some(Err(<Error<T>>::OuroborosDetected.into()));194 }195 }196 _ => finished = true,197 }198 Some(parent as Result<_, DispatchError>)199 })200 }201202 /// Try to dereference address, until finding top level owner203 ///204 /// May return token address if parent token not yet exists205 ///206 /// - `budget`: Limit for searching parents in depth.207 pub fn find_topmost_owner(208 collection: CollectionId,209 token: TokenId,210 budget: &dyn Budget,211 ) -> Result<T::CrossAccountId, DispatchError> {212 let owner = Self::parent_chain(collection, token)213 .take_while(|_| budget.consume())214 .find(|p| matches!(p, Ok(Parent::User(_) | Parent::TokenNotFound)))215 .ok_or(<Error<T>>::DepthLimit)??;216217 Ok(match owner {218 Parent::User(v) => v,219 _ => fail!(<Error<T>>::TokenNotFound),220 })221 }222223 /// Find the topmost parent and check that assigning `for_nest` token as a child for224 /// `token` wouldn't create a cycle.225 ///226 /// - `budget`: Limit for searching parents in depth.227 pub fn get_checked_topmost_owner(228 collection: CollectionId,229 token: TokenId,230 for_nest: Option<(CollectionId, TokenId)>,231 budget: &dyn Budget,232 ) -> Result<T::CrossAccountId, DispatchError> {233 // Tried to nest token in itself234 if Some((collection, token)) == for_nest {235 return Err(<Error<T>>::OuroborosDetected.into());236 }237238 for parent in Self::parent_chain(collection, token).take_while(|_| budget.consume()) {239 match parent? {240 // Tried to nest token in chain, which has this token as one of parents241 Parent::Token(collection, token) if Some((collection, token)) == for_nest => {242 return Err(<Error<T>>::OuroborosDetected.into())243 }244 // Token is owned by other user245 Parent::User(user) => return Ok(user),246 Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),247 // Continue parent chain248 Parent::Token(_, _) => {}249 }250 }251252 Err(<Error<T>>::DepthLimit.into())253 }254255 /// Burn token and all of it's nested tokens256 ///257 /// - `self_budget`: Limit for searching children in depth.258 /// - `breadth_budget`: Limit of breadth of searching children.259 pub fn burn_item_recursively(260 from: T::CrossAccountId,261 collection: CollectionId,262 token: TokenId,263 self_budget: &dyn Budget,264 breadth_budget: &dyn Budget,265 ) -> DispatchResultWithPostInfo {266 let handle = <CollectionHandle<T>>::try_get(collection)?;267 let dispatch = T::CollectionDispatch::dispatch(handle);268 let dispatch = dispatch.as_dyn();269 dispatch.burn_item_recursively(from.clone(), token, self_budget, breadth_budget)270 }271272 /// Check if `token` indirectly owned by `user`273 ///274 /// Returns `true` if `user` is `token`'s owner. Or If token is provided as `user` then275 /// check that `user` and `token` have same owner.276 /// Checks that assigning `for_nest` token as a child for `token` wouldn't create a cycle.277 ///278 /// - `budget`: Limit for searching parents in depth.279 pub fn check_indirectly_owned(280 user: T::CrossAccountId,281 collection: CollectionId,282 token: TokenId,283 for_nest: Option<(CollectionId, TokenId)>,284 budget: &dyn Budget,285 ) -> Result<bool, DispatchError> {286 let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {287 Some((collection, token)) => Self::find_topmost_owner(collection, token, budget)?,288 None => user,289 };290291 Self::get_checked_topmost_owner(collection, token, for_nest, budget)292 .map(|indirect_owner| indirect_owner == target_parent)293 }294295 /// Checks that `under` is valid token and that `token_id` could be nested under it296 /// and that `from` is `under`'s owner297 ///298 /// Returns OK if `under` is not a token299 ///300 /// - `nesting_budget`: Limit for searching parents in depth.301 pub fn check_nesting(302 from: T::CrossAccountId,303 under: &T::CrossAccountId,304 collection_id: CollectionId,305 token_id: TokenId,306 nesting_budget: &dyn Budget,307 ) -> DispatchResult {308 Self::try_exec_if_token(under, |collection, parent_id| {309 collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)310 })311 }312313 /// Nests `token_id` under `under` token314 ///315 /// Returns OK if `under` is not a token. Checks that nesting is possible.316 ///317 /// - `nesting_budget`: Limit for searching parents in depth.318 pub fn nest_if_sent_to_token(319 from: T::CrossAccountId,320 under: &T::CrossAccountId,321 collection_id: CollectionId,322 token_id: TokenId,323 nesting_budget: &dyn Budget,324 ) -> DispatchResult {325 Self::try_exec_if_token(under, |collection, parent_id| {326 collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)?;327328 collection.nest(parent_id, (collection_id, token_id));329330 Ok(())331 })332 }333334 /// Nests `token_id` under `owner` token335 ///336 /// Caller should check that nesting wouldn't cause recursion in nesting337 pub fn nest_if_sent_to_token_unchecked(338 owner: &T::CrossAccountId,339 collection_id: CollectionId,340 token_id: TokenId,341 ) {342 Self::exec_if_token(owner, |collection, parent_id| {343 collection.nest(parent_id, (collection_id, token_id))344 });345 }346347 /// Unnests `token_id` from `owner`.348 pub fn unnest_if_nested(349 owner: &T::CrossAccountId,350 collection_id: CollectionId,351 token_id: TokenId,352 ) {353 if let Err(e) = Self::try_exec_if_token(owner, |collection, parent_id| {354 collection.unnest(parent_id, (collection_id, token_id));355 Ok(())356 }) {357 log::warn!("unnest precondition failed: {e:?}")358 }359 }360361 /// # Panics362 /// If [`Self::try_exec_if_token`] fails363 fn exec_if_token(364 account: &T::CrossAccountId,365 action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId),366 ) {367 Self::try_exec_if_token(account, |collection, id| {368 action(collection, id);369 Ok(())370 })371 .unwrap();372 }373374 /// If `account` is a token address, execute `action` providing found collection as an argument375 /// Token may not exist, it is expected it will be checked in the callback.376 fn try_exec_if_token(377 account: &T::CrossAccountId,378 action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult,379 ) -> DispatchResult {380 if is_collection(&account.as_eth()) {381 fail!(<Error<T>>::CantNestTokenUnderCollection);382 }383 let Some((collection, token)) = T::CrossTokenAddressMapping::address_to_token(account) else {384 return Ok(())385 };386387 let handle = <CollectionHandle<T>>::try_get(collection)?;388389 let dispatch = T::CollectionDispatch::dispatch(handle);390 let dispatch = dispatch.as_dyn();391392 action(dispatch, token)393 }394}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//! # Structure Pallet18//!19//! The Structure pallet provides functionality for handling tokens nesting an unnesting.20//!21//! - [`Config`]22//! - [`Pallet`]23//!24//! ## Overview25//!26//! The Structure pallet provides functions for:27//!28//! - Searching for token parents, children and owners. Actual implementation of searching for29//! parent/child is done by pallets corresponding to token's collection type.30//! - Nesting and unnesting tokens. Actual implementation of nesting is done by pallets corresponding31//! to token's collection type.32//!33//! ### Terminology34//!35//! - **Nesting:** Setting up parent-child relationship between tokens. Nested tokens are inhereting36//! owner from their parent. There could be multiple levels of nesting. Token couldn't be nested in37//! it's child token i.e. parent-child relationship graph shouldn't have38//!39//! - **Parent:** Token that current token is nested in.40//!41//! - **Owner:** Account that owns the token and all nested tokens.42//!43//! ## Interface44//!45//! ### Available Functions46//!47//! - `find_parent` - Find parent of the token. It could be an account or another token.48//! - `parent_chain` - Find chain of parents of the token.49//! - `find_topmost_owner` - Find account or token in the end of the chain of parents.50//! - `check_nesting` - Check if the token could be nested in the other token51//! - `nest_if_sent_to_token` - Nest the token in the other token52//! - `unnest_if_nested` - Unnest the token from the other token5354#![cfg_attr(not(feature = "std"), no_std)]5556use pallet_common::CommonCollectionOperations;57use pallet_common::{erc::CrossAccountId, eth::is_collection};58use sp_std::collections::btree_set::BTreeSet;5960use frame_support::dispatch::{DispatchError, DispatchResult, DispatchResultWithPostInfo};61use frame_support::fail;62pub use pallet::*;63use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};64use up_data_structs::{65 CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget, TokenOwnerError,66};6768#[cfg(feature = "runtime-benchmarks")]69pub mod benchmarking;70pub mod weights;7172pub type SelfWeightOf<T> = <T as crate::Config>::WeightInfo;7374#[frame_support::pallet]75pub mod pallet {76 use frame_support::Parameter;77 use frame_support::dispatch::{GetDispatchInfo, UnfilteredDispatchable};78 use frame_support::pallet_prelude::*;7980 use super::*;8182 #[pallet::error]83 pub enum Error<T> {84 /// While nesting, encountered an already checked account, detecting a loop.85 OuroborosDetected,86 /// While nesting, reached the depth limit of nesting, exceeding the provided budget.87 DepthLimit,88 /// While nesting, reached the breadth limit of nesting, exceeding the provided budget.89 BreadthLimit,90 /// Couldn't find the token owner that is itself a token.91 TokenNotFound,92 /// Tried to nest token under collection contract address, instead of token address93 CantNestTokenUnderCollection,94 }9596 #[pallet::event]97 pub enum Event<T> {98 /// Executed call on behalf of the token.99 Executed(DispatchResult),100 }101102 #[pallet::config]103 pub trait Config: frame_system::Config + pallet_common::Config {104 type WeightInfo: weights::WeightInfo;105 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;106 type RuntimeCall: Parameter107 + UnfilteredDispatchable<RuntimeOrigin = Self::RuntimeOrigin>108 + GetDispatchInfo;109 }110111 #[pallet::pallet]112 pub struct Pallet<T>(_);113114 #[pallet::call]115 impl<T: Config> Pallet<T> {116 // #[pallet::weight({117 // let dispatch_info = call.get_dispatch_info();118119 // (120 // dispatch_info.weight121 // // Cost of dereferencing parent122 // .saturating_add(T::DbWeight::get().reads(2 * *max_depth as Weight))123 // .saturating_add(4000 * *max_depth as Weight),124 // dispatch_info.class)125 // })]126 // pub fn execute(127 // origin: OriginFor<T>,128 // call: Box<<T as Config>::Call>,129 // max_depth: u32,130 // ) -> DispatchResult {131 }132}133134#[derive(PartialEq)]135pub enum Parent<CrossAccountId> {136 /// Token owned by a normal account.137 User(CrossAccountId),138 /// Could not find the token provided as the owner.139 TokenNotFound,140 /// Nested token has multiple owners.141 MultipleOwners,142 /// Token owner is another token (still, the target token may not exist).143 Token(CollectionId, TokenId),144}145146impl<T: Config> Pallet<T> {147 /// Find account owning the `token` or a token that the `token` is nested in.148 ///149 /// Returns the enum that have three variants:150 /// - [`User`](crate::Parent<T>::User): Contains account.151 /// - [`Token`](crate::Parent<T>::Token): Contains token id and collection id.152 /// - [`TokenNotFound`](crate::Parent<T>::TokenNotFound): Indicates that parent was not found153 pub fn find_parent(154 collection: CollectionId,155 token: TokenId,156 ) -> Result<Parent<T::CrossAccountId>, DispatchError> {157 // TODO: Reduce cost by not reading collection config158 let handle = match CollectionHandle::try_get(collection) {159 Ok(v) => v,160 Err(_) => return Ok(Parent::TokenNotFound),161 };162 let handle = T::CollectionDispatch::dispatch(handle);163 let handle = handle.as_dyn();164165 Ok(match handle.token_owner(token) {166 Ok(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {167 Some((collection, token)) => Parent::Token(collection, token),168 None => Parent::User(owner),169 },170 Err(TokenOwnerError::MultipleOwners) => Parent::MultipleOwners,171 Err(TokenOwnerError::NotFound) => Parent::TokenNotFound,172 })173 }174175 /// Get the chain of parents of a token in the nesting hierarchy176 ///177 /// Returns an iterator of addresses of the owning tokens and the owning account,178 /// starting from the immediate parent token, ending with the account.179 /// Returns error if cycle is detected.180 pub fn parent_chain(181 mut collection: CollectionId,182 mut token: TokenId,183 ) -> impl Iterator<Item = Result<Parent<T::CrossAccountId>, DispatchError>> {184 let mut finished = false;185 let mut visited = BTreeSet::new();186 visited.insert((collection, token));187 core::iter::from_fn(move || {188 if finished {189 return None;190 }191 let parent = Self::find_parent(collection, token);192 match parent {193 Ok(Parent::Token(new_collection, new_token)) => {194 collection = new_collection;195 token = new_token;196 if !visited.insert((new_collection, new_token)) {197 finished = true;198 return Some(Err(<Error<T>>::OuroborosDetected.into()));199 }200 }201 _ => finished = true,202 }203 Some(parent as Result<_, DispatchError>)204 })205 }206207 /// Try to dereference address, until finding top level owner208 ///209 /// May return token address if parent token not yet exists210 ///211 /// Returns `None` if the token has multiple owners.212 ///213 /// - `budget`: Limit for searching parents in depth.214 pub fn find_topmost_owner(215 collection: CollectionId,216 token: TokenId,217 budget: &dyn Budget,218 ) -> Result<Option<T::CrossAccountId>, DispatchError> {219 let owner = Self::parent_chain(collection, token)220 .take_while(|_| budget.consume())221 .find(|p| {222 matches!(223 p,224 Ok(Parent::User(_) | Parent::TokenNotFound | Parent::MultipleOwners)225 )226 })227 .ok_or(<Error<T>>::DepthLimit)??;228229 Ok(match owner {230 Parent::User(v) => Some(v),231 Parent::MultipleOwners => None,232 _ => fail!(<Error<T>>::TokenNotFound),233 })234 }235236 /// Find the topmost parent and check that assigning `for_nest` token as a child for237 /// `token` wouldn't create a cycle.238 ///239 /// Returns `None` if the token has multiple owners.240 ///241 /// - `budget`: Limit for searching parents in depth.242 pub fn get_checked_topmost_owner(243 collection: CollectionId,244 token: TokenId,245 for_nest: Option<(CollectionId, TokenId)>,246 budget: &dyn Budget,247 ) -> Result<Option<T::CrossAccountId>, DispatchError> {248 // Tried to nest token in itself249 if Some((collection, token)) == for_nest {250 return Err(<Error<T>>::OuroborosDetected.into());251 }252253 for parent in Self::parent_chain(collection, token).take_while(|_| budget.consume()) {254 match parent? {255 // Tried to nest token in chain, which has this token as one of parents256 Parent::Token(collection, token) if Some((collection, token)) == for_nest => {257 return Err(<Error<T>>::OuroborosDetected.into())258 }259 // Token is owned by other user260 Parent::User(user) => return Ok(Some(user)),261 Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),262 Parent::MultipleOwners => return Ok(None),263 // Continue parent chain264 Parent::Token(_, _) => {}265 }266 }267268 Err(<Error<T>>::DepthLimit.into())269 }270271 /// Burn token and all of it's nested tokens272 ///273 /// - `self_budget`: Limit for searching children in depth.274 /// - `breadth_budget`: Limit of breadth of searching children.275 pub fn burn_item_recursively(276 from: T::CrossAccountId,277 collection: CollectionId,278 token: TokenId,279 self_budget: &dyn Budget,280 breadth_budget: &dyn Budget,281 ) -> DispatchResultWithPostInfo {282 let handle = <CollectionHandle<T>>::try_get(collection)?;283 let dispatch = T::CollectionDispatch::dispatch(handle);284 let dispatch = dispatch.as_dyn();285 dispatch.burn_item_recursively(from.clone(), token, self_budget, breadth_budget)286 }287288 /// Check if `token` indirectly owned by `user`289 ///290 /// Returns `true` if `user` is `token`'s owner. Or If token is provided as `user` then291 /// check that `user` and `token` have same owner.292 /// Checks that assigning `for_nest` token as a child for `token` wouldn't create a cycle.293 ///294 /// - `budget`: Limit for searching parents in depth.295 pub fn check_indirectly_owned(296 user: T::CrossAccountId,297 collection: CollectionId,298 token: TokenId,299 for_nest: Option<(CollectionId, TokenId)>,300 budget: &dyn Budget,301 ) -> Result<bool, DispatchError> {302 let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {303 Some((collection, token)) => match Self::find_topmost_owner(collection, token, budget)?304 {305 Some(topmost_owner) => topmost_owner,306 None => return Ok(false),307 },308 None => user,309 };310311 Self::get_checked_topmost_owner(collection, token, for_nest, budget).map(|indirect_owner| {312 indirect_owner.map_or(false, |indirect_owner| indirect_owner == target_parent)313 })314 }315316 /// Checks that `under` is valid token and that `token_id` could be nested under it317 /// and that `from` is `under`'s owner318 ///319 /// Returns OK if `under` is not a token320 ///321 /// - `nesting_budget`: Limit for searching parents in depth.322 pub fn check_nesting(323 from: T::CrossAccountId,324 under: &T::CrossAccountId,325 collection_id: CollectionId,326 token_id: TokenId,327 nesting_budget: &dyn Budget,328 ) -> DispatchResult {329 Self::try_exec_if_token(under, |collection, parent_id| {330 collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)331 })332 }333334 /// Nests `token_id` under `under` token335 ///336 /// Returns OK if `under` is not a token. Checks that nesting is possible.337 ///338 /// - `nesting_budget`: Limit for searching parents in depth.339 pub fn nest_if_sent_to_token(340 from: T::CrossAccountId,341 under: &T::CrossAccountId,342 collection_id: CollectionId,343 token_id: TokenId,344 nesting_budget: &dyn Budget,345 ) -> DispatchResult {346 Self::try_exec_if_token(under, |collection, parent_id| {347 collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)?;348349 collection.nest(parent_id, (collection_id, token_id));350351 Ok(())352 })353 }354355 /// Nests `token_id` under `owner` token356 ///357 /// Caller should check that nesting wouldn't cause recursion in nesting358 pub fn nest_if_sent_to_token_unchecked(359 owner: &T::CrossAccountId,360 collection_id: CollectionId,361 token_id: TokenId,362 ) {363 Self::exec_if_token(owner, |collection, parent_id| {364 collection.nest(parent_id, (collection_id, token_id))365 });366 }367368 /// Unnests `token_id` from `owner`.369 pub fn unnest_if_nested(370 owner: &T::CrossAccountId,371 collection_id: CollectionId,372 token_id: TokenId,373 ) {374 if let Err(e) = Self::try_exec_if_token(owner, |collection, parent_id| {375 collection.unnest(parent_id, (collection_id, token_id));376 Ok(())377 }) {378 log::warn!("unnest precondition failed: {e:?}")379 }380 }381382 /// # Panics383 /// If [`Self::try_exec_if_token`] fails384 fn exec_if_token(385 account: &T::CrossAccountId,386 action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId),387 ) {388 Self::try_exec_if_token(account, |collection, id| {389 action(collection, id);390 Ok(())391 })392 .unwrap();393 }394395 /// If `account` is a token address, execute `action` providing found collection as an argument396 /// Token may not exist, it is expected it will be checked in the callback.397 fn try_exec_if_token(398 account: &T::CrossAccountId,399 action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult,400 ) -> DispatchResult {401 if is_collection(&account.as_eth()) {402 fail!(<Error<T>>::CantNestTokenUnderCollection);403 }404 let Some((collection, token)) = T::CrossTokenAddressMapping::address_to_token(account) else {405 return Ok(())406 };407408 let handle = <CollectionHandle<T>>::try_get(collection)?;409410 let dispatch = T::CollectionDispatch::dispatch(handle);411 let dispatch = dispatch.as_dyn();412413 action(dispatch, token)414 }415}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))