git.delta.rocks / unique-network / refs/commits / 05c459d3caac

difftreelog

fix find_parent

Daniel Shiposha2023-01-19parent: #6a7ab3b.patch.diff
in: master

14 files changed

modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -28,8 +28,8 @@
 use sp_std::{vec, vec::Vec};
 use sp_core::U256;
 use up_data_structs::{
-	AccessMode, CollectionMode, CollectionPermissions, OwnerRestrictedSet, Property,
-	SponsoringRateLimit, SponsorshipState,
+	CollectionMode, CollectionPermissions, OwnerRestrictedSet, Property, SponsoringRateLimit,
+	SponsorshipState,
 };
 
 use crate::{
modifiedpallets/common/src/eth.rsdiffbeforeafterboth
--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -80,10 +80,7 @@
 		if cross_account_id.is_canonical_substrate() {
 			Self::from_sub::<T>(cross_account_id.as_sub())
 		} else {
-			Self {
-				eth: *cross_account_id.as_eth(),
-				sub: Default::default(),
-			}
+			Self::from_eth(*cross_account_id.as_eth())
 		}
 	}
 	/// Creates [`CrossAddress`] from Substrate account.
@@ -97,6 +94,13 @@
 			sub: U256::from_big_endian(account_id.as_ref()),
 		}
 	}
+	/// Creates [`CrossAddress`] from Ethereum account.
+	pub fn from_eth(address: Address) -> Self {
+		Self {
+			eth: address,
+			sub: Default::default(),
+		}
+	}
 	/// Converts [`CrossAddress`] to `CrossAccountId`.
 	pub fn into_sub_cross_account<T>(&self) -> evm_coder::execution::Result<T::CrossAccountId>
 	where
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -100,6 +100,7 @@
 	PropertyValue,
 	PropertyPermission,
 	PropertiesError,
+	TokenOwnerError,
 	PropertyKeyPermission,
 	TokenData,
 	TrySetProperty,
@@ -2134,7 +2135,7 @@
 	/// Get the owner of the token.
 	///
 	/// * `token` - The token for which you need to find out the owner.
