git.delta.rocks / unique-network / refs/commits / b08cb26894de

difftreelog

Merge pull request #355 from UniqueNetwork/feature/nft-children

Yaroslav Bolyukin2022-05-30parents: #764dfd5 #8cbbfc6.patch.diff
in: master
Structure children map

12 files changed

modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -353,6 +353,8 @@
 		MustBeTokenOwner,
 		/// No permission to perform action
 		NoPermission,
+		/// Destroying only empty collections is allowed
+		CantDestroyNotEmptyCollection,
 		/// Collection is not in mint mode.
 		PublicMintingNotAllowed,
 		/// Address is not in allow list.
@@ -1268,6 +1270,18 @@
 		budget: &dyn Budget,
 	) -> DispatchResult;
 
+	fn nest(
+		&self,
+		under: TokenId,
+		to_nest: (CollectionId, TokenId)
+	);
+
+	fn unnest(
+		&self,
+		under: TokenId,
+		to_nest: (CollectionId, TokenId)
+	);
+
 	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;
 	fn collection_tokens(&self) -> Vec<TokenId>;
 	fn token_exists(&self, token: TokenId) -> bool;
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -298,6 +298,18 @@
 		fail!(<Error<T>>::FungibleDisallowsNesting)
 	}
 
+	fn nest(
+		&self,
+		_under: TokenId,
+		_to_nest: (CollectionId, TokenId)
+	) {}
+
+	fn unnest(
+		&self,
+		_under: TokenId,
+		_to_nest: (CollectionId, TokenId)
+	) {}
+
 	fn collection_tokens(&self) -> Vec<TokenId> {
 		vec![TokenId::default()]
 	}
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -25,8 +25,8 @@
 	budget::Budget,
 };
 use pallet_common::{
-	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, CollectionHandle,
-	dispatch::CollectionDispatch, eth::collection_id_to_address,
+	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
+	eth::collection_id_to_address,
 };
 use pallet_evm::Pallet as PalletEvm;
 use pallet_structure::Pallet as PalletStructure;
@@ -145,6 +145,10 @@
 	) -> DispatchResult {
 		let id = collection.id;
 
+		if Self::collection_has_tokens(id) {
+			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());
+		}
+
 		// =========
 
 		PalletCommon::destroy_collection(collection.0, sender)?;
@@ -155,6 +159,10 @@
 		Ok(())
 	}
 
+	fn collection_has_tokens(collection_id: CollectionId) -> bool {
+		<TotalSupply<T>>::get(collection_id) != 0
+	}
+
 	pub fn burn(
 		collection: &FungibleHandle<T>,
 		owner: &T::CrossAccountId,
@@ -176,6 +184,11 @@
 
 		if balance == 0 {
 			<Balance<T>>::remove((collection.id, owner));
+			<PalletStructure<T>>::unnest_if_nested(
+				owner,
+				collection.id,
+				TokenId::default()
+			);
 		} else {
 			<Balance<T>>::insert((collection.id, owner), balance);
 		}
@@ -229,25 +242,25 @@
 			None
 		};
 
-		if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {
-			let handle = <CollectionHandle<T>>::try_get(target.0)?;
-			let dispatch = T::CollectionDispatch::dispatch(handle);
-			let dispatch = dispatch.as_dyn();
+		// =========
 
-			dispatch.check_nesting(
-				from.clone(),
-				(collection.id, TokenId::default()),
-				target.1,
-				nesting_budget,
-			)?;
-		}
+		<PalletStructure<T>>::nest_if_sent_to_token(
+			from.clone(),
+			to,
+			collection.id,
+			TokenId::default(),
+			nesting_budget
+		)?;
 
-		// =========
-
 		if let Some(balance_to) = balance_to {
 			// from != to
 			if balance_from == 0 {
 				<Balance<T>>::remove((collection.id, from));
+				<PalletStructure<T>>::unnest_if_nested(
+					from,
+					collection.id,
+					TokenId::default()
+				);
 			} else {
 				<Balance<T>>::insert((collection.id, from), balance_from);
 			}
@@ -306,18 +319,13 @@
 		}
 
 		for (to, _) in balances.iter() {
-			if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {
-				let handle = <CollectionHandle<T>>::try_get(target.0)?;
-				let dispatch = T::CollectionDispatch::dispatch(handle);
-				let dispatch = dispatch.as_dyn();
-
-				dispatch.check_nesting(
-					sender.clone(),
-					(collection.id, TokenId::default()),
-					target.1,
-					nesting_budget,
-				)?;
-			}
+			<PalletStructure<T>>::check_nesting(
+				sender.clone(),
+				to,
+				collection.id,
+				TokenId::default(),
+				nesting_budget,
+			)?;
 		}
 
 		// =========
@@ -325,7 +333,7 @@
 		<TotalSupply<T>>::insert(collection.id, total_supply);
 		for (user, amount) in balances {
 			<Balance<T>>::insert((collection.id, &user), amount);
-
+			<PalletStructure<T>>::nest_if_sent_to_token_unchecked(&user, collection.id, TokenId::default());
 			<PalletEvm<T>>::deposit_log(
 				ERC20Events::Transfer {
 					from: H160::default(),
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -353,6 +353,22 @@
 		<Pallet<T>>::check_nesting(self, sender, from, under, budget)
 	}
 
+	fn nest(
+		&self,
+		under: TokenId,
+		to_nest: (CollectionId, TokenId)
+	) {
+		<Pallet<T>>::nest((self.id, under), to_nest);
+	}
+
+	fn unnest(
+		&self,
+		under: TokenId,
+		to_unnest: (CollectionId, TokenId)
+	) {
+		<Pallet<T>>::unnest((self.id, under), to_unnest);
+	}
+
 	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
 		<Owned<T>>::iter_prefix((self.id, account))
 			.map(|(id, _)| id)
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -27,7 +27,7 @@
 use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
 use pallet_common::{
 	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,
-	dispatch::CollectionDispatch, eth::collection_id_to_address,
+	eth::collection_id_to_address,
 };
 use pallet_structure::Pallet as PalletStructure;
 use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
@@ -76,6 +76,8 @@
 		NotNonfungibleDataUsedToMintFungibleCollectionToken,
 		/// Used amount > 1 with NFT
 		NonfungibleItemsHaveNoAmount,
+		/// Unable to burn NFT with children
+		CantBurnNftWithChildren,
 	}
 
 	#[pallet::config]
@@ -127,7 +129,20 @@
 		QueryKind = ValueQuery,
 	>;
 
+	/// Used to enumerate token's children
 	#[pallet::storage]
+	#[pallet::getter(fn token_children)]
+	pub type TokenChildren<T: Config> = StorageNMap<
+		Key = (
+			Key<Twox64Concat, CollectionId>,
+			Key<Twox64Concat, TokenId>,
+			Key<Twox64Concat, (CollectionId, TokenId)>,
+		),
+		Value = bool,
+		QueryKind = ValueQuery,
+	>;
+
+	#[pallet::storage]
 	pub type AccountBalance<T: Config> = StorageNMap<
 		Key = (
 			Key<Twox64Concat, CollectionId>,
@@ -277,11 +292,16 @@
 	) -> DispatchResult {
 		let id = collection.id;
 
+		if Self::collection_has_tokens(id) {
+			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());
+		}
+
 		// =========
 
 		PalletCommon::destroy_collection(collection.0, sender)?;
 
 		<TokenData<T>>::remove_prefix((id,), None);
+		<TokenChildren<T>>::remove_prefix((id,), None);
 		<Owned<T>>::remove_prefix((id,), None);
 		<TokensMinted<T>>::remove(id);
 		<TokensBurnt<T>>::remove(id);
@@ -307,6 +327,10 @@
 			collection.check_allowlist(sender)?;
 		}
 
+		if Self::token_has_children(collection.id, token) {
+			return Err(<Error<T>>::CantBurnNftWithChildren.into());
+		}
+
 		let burnt = <TokensBurnt<T>>::get(collection.id)
 			.checked_add(1)
 			.ok_or(ArithmeticError::Overflow)?;
@@ -315,13 +339,20 @@
 			.checked_sub(1)
 			.ok_or(ArithmeticError::Overflow)?;
 
+		// =========
+
 		if balance == 0 {
 			<AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));
 		} else {
 			<AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);
 		}
-		// =========
 
+		<PalletStructure<T>>::unnest_if_nested(
+			&token_data.owner,
+			collection.id,
+			token
+		);
+
 		<Owned<T>>::remove((collection.id, &token_data.owner, token));
 		<TokensBurnt<T>>::insert(collection.id, burnt);
 		<TokenData<T>>::remove((collection.id, token));
@@ -553,20 +584,21 @@
 			None
 		};
 
-		if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {
-			let handle = <CollectionHandle<T>>::try_get(target.0)?;
-			let dispatch = T::CollectionDispatch::dispatch(handle);
-			let dispatch = dispatch.as_dyn();
+		<PalletStructure<T>>::nest_if_sent_to_token(
+			from.clone(),
+			to,
+			collection.id,
+			token,
+			nesting_budget
+		)?;
 
-			dispatch.check_nesting(
-				from.clone(),
-				(collection.id, token),
-				target.1,
-				nesting_budget,
-			)?;
-		}
+		// =========
 
-		// =========
+		<PalletStructure<T>>::unnest_if_nested(
+			from,
+			collection.id,
+			token
+		);
 
 		<TokenData<T>>::insert(
 			(collection.id, token),
@@ -653,17 +685,14 @@
 
 		for (i, data) in data.iter().enumerate() {
 			let token = TokenId(first_token + i as u32 + 1);
-			if let Some(target) = T::CrossTokenAddressMapping::address_to_token(&data.owner) {
-				let handle = <CollectionHandle<T>>::try_get(target.0)?;
-				let dispatch = T::CollectionDispatch::dispatch(handle);
-				let dispatch = dispatch.as_dyn();
-				dispatch.check_nesting(
-					sender.clone(),
-					(collection.id, token),
-					target.1,
-					nesting_budget,
-				)?;
-			}
+
+			<PalletStructure<T>>::check_nesting(
+				sender.clone(),
+				&data.owner,
+				collection.id,
+				token,
+				nesting_budget,
+			)?;
 		}
 
 		// =========
@@ -680,6 +709,8 @@
 					},
 				);
 
+				<PalletStructure<T>>::nest_if_sent_to_token_unchecked(&data.owner, collection.id, TokenId(token));
+
 				if let Err(e) = Self::set_token_properties(
 					collection,
 					sender,
@@ -927,6 +958,33 @@
 		Ok(())
 	}
 
+	fn nest(
+		under: (CollectionId, TokenId),
+		to_nest: (CollectionId, TokenId),
+	) {
+		<TokenChildren<T>>::insert(
+			(under.0, under.1, (to_nest.0, to_nest.1)),
+			true
+		);
+	}
+
+	fn unnest(
+		under: (CollectionId, TokenId),
+		to_unnest: (CollectionId, TokenId),
+	) {
+		<TokenChildren<T>>::remove(
+			(under.0, under.1, to_unnest)
+		);
+	}
+
+	fn collection_has_tokens(collection_id: CollectionId) -> bool {
+		<TokenData<T>>::iter_prefix((collection_id,)).next().is_some()
+	}
+
+	fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {
+		<TokenChildren<T>>::iter_prefix((collection_id, token_id)).next().is_some()
+	}
+
 	/// Delegated to `create_multiple_items`
 	pub fn create_item(
 		collection: &NonfungibleHandle<T>,
modifiedpallets/proxy-rmrk-core/src/misc.rsdiffbeforeafterboth
--- a/pallets/proxy-rmrk-core/src/misc.rs
+++ b/pallets/proxy-rmrk-core/src/misc.rs
@@ -26,6 +26,18 @@
     }
 }
 
+pub trait RmrkRebind<T, S> {
+    fn rebind(&self) -> BoundedVec<u8, S>;
+}
+
+impl<T, S> RmrkRebind<T, S> for BoundedVec<u8, T> where BoundedVec<u8, S>: TryFrom<Vec<u8>> {
+    fn rebind(&self) -> BoundedVec<u8, S> {
+        BoundedVec::<u8, S>::try_from(
+            self.clone().into_inner()
+        ).unwrap_or_default()
+    }
+}
+
 #[derive(Encode, Decode, PartialEq, Eq)]
 pub enum CollectionType {
     Regular,
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -313,6 +313,18 @@
 		fail!(<Error<T>>::RefungibleDisallowsNesting)
 	}
 
+	fn nest(
+		&self,
+		_under: TokenId,
+		_to_nest: (CollectionId, TokenId)
+	) {}
+
+	fn unnest(
+		&self,
+		_under: TokenId,
+		_to_nest: (CollectionId, TokenId)
+	) {}
+
 	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
 		<Owned<T>>::iter_prefix((self.id, account))
 			.map(|(id, _)| id)
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -23,8 +23,7 @@
 };
 use pallet_evm::account::CrossAccountId;
 use pallet_common::{
-	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, CollectionHandle,
-	dispatch::CollectionDispatch,
+	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
 };
 use pallet_structure::Pallet as PalletStructure;
 use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
@@ -211,6 +210,10 @@
 	) -> DispatchResult {
 		let id = collection.id;
 
+		if Self::collection_has_tokens(id) {
+			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());
+		}
+
 		// =========
 
 		PalletCommon::destroy_collection(collection.0, sender)?;
@@ -226,6 +229,10 @@
 		Ok(())
 	}
 
+	fn collection_has_tokens(collection_id: CollectionId) -> bool {
+		<TokenData<T>>::iter_prefix((collection_id,)).next().is_some()
+	}
+
 	pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {
 		let burnt = <TokensBurnt<T>>::get(collection.id)
 			.checked_add(1)
@@ -265,6 +272,7 @@
 			// =========
 
 			<Owned<T>>::remove((collection.id, owner, token));
+			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);
 			<AccountBalance<T>>::insert((collection.id, owner), account_balance);
 			Self::burn_token(collection, token)?;
 			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(
@@ -292,6 +300,7 @@
 
 		if balance == 0 {
 			<Owned<T>>::remove((collection.id, owner, token));
+			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);
 			<Balance<T>>::remove((collection.id, token, owner));
 			<AccountBalance<T>>::insert((collection.id, owner), account_balance);
 		} else {
@@ -372,25 +381,25 @@
 			None
 		};
 