-	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;
+	fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;
 
 	/// Returns 10 tokens owners in no particular order.
 	///
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- 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
62pub use pallet::*;62pub use pallet::*;
63use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};63use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};
64use up_data_structs::{CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget};64use up_data_structs::{
65 CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget, TokenOwnerError,
66};
6567
66#[cfg(feature = "runtime-benchmarks")]68#[cfg(feature = "runtime-benchmarks")]
135 User(CrossAccountId),137 User(CrossAccountId),
136 /// Could not find the token provided as the owner.138 /// Could not find the token provided as the owner.
137 TokenNotFound,139 TokenNotFound,
140 /// Nested token has multiple owners.
141 MultipleOwners,
138 /// Token owner is another token (still, the target token may not exist).142 /// Token owner is another token (still, the target token may not exist).
139 Token(CollectionId, TokenId),143 Token(CollectionId, TokenId),
140}144}
159 let handle = handle.as_dyn();163 let handle = handle.as_dyn();
160164
161 Ok(match handle.token_owner(token) {165 Ok(match handle.token_owner(token) {
162 Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {166 Ok(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {
163 Some((collection, token)) => Parent::Token(collection, token),167 Some((collection, token)) => Parent::Token(collection, token),
164 None => Parent::User(owner),168 None => Parent::User(owner),
165 },169 },
170 Err(TokenOwnerError::MultipleOwners) => Parent::MultipleOwners,
166 None => Parent::TokenNotFound,171 Err(TokenOwnerError::NotFound) => Parent::TokenNotFound,
167 })172 })
168 }173 }
169174
202 /// Try to dereference address, until finding top level owner207 /// Try to dereference address, until finding top level owner
203 ///208 ///
204 /// May return token address if parent token not yet exists209 /// May return token address if parent token not yet exists
210 ///
211 /// Returns `None` if the token has multiple owners.
205 ///212 ///
206 /// - `budget`: Limit for searching parents in depth.213 /// - `budget`: Limit for searching parents in depth.
207 pub fn find_topmost_owner(214 pub fn find_topmost_owner(
208 collection: CollectionId,215 collection: CollectionId,
209 token: TokenId,216 token: TokenId,
210 budget: &dyn Budget,217 budget: &dyn Budget,
211 ) -> Result<T::CrossAccountId, DispatchError> {218 ) -> Result<Option<T::CrossAccountId>, DispatchError> {
212 let owner = Self::parent_chain(collection, token)219 let owner = Self::parent_chain(collection, token)
213 .take_while(|_| budget.consume())220 .take_while(|_| budget.consume())
214 .find(|p| matches!(p, Ok(Parent::User(_) | Parent::TokenNotFound)))221 .find(|p| {
222 matches!(
223 p,
224 Ok(Parent::User(_) | Parent::TokenNotFound | Parent::MultipleOwners)
225 )
226 })
215 .ok_or(<Error<T>>::DepthLimit)??;227 .ok_or(<Error<T>>::DepthLimit)??;
216228
217 Ok(match owner {229 Ok(match owner {
218 Parent::User(v) => v,230 Parent::User(v) => Some(v),
231 Parent::MultipleOwners => None,
219 _ => fail!(<Error<T>>::TokenNotFound),232 _ => fail!(<Error<T>>::TokenNotFound),
220 })233 })
221 }234 }
222235
223 /// Find the topmost parent and check that assigning `for_nest` token as a child for236 /// Find the topmost parent and check that assigning `for_nest` token as a child for
224 /// `token` wouldn't create a cycle.237 /// `token` wouldn't create a cycle.
238 ///
239 /// Returns `None` if the token has multiple owners.
225 ///240 ///
226 /// - `budget`: Limit for searching parents in depth.241 /// - `budget`: Limit for searching parents in depth.
227 pub fn get_checked_topmost_owner(242 pub fn get_checked_topmost_owner(
228 collection: CollectionId,243 collection: CollectionId,
229 token: TokenId,244 token: TokenId,
230 for_nest: Option<(CollectionId, TokenId)>,245 for_nest: Option<(CollectionId, TokenId)>,
231 budget: &dyn Budget,246 budget: &dyn Budget,
232 ) -> Result<T::CrossAccountId, DispatchError> {247 ) -> Result<Option<T::CrossAccountId>, DispatchError> {
233 // Tried to nest token in itself248 // Tried to nest token in itself
234 if Some((collection, token)) == for_nest {249 if Some((collection, token)) == for_nest {
235 return Err(<Error<T>>::OuroborosDetected.into());250 return Err(<Error<T>>::OuroborosDetected.into());
242 return Err(<Error<T>>::OuroborosDetected.into())257 return Err(<Error<T>>::OuroborosDetected.into())
243 }258 }
244 // Token is owned by other user259 // Token is owned by other user
245 Parent::User(user) => return Ok(user),260 Parent::User(user) => return Ok(Some(user)),
246 Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),261 Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),
262 Parent::MultipleOwners => return Ok(None),
247 // Continue parent chain263 // Continue parent chain
248 Parent::Token(_, _) => {}264 Parent::Token(_, _) => {}
249 }265 }
284 budget: &dyn Budget,300 budget: &dyn Budget,
285 ) -> Result<bool, DispatchError> {301 ) -> Result<bool, DispatchError> {
286 let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {302 let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {
287 Some((collection, token)) => Self::find_topmost_owner(collection, token, budget)?,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 },
288 None => user,308 None => user,
289 };309 };
290310
291 Self::get_checked_topmost_owner(collection, token, for_nest, budget)311 Self::get_checked_topmost_owner(collection, token, for_nest, budget).map(|indirect_owner| {
292 .map(|indirect_owner| indirect_owner == target_parent)312 indirect_owner.map_or(false, |indirect_owner| indirect_owner == target_parent)
313 })
293 }314 }
294315
295 /// Checks that `under` is valid token and that `token_id` could be nested under it316 /// 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))