-		if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {
-			let handle = <CollectionHandle<T>>::try_get(target.0)?;
-			let dispatch = T::CollectionDispatch::dispatch(handle);
-			let dispatch = dispatch.as_dyn();
+		// =========
 
-			dispatch.check_nesting(
-				from.clone(),
-				(collection.id, token),
-				target.1,
-				nesting_budget,
-			)?;
-		}
-
-		// =========
+		<PalletStructure<T>>::nest_if_sent_to_token(
+			from.clone(),
+			to,
+			collection.id,
+			token,
+			nesting_budget
+		)?;
 
 		if let Some(balance_to) = balance_to {
 			// from != to
 			if balance_from == 0 {
 				<Balance<T>>::remove((collection.id, token, from));
+				<PalletStructure<T>>::unnest_if_nested(
+					from,
+					collection.id,
+					token
+				);
 			} else {
 				<Balance<T>>::insert((collection.id, token, from), balance_from);
 			}
@@ -488,18 +497,14 @@
 		for (i, token) in data.iter().enumerate() {
 			let token_id = TokenId(first_token_id + i as u32 + 1);
 			for (to, _) in token.users.iter() {
-				if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {
-					let handle = <CollectionHandle<T>>::try_get(target.0)?;
-					let dispatch = T::CollectionDispatch::dispatch(handle);
-					let dispatch = dispatch.as_dyn();
 
-					dispatch.check_nesting(
-						sender.clone(),
-						(collection.id, token_id),
-						target.1,
-						nesting_budget,
-					)?;
-				}
+				<PalletStructure<T>>::check_nesting(
+					sender.clone(),
+					to,
+					collection.id,
+					token_id,
+					nesting_budget,
+				)?;
 			}
 		}
 
@@ -519,12 +524,15 @@
 					const_data: token.const_data,
 				},
 			);
+
 			for (user, amount) in token.users.into_iter() {
 				if amount == 0 {
 					continue;
 				}
 				<Balance<T>>::insert((collection.id, token_id, &user), amount);
 				<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);
+				<PalletStructure<T>>::nest_if_sent_to_token_unchecked(&user, collection.id, TokenId(token_id));
+
 				// TODO: ERC20 transfer event
 				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(
 					collection.id,
modifiedpallets/structure/src/lib.rsdiffbeforeafterboth
--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -1,8 +1,9 @@
 #![cfg_attr(not(feature = "std"), no_std)]
 
+use pallet_common::CommonCollectionOperations;
 use sp_std::collections::btree_set::BTreeSet;
 
-use frame_support::dispatch::DispatchError;
+use frame_support::dispatch::{DispatchError, DispatchResult};
 use frame_support::fail;
 pub use pallet::*;
 use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};
@@ -155,8 +156,8 @@
 		budget: &dyn Budget,
 	) -> Result<bool, DispatchError> {
 		let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {
-			Some((collection, token)) => Parent::Token(collection, token),
-			None => Parent::User(user),
+			Some((collection, token)) => Self::find_topmost_owner(collection, token, budget)?,
+			None => user,
 		};
 
 		// Tried to nest token in itself
@@ -171,10 +172,10 @@
 					return Err(<Error<T>>::OuroborosDetected.into())
 				}
 				// Found needed parent, token is indirecty owned
-				v if v == target_parent => return Ok(true),
+				Parent::User(user) if user == target_parent => return Ok(true),
 				// Token is owned by other user
 				Parent::User(_) => return Ok(false),
-				Parent::TokenNotFound => return Ok(false),
+				Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),
 				// Continue parent chain
 				Parent::Token(_, _) => {}
 			}
@@ -182,4 +183,113 @@
 
 		Err(<Error<T>>::DepthLimit.into())
 	}
+
+	pub fn check_nesting(
+		from: T::CrossAccountId,
+		under: &T::CrossAccountId,
+		collection_id: CollectionId,
+		token_id: TokenId,
+		nesting_budget: &dyn Budget
+	) -> DispatchResult {
+		Self::try_exec_if_owner_is_valid_nft(
+			under,
+			|d, parent_id| d.check_nesting(
+				from,
+				(collection_id, token_id),
+				parent_id,
+				nesting_budget
+			)
+		)
+	}
+
+	pub fn nest_if_sent_to_token(
+		from: T::CrossAccountId,
+		under: &T::CrossAccountId,
+		collection_id: CollectionId,
+		token_id: TokenId,
+		nesting_budget: &dyn Budget
+	) -> DispatchResult {
+		Self::try_exec_if_owner_is_valid_nft(
+			under,
+			|d, parent_id| {
+				d.check_nesting(
+					from,
+					(collection_id, token_id),
+					parent_id,
+					nesting_budget
+				)?;
+
+				d.nest(parent_id, (collection_id, token_id));
+
+				Ok(())
+			}
+		)
+	}
+
+	pub fn nest_if_sent_to_token_unchecked(
+		owner: &T::CrossAccountId,
+		collection_id: CollectionId,
+		token_id: TokenId
+	) {
+		Self::exec_if_owner_is_valid_nft(
+			owner,
+			|d, parent_id| d.nest(
+				parent_id,
+				(collection_id, token_id)
+			)
+		);
+	}
+
+	pub fn unnest_if_nested(
+		owner: &T::CrossAccountId,
+		collection_id: CollectionId,
+		token_id: TokenId
+	) {
+		Self::exec_if_owner_is_valid_nft(
+			owner,
+			|d, parent_id| d.unnest(
+			parent_id,
+			(collection_id, token_id)
+			)
+		);
+	}
+
+	fn exec_if_owner_is_valid_nft(
+		account: &T::CrossAccountId,
+		action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId)
+	) {
+		Self::try_exec_if_owner_is_valid_nft(
+			account,
+			|d, id| {
+				action(d, id);
+				Ok(())
+			}
+		).unwrap();
+	}
+
+	fn try_exec_if_owner_is_valid_nft(
+		account: &T::CrossAccountId,
+		action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult
+	) -> DispatchResult {
+		let account = T::CrossTokenAddressMapping::address_to_token(account);
+
+		if account.is_none() {
+			return Ok(());
+		}
+
+		let account = account.unwrap();
+
+		let handle = <CollectionHandle<T>>::try_get(account.0);
+
+		if handle.is_err() {
+			return Ok(());
+		}
+
+		let handle = handle.unwrap();
+
+		let dispatch = T::CollectionDispatch::dispatch(handle);
+		let dispatch = dispatch.as_dyn();
+
+		action(dispatch, account.1)
+	}
 }
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -55,6 +55,8 @@
 pub mod weights;
 use weights::WeightInfo;
 
+const NESTING_BUDGET: u32 = 5;
+
 decl_error! {
 	/// Error for non-fungible-token module.
 	pub enum Error for Module<T: Config> {
@@ -569,7 +571,7 @@
 		#[transactional]
 		pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResultWithPostInfo {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-			let budget = budget::Value::new(2);
+			let budget = budget::Value::new(NESTING_BUDGET);
 
 			dispatch_call::<T, _>(collection_id, |d| d.create_item(sender, owner, data, &budget))
 		}
@@ -597,7 +599,7 @@
 		pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResultWithPostInfo {
 			ensure!(!items_data.is_empty(), Error::<T>::EmptyArgument);
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-			let budget = budget::Value::new(2);
+			let budget = budget::Value::new(NESTING_BUDGET);
 
 			dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items(sender, owner, items_data, &budget))
 		}
@@ -678,7 +680,7 @@
 		#[transactional]
 		pub fn create_multiple_items_ex(origin, collection_id: CollectionId, data: CreateItemExData<T::CrossAccountId>) -> DispatchResultWithPostInfo {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-			let budget = budget::Value::new(2);
+			let budget = budget::Value::new(NESTING_BUDGET);
 
 			dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items_ex(sender, data, &budget))
 		}
@@ -758,7 +760,7 @@
 		#[transactional]
 		pub fn burn_from(origin, collection_id: CollectionId, from: T::CrossAccountId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-			let budget = budget::Value::new(2);
+			let budget = budget::Value::new(NESTING_BUDGET);
 
 			dispatch_call::<T, _>(collection_id, |d| d.burn_from(sender, from, item_id, value, &budget))
 		}
@@ -790,7 +792,7 @@
 		#[transactional]
 		pub fn transfer(origin, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-			let budget = budget::Value::new(2);
+			let budget = budget::Value::new(NESTING_BUDGET);
 
 			dispatch_call::<T, _>(collection_id, |d| d.transfer(sender, recipient, item_id, value, &budget))
 		}
@@ -841,7 +843,7 @@
 		#[transactional]
 		pub fn transfer_from(origin, from: T::CrossAccountId, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResultWithPostInfo {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-			let budget = budget::Value::new(2);
+			let budget = budget::Value::new(NESTING_BUDGET);
 
 			dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value, &budget))
 		}
modifiedruntime/common/src/runtime_apis.rsdiffbeforeafterboth
before · runtime/common/src/runtime_apis.rs
1#[macro_export]2macro_rules! impl_common_runtime_apis {3    (4        $(5            #![custom_apis]67            $($custom_apis:tt)+8        )?9    ) => {10        impl_runtime_apis! {11            $($($custom_apis)+)?1213            impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId> for Runtime {14                fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {15                    dispatch_unique_runtime!(collection.account_tokens(account))16                }17                fn collection_tokens(collection: CollectionId) -> Result<Vec<TokenId>, DispatchError> {18                    dispatch_unique_runtime!(collection.collection_tokens())19                }20                fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {21                    dispatch_unique_runtime!(collection.token_exists(token))22                }2324                fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {25                    dispatch_unique_runtime!(collection.token_owner(token))26                }27                fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {28                    let budget = up_data_structs::budget::Value::new(5);2930                    Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))31                }3233                fn collection_properties(34                    collection: CollectionId,35                    keys: Option<Vec<Vec<u8>>>36                ) -> Result<Vec<Property>, DispatchError> {37                    let keys = keys.map(38                        |keys| Common::bytes_keys_to_property_keys(keys)39                    ).transpose()?;4041                    Common::filter_collection_properties(collection, keys)42                }4344                fn token_properties(45                    collection: CollectionId,46                    token_id: TokenId,47                    keys: Option<Vec<Vec<u8>>>48                ) -> Result<Vec<Property>, DispatchError> {49                    let keys = keys.map(50                        |keys| Common::bytes_keys_to_property_keys(keys)51                    ).transpose()?;5253                    dispatch_unique_runtime!(collection.token_properties(token_id, keys))54                }5556                fn property_permissions(57                    collection: CollectionId,58                    keys: Option<Vec<Vec<u8>>>59                ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {60                    let keys = keys.map(61                        |keys| Common::bytes_keys_to_property_keys(keys)62                    ).transpose()?;6364                    Common::filter_property_permissions(collection, keys)65                }6667                fn token_data(68                    collection: CollectionId,69                    token_id: TokenId,70                    keys: Option<Vec<Vec<u8>>>71                ) -> Result<TokenData<CrossAccountId>, DispatchError> {72                    let token_data = TokenData {73                        properties: Self::token_properties(collection, token_id, keys)?,74                        owner: Self::token_owner(collection, token_id)?75                    };7677                    Ok(token_data)78                }7980                fn total_supply(collection: CollectionId) -> Result<u32, DispatchError> {81                    dispatch_unique_runtime!(collection.total_supply())82                }83                fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {84                    dispatch_unique_runtime!(collection.account_balance(account))85                }86                fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {87                    dispatch_unique_runtime!(collection.balance(account, token))88                }89                fn allowance(90                    collection: CollectionId,91                    sender: CrossAccountId,92                    spender: CrossAccountId,93                    token: TokenId,94                ) -> Result<u128, DispatchError> {95                    dispatch_unique_runtime!(collection.allowance(sender, spender, token))96                }9798                fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {99                    Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))100                }101                fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {102                    Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))103                }104                fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {105                    Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))106                }107                fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {108                    dispatch_unique_runtime!(collection.last_token_id())109                }110                fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>, DispatchError> {111                    Ok(<pallet_common::Pallet<Runtime>>::rpc_collection(collection))112                }113                fn collection_stats() -> Result<CollectionStats, DispatchError> {114                    Ok(<pallet_common::Pallet<Runtime>>::collection_stats())115                }116                fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>, DispatchError> {117                    Ok(<$crate::sponsoring::UniqueSponsorshipPredict<Runtime> as118                            $crate::sponsoring::SponsorshipPredict<Runtime>>::predict(119                        collection,120                        account,121                        token))122                }123124                fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {125                    Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))126                }127            }128129            impl rmrk_rpc::RmrkApi<130                Block,131                AccountId,132                RmrkCollectionInfo<AccountId>,133                RmrkInstanceInfo<AccountId>,134                RmrkResourceInfo,135                RmrkPropertyInfo,136                RmrkBaseInfo<AccountId>,137                RmrkPartType,138                RmrkTheme139            > for Runtime {140                fn last_collection_idx() -> Result<RmrkCollectionId, DispatchError> {141                    Ok(RmrkCore::last_collection_idx())142                }143144                fn collection_by_id(collection_id: RmrkCollectionId) -> Result<Option<RmrkCollectionInfo<AccountId>>, DispatchError> {145                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkDecode}};146147                    let collection_id = CollectionId(collection_id);148                    let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Regular) {149                        Ok(c) => c,150                        Err(_) => return Ok(None),151                    };152153                    let nfts_count = dispatch_unique_runtime!(collection_id.total_supply())?;154155                    Ok(Some(RmrkCollectionInfo {156                        issuer: collection.owner.clone(),157                        metadata: RmrkCore::get_collection_property(collection_id, RmrkProperty::Metadata)?.decode_or_default(),158                        max: collection.limits.token_limit,159                        symbol: collection.token_prefix.decode_or_default(),160                        nfts_count161                    }))162                }163164                fn nft_by_id(collection_id: RmrkCollectionId, nft_by_id: RmrkNftId) -> Result<Option<RmrkInstanceInfo<AccountId>>, DispatchError> {165                    use up_data_structs::mapping::TokenAddressMapping;166                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::RmrkDecode};167168                    let collection_id = CollectionId(collection_id);169                    let nft_id = TokenId(nft_by_id);170                    if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(None); }171172                    let owner = match dispatch_unique_runtime!(collection_id.token_owner(nft_id))? {173                        Some(owner) => match <Runtime as pallet_common::Config>::CrossTokenAddressMapping::address_to_token(&owner) {174                            Some((col, tok)) => RmrkAccountIdOrCollectionNftTuple::CollectionAndNftTuple(col.0, tok.0),175                            None => RmrkAccountIdOrCollectionNftTuple::AccountId(owner.as_sub().clone())176                        },177                        None => return Ok(None)178                    };179180                    let allowance = pallet_nonfungible::Allowance::<Runtime>::get((collection_id, nft_id));181182                    Ok(Some(RmrkInstanceInfo {183                        owner: owner,184                        royalty: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::RoyaltyInfo)?.decode_or_default(),185                        metadata: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::Metadata)?.decode_or_default(),186                        equipped: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::Equipped)?.decode_or_default(),187                        pending: allowance.is_some(),188                    }))189                }190191                fn account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Result<Vec<RmrkNftId>, DispatchError> {192                    use pallet_proxy_rmrk_core::misc::CollectionType;193194                    let cross_account_id = CrossAccountId::from_sub(account_id);195                    let collection_id = CollectionId(collection_id);196                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Regular).is_err() { return Ok(Vec::new()); }197198                    Ok(199                        dispatch_unique_runtime!(collection_id.account_tokens(cross_account_id))?200                            .into_iter()201                            .map(|token| token.0)202                            .collect()203                    )204                }205206                fn nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkNftChild>, DispatchError> {207                    use up_data_structs::mapping::TokenAddressMapping;208209                    let collection_id = CollectionId(collection_id);210                    let nft_id = TokenId(nft_id);211                    if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(Vec::new()); }212213                    let cross_account_id = CrossAccountId::from_eth(214                        EvmTokenAddressMapping::token_to_address(collection_id, nft_id)215                    );216217                    Ok(218                        pallet_nonfungible::Owned::<Runtime>::iter_prefix((collection_id, cross_account_id))219                            .map(|(child_id, _)| RmrkNftChild {220                                collection_id: collection_id.0, // todo make sure they're always from this collection // spoiler: they're not221                                nft_id: child_id.0,222                            }).collect()223                    )224                }225226                fn collection_properties(collection_id: RmrkCollectionId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {227                    use pallet_proxy_rmrk_core::misc::CollectionType;228229                    let collection_id = CollectionId(collection_id);230                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Regular).is_err() {231                        return Ok(Vec::new());232                    }233234                    let properties = RmrkCore::filter_user_properties(235                        collection_id,236                        /* token_id = */ None,237                        filter_keys,238                        |key, value| RmrkPropertyInfo {239                            key,240                            value241                        }242                    )?;243244                    Ok(properties)245                }246247                fn nft_properties(collection_id: RmrkCollectionId, nft_id: RmrkNftId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {248                    use pallet_proxy_rmrk_core::misc::NftType;249250                    let collection_id = CollectionId(collection_id);251                    let token_id = TokenId(nft_id);252253                    if RmrkCore::ensure_nft_type(collection_id, token_id, NftType::Regular).is_err() {254                        return Ok(Vec::new());255                    }256257		            let properties = RmrkCore::filter_user_properties(258                        collection_id,259                        Some(token_id),260                        filter_keys,261                        |key, value| RmrkPropertyInfo {262                            key,263                            value264                        }265                    )?;266267                    Ok(properties)268                }269270                fn nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceInfo>, DispatchError> {271                    use frame_support::BoundedVec;272                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};273274                    let collection_id = CollectionId(collection_id);275                    if !RmrkCore::collection_exists(collection_id) { return Ok(Vec::new()); } // todo make sure the collection type doesn't matter276277                    let nft_id = TokenId(nft_id);278                    if RmrkCore::ensure_nft_type(collection_id, nft_id, NftType::Resource).is_err() { return Ok(Vec::new()); }279280                    let resource_collection_id: CollectionId = RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::ResourceCollection)281                        .unwrap()282                        .decode_or_default();283                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Resource).is_err() { return Ok(Vec::new()); }284285                    let resources = pallet_nonfungible::TokenProperties::<Runtime>::iter_prefix((resource_collection_id,))286                        .filter_map(|(resource_id, properties)| Some(RmrkResourceInfo {287                            id: BoundedVec::default(), // todo ResourceId property288                            pending: RmrkCore::get_nft_property(resource_collection_id, resource_id, RmrkProperty::PendingResourceAccept).unwrap().decode_or_default(),289                            pending_removal: RmrkCore::get_nft_property(resource_collection_id, resource_id, RmrkProperty::PendingResourceRemoval).unwrap().decode_or_default(),290                            resource: RmrkCore::get_nft_property(resource_collection_id, resource_id, RmrkProperty::ResourceType).unwrap().decode_or_default(),/* {291                                RmrkResourceTypes::Basic(resource) => RmrkResourceTypes::Basic(),/*(RmrkBasicResource {292                                    src: RmrkCore::get_nft_property_inner(properties, RmrkProperty::Src).unwrap().decode_or_default(),293                                    metadata: RmrkCore::get_nft_property_inner(properties, RmrkProperty::Metadata).unwrap().decode_or_default(),294                                    license: RmrkCore::get_nft_property_inner(properties, RmrkProperty::License).unwrap().decode_or_default(),295                                    thumb: RmrkCore::get_nft_property_inner(properties, RmrkProperty::Thumb).unwrap().decode_or_default(),296                                },*///BasicResource<BoundedString>)297                                _ => todo!(), //RmrkResourceTypes::Composable(ComposableResource<BoundedString, BoundedParts>),298                                //RmrkResourceTypes::Slot(SlotResource<BoundedString>),299                            },*/300                        }))301                        .collect();302303                    Ok(resources)304                }305306                fn nft_resource_priorities(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceId>, DispatchError> {307                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};308309                    let collection_id = CollectionId(collection_id);310                    if !RmrkCore::collection_exists(collection_id) { return Ok(Vec::new()); } // todo ensure the collection type doesn't matter311312                    let nft_id = TokenId(nft_id);313                    if RmrkCore::ensure_nft_type(collection_id, nft_id, NftType::Resource).is_err() { return Ok(Vec::new()); }314315                    /*let resource_collection_id: CollectionId = RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::ResourceCollection)316                        .unwrap()317                        .decode_or_default();318                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Resource).is_err() { return Ok(Vec::new()); }319320                    let resources = pallet_nonfungible::TokenProperties::<Runtime>::iter_prefix((resource_collection_id,))321                        .filter_map(|(resource_id, properties)| Some((322                            resource_id, // ResourceId property323                            RmrkCore::get_nft_property(resource_collection_id, resource_id, RmrkProperty::Priority).unwrap().decode_or_default(),324                        )))325                        .collect()326                        .sort_by_key(|(_, index)| *index)327                        .into_iter().map(|(resource_id, _)| resource_id)*/328                    let priorities = RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::ResourcePriorities)?.decode_or_default();329330                    Ok(priorities)331                }332333                fn base(base_id: RmrkBaseId) -> Result<Option<RmrkBaseInfo<AccountId>>, DispatchError> {334                    use pallet_proxy_rmrk_core::{335                        RmrkProperty, misc::{CollectionType, RmrkDecode},336                    };337338                    let collection_id = CollectionId(base_id);339                    let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Base) {340                        Ok(c) => c,341                        Err(_) => return Ok(None),342                    };343344                    Ok(Some(RmrkBaseInfo {345                        issuer: collection.owner.clone(),346                        base_type: RmrkCore::get_collection_property(collection_id, RmrkProperty::BaseType)?.decode_or_default(),347                        symbol: collection.token_prefix.decode_or_default(),348                    }))349                }350351                fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {352                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};353354                    let collection_id = CollectionId(base_id);355                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() { return Ok(Vec::new()); }356357                    let parts = dispatch_unique_runtime!(collection_id.collection_tokens())?358                        .into_iter()359                        .filter_map(|token_id| {360                            let nft_type = RmrkCore::get_nft_type(collection_id, token_id).ok()?;361362                            match nft_type {363                                NftType::FixedPart => Some(RmrkPartType::FixedPart(RmrkFixedPart {364                                    id: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ExternalPartId).ok()?.decode_or_default(),365                                    src: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::Src).ok()?.decode_or_default(),366                                    z: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ZIndex).ok()?.decode_or_default(),367                                })),368                                NftType::SlotPart => Some(RmrkPartType::SlotPart(RmrkSlotPart {369                                    id: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ExternalPartId).ok()?.decode_or_default(),370                                    src: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::Src).ok()?.decode_or_default(),371                                    z: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ZIndex).ok()?.decode_or_default(),372                                    equippable: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::EquippableList).ok()?.decode_or_default(),373                                })),374                                _ => None375                            }376                        })377                        .collect();378379                    Ok(parts)380                }381382                fn theme_names(base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {383                    use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkDecode}};384385                    let collection_id = CollectionId(base_id);386                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() {387                        return Ok(Vec::new());388                    }389390                    let theme_names = dispatch_unique_runtime!(collection_id.collection_tokens())?391                        .iter()392                        .filter_map(|token_id| {393                            let nft_type = RmrkCore::get_nft_type(collection_id, *token_id).unwrap();394395                            match nft_type {396                                Theme => Some(397                                    RmrkCore::get_nft_property(collection_id, *token_id, RmrkProperty::ThemeName).unwrap().decode_or_default()398                                ),399                                _ => None400                            }401                        })402                        .collect();403404                    Ok(theme_names)405                }406407                fn theme(base_id: RmrkBaseId, theme_name: RmrkThemeName, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Option<RmrkTheme>, DispatchError> {408                    use pallet_proxy_rmrk_core::{409                        RmrkProperty,410                        misc::{CollectionType, NftType, RmrkDecode}411                    };412413                    let collection_id = CollectionId(base_id);414                    if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() {415                        return Ok(None);416                    }417418                    let theme_info = dispatch_unique_runtime!(collection_id.collection_tokens())?419                        .into_iter()420                        .find_map(|token_id| {421                            RmrkCore::ensure_nft_type(collection_id, token_id, NftType::Theme).ok()?;422423                            let name: RmrkString = RmrkCore::get_nft_property(424                                collection_id, token_id, RmrkProperty::ThemeName425                            ).ok()?.decode_or_default();426427                            if name == theme_name {428                                Some((name, token_id))429                            } else {430                                None431                            }432                        });433434                    let (name, theme_id) = match theme_info {435                        Some((name, theme_id)) => (name, theme_id),436                        None => return Ok(None)437                    };438439                    let properties = RmrkCore::filter_user_properties(440                        collection_id,441                        Some(theme_id),442                        filter_keys,443                        |key, value| RmrkThemeProperty {444                            key,445                            value446                        }447                    )?;448449                    let inherit = RmrkCore::get_nft_property(450                        collection_id,451                        theme_id,452                        RmrkProperty::ThemeInherit453                    )?.decode_or_default();454455                    let theme = RmrkTheme {456                        name,457                        properties,458                        inherit,459                    };460461                    Ok(Some(theme))462                }463            }464465            impl sp_api::Core<Block> for Runtime {466                fn version() -> RuntimeVersion {467                    VERSION468                }469470                fn execute_block(block: Block) {471                    Executive::execute_block(block)472                }473474                fn initialize_block(header: &<Block as BlockT>::Header) {475                    Executive::initialize_block(header)476                }477            }478479            impl sp_api::Metadata<Block> for Runtime {480                fn metadata() -> OpaqueMetadata {481                    OpaqueMetadata::new(Runtime::metadata().into())482                }483            }484485            impl sp_block_builder::BlockBuilder<Block> for Runtime {486                fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {487                    Executive::apply_extrinsic(extrinsic)488                }489490                fn finalize_block() -> <Block as BlockT>::Header {491                    Executive::finalize_block()492                }493494                fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {495                    data.create_extrinsics()496                }497498                fn check_inherents(499                    block: Block,500                    data: sp_inherents::InherentData,501                ) -> sp_inherents::CheckInherentsResult {502                    data.check_extrinsics(&block)503                }504505                // fn random_seed() -> <Block as BlockT>::Hash {506                //     RandomnessCollectiveFlip::random_seed().0507                // }508            }509510            impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {511                fn validate_transaction(512                    source: TransactionSource,513                    tx: <Block as BlockT>::Extrinsic,514                    hash: <Block as BlockT>::Hash,515                ) -> TransactionValidity {516                    Executive::validate_transaction(source, tx, hash)517                }518            }519520            impl sp_offchain::OffchainWorkerApi<Block> for Runtime {521                fn offchain_worker(header: &<Block as BlockT>::Header) {522                    Executive::offchain_worker(header)523                }524            }525526            impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {527                fn chain_id() -> u64 {528                    <Runtime as pallet_evm::Config>::ChainId::get()529                }530531                fn account_basic(address: H160) -> EVMAccount {532                    EVM::account_basic(&address)533                }534535                fn gas_price() -> U256 {536                    <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()537                }538539                fn account_code_at(address: H160) -> Vec<u8> {540                    EVM::account_codes(address)541                }542543                fn author() -> H160 {544                    <pallet_evm::Pallet<Runtime>>::find_author()545                }546547                fn storage_at(address: H160, index: U256) -> H256 {548                    let mut tmp = [0u8; 32];549                    index.to_big_endian(&mut tmp);550                    EVM::account_storages(address, H256::from_slice(&tmp[..]))551                }552553                #[allow(clippy::redundant_closure)]554                fn call(555                    from: H160,556                    to: H160,557                    data: Vec<u8>,558                    value: U256,559                    gas_limit: U256,560                    max_fee_per_gas: Option<U256>,561                    max_priority_fee_per_gas: Option<U256>,562                    nonce: Option<U256>,563                    estimate: bool,564                    access_list: Option<Vec<(H160, Vec<H256>)>>,565                ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {566                    let config = if estimate {567                        let mut config = <Runtime as pallet_evm::Config>::config().clone();568                        config.estimate = true;569                        Some(config)570                    } else {571                        None572                    };573574                    let is_transactional = false;575                    <Runtime as pallet_evm::Config>::Runner::call(576                        CrossAccountId::from_eth(from),577                        to,578                        data,579                        value,580                        gas_limit.low_u64(),581                        max_fee_per_gas,582                        max_priority_fee_per_gas,583                        nonce,584                        access_list.unwrap_or_default(),585                        is_transactional,586                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),587                    ).map_err(|err| err.into())588                }589590                #[allow(clippy::redundant_closure)]591                fn create(592                    from: H160,593                    data: Vec<u8>,594                    value: U256,595                    gas_limit: U256,596                    max_fee_per_gas: Option<U256>,597                    max_priority_fee_per_gas: Option<U256>,598                    nonce: Option<U256>,599                    estimate: bool,600                    access_list: Option<Vec<(H160, Vec<H256>)>>,601                ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {602                    let config = if estimate {603                        let mut config = <Runtime as pallet_evm::Config>::config().clone();604                        config.estimate = true;605                        Some(config)606                    } else {607                        None608                    };609610                    let is_transactional = false;611                    <Runtime as pallet_evm::Config>::Runner::create(612                        CrossAccountId::from_eth(from),613                        data,614                        value,615                        gas_limit.low_u64(),616                        max_fee_per_gas,617                        max_priority_fee_per_gas,618                        nonce,619                        access_list.unwrap_or_default(),620                        is_transactional,621                        config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),622                    ).map_err(|err| err.into())623                }624625                fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {626                    Ethereum::current_transaction_statuses()627                }628629                fn current_block() -> Option<pallet_ethereum::Block> {630                    Ethereum::current_block()631                }632633                fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {634                    Ethereum::current_receipts()635                }636637                fn current_all() -> (638                    Option<pallet_ethereum::Block>,639                    Option<Vec<pallet_ethereum::Receipt>>,640                    Option<Vec<TransactionStatus>>641                ) {642                    (643                        Ethereum::current_block(),644                        Ethereum::current_receipts(),645                        Ethereum::current_transaction_statuses()646                    )647                }648649                fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {650                    xts.into_iter().filter_map(|xt| match xt.0.function {651                        Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),652                        _ => None653                    }).collect()654                }655656                fn elasticity() -> Option<Permill> {657                    None658                }659            }660661            impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {662                fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic  {663                    UncheckedExtrinsic::new_unsigned(664                        pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),665                    )666                }667            }668669            impl sp_session::SessionKeys<Block> for Runtime {670                fn decode_session_keys(671                    encoded: Vec<u8>,672                ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {673                    SessionKeys::decode_into_raw_public_keys(&encoded)674                }675676                fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {677                    SessionKeys::generate(seed)678                }679            }680681            impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {682                fn slot_duration() -> sp_consensus_aura::SlotDuration {683                    sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())684                }685686                fn authorities() -> Vec<AuraId> {687                    Aura::authorities().to_vec()688                }689            }690691            impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {692                fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {693                    ParachainSystem::collect_collation_info(header)694                }695            }696697            impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {698                fn account_nonce(account: AccountId) -> Index {699                    System::account_nonce(account)700                }701            }702703            impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {704                fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {705                    TransactionPayment::query_info(uxt, len)706                }707                fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {708                    TransactionPayment::query_fee_details(uxt, len)709                }710            }711712            /*713            impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>714                for Runtime715            {716                fn call(717                    origin: AccountId,718                    dest: AccountId,719                    value: Balance,720                    gas_limit: u64,721                    input_data: Vec<u8>,722                ) -> pallet_contracts_primitives::ContractExecResult {723                    Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)724                }725726                fn instantiate(727                    origin: AccountId,728                    endowment: Balance,729                    gas_limit: u64,730                    code: pallet_contracts_primitives::Code<Hash>,731                    data: Vec<u8>,732                    salt: Vec<u8>,733                ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>734                {735                    Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)736                }737738                fn get_storage(739                    address: AccountId,740                    key: [u8; 32],741                ) -> pallet_contracts_primitives::GetStorageResult {742                    Contracts::get_storage(address, key)743                }744745                fn rent_projection(746                    address: AccountId,747                ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {748                    Contracts::rent_projection(address)749                }750            }751            */752753            #[cfg(feature = "runtime-benchmarks")]754            impl frame_benchmarking::Benchmark<Block> for Runtime {755                fn benchmark_metadata(extra: bool) -> (756                    Vec<frame_benchmarking::BenchmarkList>,757                    Vec<frame_support::traits::StorageInfo>,758                ) {759                    use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};760                    use frame_support::traits::StorageInfoTrait;761762                    let mut list = Vec::<BenchmarkList>::new();763764                    list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);765                    list_benchmark!(list, extra, pallet_common, Common);766                    list_benchmark!(list, extra, pallet_unique, Unique);767                    list_benchmark!(list, extra, pallet_structure, Structure);768                    list_benchmark!(list, extra, pallet_inflation, Inflation);769                    list_benchmark!(list, extra, pallet_fungible, Fungible);770                    list_benchmark!(list, extra, pallet_refungible, Refungible);771                    list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);772                    // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);773774                    let storage_info = AllPalletsReversedWithSystemFirst::storage_info();775776                    return (list, storage_info)777                }778779                fn dispatch_benchmark(780                    config: frame_benchmarking::BenchmarkConfig781                ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {782                    use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};783784                    let allowlist: Vec<TrackedStorageKey> = vec![785                        // Total Issuance786                        hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),787788                        // Block Number789                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),790                        // Execution Phase791                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),792                        // Event Count793                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),794                        // System Events795                        hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),796797                        // Evm CurrentLogs798                        hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),799800                        // Transactional depth801                        hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),802                    ];803804                    let mut batches = Vec::<BenchmarkBatch>::new();805                    let params = (&config, &allowlist);806807                    add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);808                    add_benchmark!(params, batches, pallet_common, Common);809                    add_benchmark!(params, batches, pallet_unique, Unique);810                    add_benchmark!(params, batches, pallet_structure, Structure);811                    add_benchmark!(params, batches, pallet_inflation, Inflation);812                    add_benchmark!(params, batches, pallet_fungible, Fungible);813                    add_benchmark!(params, batches, pallet_refungible, Refungible);814                    add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);815                    // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);816817                    if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }818                    Ok(batches)819                }820            }821822            #[cfg(feature = "try-runtime")]823            impl frame_try_runtime::TryRuntime<Block> for Runtime {824                fn on_runtime_upgrade() -> (Weight, Weight) {825                    log::info!("try-runtime::on_runtime_upgrade unique-chain.");826                    let weight = Executive::try_runtime_upgrade().unwrap();827                    (weight, RuntimeBlockWeights::get().max_block)828                }829830                fn execute_block_no_check(block: Block) -> Weight {831                    Executive::execute_block_no_check(block)832                }833            }834        }835    }836}
modifiedtests/src/nesting/nest.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/nest.test.ts
+++ b/tests/src/nesting/nest.test.ts
@@ -41,7 +41,7 @@
 
       // Create a token to be nested
       const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
-      
+
       // Nest
       await transferExpectSuccess(collection, newToken, alice, {Ethereum: tokenIdToAddress(collection, targetToken)});
       expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
@@ -111,8 +111,8 @@
 
       // Create a nested token
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionFT, 
-        targetAddress, 
+        collectionFT,
+        targetAddress,
         {Fungible: {Value: 10}},
       ))).to.not.be.rejected;
 
@@ -134,8 +134,8 @@
 
       // Create a nested token
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionFT, 
-        targetAddress, 
+        collectionFT,
+        targetAddress,
         {Fungible: {Value: 10}},
       ))).to.not.be.rejected;
 
@@ -158,8 +158,8 @@
 
       // Create a nested token
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionRFT, 
-        targetAddress, 
+        collectionRFT,
+        targetAddress,
         {ReFungible: {const_data: [], pieces: 100}},
       ))).to.not.be.rejected;
 
@@ -181,7 +181,7 @@
 
       // Create a nested token
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionRFT, 
+        collectionRFT,
         targetAddress,
         {ReFungible: {const_data: [], pieces: 100}},
       ))).to.not.be.rejected;
@@ -207,17 +207,29 @@
       await setCollectionPermissionsExceptSuccess(alice, collection, {nesting: 'Owner'});
       const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
 
+      const maxNestingLevel = 5;
+      let prevToken = targetToken;
+
       // Create a nested-token matryoshka
-      const nestedToken1 = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});
-      const nestedToken2 = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, nestedToken1)});
-      // The nesting depth is limited by 2
+      for (let i = 0; i < maxNestingLevel; i++) {
+        const nestedToken = await createItemExpectSuccess(
+          alice,
+          collection,
+          'NFT',
+          {Ethereum: tokenIdToAddress(collection, prevToken)},
+        );
+
+        prevToken = nestedToken;
+      }
+
+      // The nesting depth is limited by `maxNestingLevel`
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collection, 
-        {Ethereum: tokenIdToAddress(collection, nestedToken2)}, 
+        collection,
+        {Ethereum: tokenIdToAddress(collection, prevToken)},
           {nft: {const_data: [], variable_data: []}} as any,
       )), 'while creating nested token').to.be.rejectedWith(/^structure\.DepthLimit$/);
 
-      expect(await getTopmostTokenOwner(api, collection, nestedToken2)).to.be.deep.equal({Substrate: alice.address});
+      expect(await getTopmostTokenOwner(api, collection, prevToken)).to.be.deep.equal({Substrate: alice.address});
     });
   });
 
@@ -231,8 +243,8 @@
 
       // Try to create a nested token
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collection, 
-        {Ethereum: tokenIdToAddress(collection, targetToken)}, 
+        collection,
+        {Ethereum: tokenIdToAddress(collection, targetToken)},
           {nft: {const_data: [], variable_data: []}} as any,
       )), 'while creating nested token').to.be.rejectedWith(/^common\.NestingIsDisabled$/);
 
@@ -259,8 +271,8 @@
 
       // Try to create a nested token in the wrong collection
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collection, 
-        {Ethereum: tokenIdToAddress(collection, targetToken)}, 
+        collection,
+        {Ethereum: tokenIdToAddress(collection, targetToken)},
           {nft: {const_data: [], variable_data: []}} as any,
       )), 'while creating nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
 
@@ -285,8 +297,8 @@
 
       // Try to create a nested token in the wrong collection
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collection, 
-        {Ethereum: tokenIdToAddress(collection, targetToken)}, 
+        collection,
+        {Ethereum: tokenIdToAddress(collection, targetToken)},
           {nft: {const_data: [], variable_data: []}} as any,
       )), 'while creating nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
 
@@ -307,8 +319,8 @@
 
       // Try to create a nested token in the wrong collection
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collection, 
-        {Ethereum: tokenIdToAddress(collection, targetToken)}, 
+        collection,
+        {Ethereum: tokenIdToAddress(collection, targetToken)},
           {nft: {const_data: [], variable_data: []}} as any,
       )), 'while creating nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
 
@@ -332,11 +344,11 @@
 
       // Try to create a nested token
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionFT, 
-        targetAddress, 
+        collectionFT,
+        targetAddress,
         {Fungible: {Value: 10}},
       )), 'while creating nested token').to.be.rejectedWith(/^common\.NestingIsDisabled$/);
-      
+
       // Create a token to be nested
       const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
       // Try to nest
@@ -366,8 +378,8 @@
 
       // Try to create a nested token in the wrong collection
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionFT, 
-        targetAddress, 
+        collectionFT,
+        targetAddress,
         {Fungible: {Value: 10}},
       )), 'while creating nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
 
@@ -393,8 +405,8 @@
 
       // Try to create a nested token in the wrong collection
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionFT, 
-        targetAddress, 
+        collectionFT,
+        targetAddress,
         {Fungible: {Value: 10}},
       )), 'while creating nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
 
@@ -417,8 +429,8 @@
 
       // Try to create a nested token in the wrong collection
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionFT, 
-        targetAddress, 
+        collectionFT,
+        targetAddress,
         {Fungible: {Value: 10}},
       )), 'while creating a nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
 
@@ -441,8 +453,8 @@
 
       // Create a nested token
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionRFT, 
-        targetAddress, 
+        collectionRFT,
+        targetAddress,
         {ReFungible: {const_data: [], pieces: 100}},
       )), 'while creating a nested token').to.be.rejectedWith(/^common\.NestingIsDisabled$/);
 
@@ -477,8 +489,8 @@
 
       // Try to create a nested token in the wrong collection
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionRFT, 
-        targetAddress, 
+        collectionRFT,
+        targetAddress,
         {ReFungible: {const_data: [], pieces: 100}},
       )), 'while creating a nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
 
@@ -504,8 +516,8 @@
 
       // Try to create a nested token in the wrong collection
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionRFT, 
-        targetAddress, 
+        collectionRFT,
+        targetAddress,
         {ReFungible: {const_data: [], pieces: 100}},
       )), 'while creating a nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
 
@@ -528,8 +540,8 @@
 
       // Try to create a nested token in the wrong collection
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionRFT, 
-        targetAddress, 
+        collectionRFT,
+        targetAddress,
         {ReFungible: {const_data: [], pieces: 100}},
       )), 'while creating a nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);