git.delta.rocks / unique-network / refs/commits / 3db55eb8a3c0

difftreelog

feat nest on create/transfer

Yaroslav Bolyukin2022-04-07parent: #b69837d.patch.diff
in: master

12 files changed

modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -723,17 +723,20 @@
 		sender: T::CrossAccountId,
 		to: T::CrossAccountId,
 		data: CreateItemData,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo;
 	fn create_multiple_items(
 		&self,
 		sender: T::CrossAccountId,
 		to: T::CrossAccountId,
 		data: Vec<CreateItemData>,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo;
 	fn create_multiple_items_ex(
 		&self,
 		sender: T::CrossAccountId,
 		data: CreateItemExData<T::CrossAccountId>,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo;
 	fn burn_item(
 		&self,
@@ -748,6 +751,7 @@
 		to: T::CrossAccountId,
 		token: TokenId,
 		amount: u128,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo;
 	fn approve(
 		&self,
@@ -781,11 +785,12 @@
 		data: BoundedVec<u8, CustomDataLimit>,
 	) -> DispatchResultWithPostInfo;
 
-	fn nest_token(
+	fn check_nesting(
 		&self,
 		sender: T::CrossAccountId,
-		from: (CollectionId, TokenId),
+		from: CollectionId,
 		under: TokenId,
+		budget: &dyn Budget,
 	) -> DispatchResult;
 
 	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;
modifiedpallets/evm-coder-substrate/src/lib.rsdiffbeforeafterboth
--- a/pallets/evm-coder-substrate/src/lib.rs
+++ b/pallets/evm-coder-substrate/src/lib.rs
@@ -55,7 +55,6 @@
 
 	use frame_system::ensure_signed;
 	pub use frame_support::dispatch::DispatchResult;
-	use frame_support::{pallet_prelude::*, traits::PalletInfo};
 	use frame_system::pallet_prelude::*;
 
 	/// DispatchError is opaque, but we need to somehow extract correct error in case of OutOfGas failure
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -17,7 +17,7 @@
 use core::marker::PhantomData;
 
 use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, BoundedVec};
-use up_data_structs::{TokenId, CreateItemExData, budget::Budget};
+use up_data_structs::{TokenId, CollectionId, CreateItemExData, budget::Budget};
 use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
 use sp_runtime::ArithmeticError;
 use sp_std::{vec::Vec, vec};
@@ -78,10 +78,11 @@
 		sender: T::CrossAccountId,
 		to: T::CrossAccountId,
 		data: up_data_structs::CreateItemData,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo {
 		match data {
 			up_data_structs::CreateItemData::Fungible(data) => with_weight(
-				<Pallet<T>>::create_item(self, &sender, (to, data.value)),
+				<Pallet<T>>::create_item(self, &sender, (to, data.value), nesting_budget),
 				<CommonWeights<T>>::create_item(),
 			),
 			_ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),
@@ -93,6 +94,7 @@
 		sender: T::CrossAccountId,
 		to: T::CrossAccountId,
 		data: Vec<up_data_structs::CreateItemData>,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo {
 		let mut sum: u128 = 0;
 		for data in data {
@@ -107,7 +109,7 @@
 		}
 
 		with_weight(
-			<Pallet<T>>::create_item(self, &sender, (to, sum)),
+			<Pallet<T>>::create_item(self, &sender, (to, sum), nesting_budget),
 			<CommonWeights<T>>::create_item(),
 		)
 	}
@@ -116,6 +118,7 @@
 		&self,
 		sender: <T>::CrossAccountId,
 		data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo {
 		let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);
 		let data = match data {
@@ -124,7 +127,7 @@
 		};
 
 		with_weight(
-			<Pallet<T>>::create_multiple_items(self, &sender, data.into_inner()),
+			<Pallet<T>>::create_multiple_items(self, &sender, data.into_inner(), nesting_budget),
 			weight,
 		)
 	}
@@ -152,6 +155,7 @@
 		to: T::CrossAccountId,
 		token: TokenId,
 		amount: u128,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo {
 		ensure!(
 			token == TokenId::default(),
@@ -159,7 +163,7 @@
 		);
 
 		with_weight(
-			<Pallet<T>>::transfer(self, &from, &to, amount),
+			<Pallet<T>>::transfer(self, &from, &to, amount, nesting_budget),
 			<CommonWeights<T>>::transfer(),
 		)
 	}
@@ -230,11 +234,12 @@
 		fail!(<Error<T>>::FungibleItemsDontHaveData)
 	}
 
-	fn nest_token(
+	fn check_nesting(
 		&self,
 		_sender: <T>::CrossAccountId,
-		_from: (up_data_structs::CollectionId, TokenId),
+		_from: CollectionId,
 		_under: TokenId,
+		_budget: &dyn Budget,
 	) -> sp_runtime::DispatchResult {
 		fail!(<Error<T>>::FungibleDisallowsNesting)
 	}
modifiedpallets/fungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -81,8 +81,11 @@
 		let caller = T::CrossAccountId::from_eth(caller);
 		let to = T::CrossAccountId::from_eth(to);
 		let amount = amount.try_into().map_err(|_| "amount overflow")?;
+		let budget = self
+			.recorder
+			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
-		<Pallet<T>>::transfer(self, &caller, &to, amount).map_err(|_| "transfer error")?;
+		<Pallet<T>>::transfer(self, &caller, &to, amount, &budget).map_err(|_| "transfer error")?;
 		Ok(true)
 	}
 	#[weight(<SelfWeightOf<T>>::transfer_from())]
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -193,6 +193,7 @@
 		from: &T::CrossAccountId,
 		to: &T::CrossAccountId,
 		amount: u128,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
 		ensure!(
 			collection.limits.transfers_enabled(),
@@ -222,12 +223,12 @@
 			let handle = <CollectionHandle<T>>::try_get(target.0)?;
 			let dispatch = T::CollectionDispatch::dispatch(handle);
 			let dispatch = dispatch.as_dyn();
-
-			// =========
 
-			dispatch.nest_token(from.clone(), (collection.id, TokenId::default()), target.1)?;
+			dispatch.check_nesting(from.clone(), collection.id, target.1, nesting_budget)?;
 		}
 
+		// =========
+
 		if let Some(balance_to) = balance_to {
 			// from != to
 			if balance_from == 0 {
@@ -257,6 +258,7 @@
 		collection: &FungibleHandle<T>,
 		sender: &T::CrossAccountId,
 		data: BTreeMap<T::CrossAccountId, u128>,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
 		if !collection.is_owner_or_admin(sender) {
 			ensure!(
@@ -285,6 +287,16 @@
 				.ok_or(ArithmeticError::Overflow)?;
 		}
 
+		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, target.1, nesting_budget)?;
+			}
+		}
+
 		// =========
 
 		<TotalSupply<T>>::insert(collection.id, total_supply);
@@ -407,7 +419,7 @@
 
 		// =========
 
-		Self::transfer(collection, from, to, amount)?;
+		Self::transfer(collection, from, to, amount, nesting_budget)?;
 		if let Some(allowance) = allowance {
 			Self::set_allowance_unchecked(collection, from, spender, allowance);
 		}
@@ -437,7 +449,13 @@
 		collection: &FungibleHandle<T>,
 		sender: &T::CrossAccountId,
 		data: CreateItemData<T>,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
-		Self::create_multiple_items(collection, sender, [(data.0, data.1)].into_iter().collect())
+		Self::create_multiple_items(
+			collection,
+			sender,
+			[(data.0, data.1)].into_iter().collect(),
+			nesting_budget,
+		)
 	}
 }
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -89,9 +89,15 @@
 		sender: T::CrossAccountId,
 		to: T::CrossAccountId,
 		data: up_data_structs::CreateItemData,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo {
 		with_weight(
-			<Pallet<T>>::create_item(self, &sender, map_create_data::<T>(data, &to)?),
+			<Pallet<T>>::create_item(
+				self,
+				&sender,
+				map_create_data::<T>(data, &to)?,
+				nesting_budget,
+			),
 			<CommonWeights<T>>::create_item(),
 		)
 	}
@@ -101,6 +107,7 @@
 		sender: T::CrossAccountId,
 		to: T::CrossAccountId,
 		data: Vec<up_data_structs::CreateItemData>,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo {
 		let data = data
 			.into_iter()
@@ -109,7 +116,7 @@
 
 		let amount = data.len();
 		with_weight(
-			<Pallet<T>>::create_multiple_items(self, &sender, data),
+			<Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),
 			<CommonWeights<T>>::create_multiple_items(amount as u32),
 		)
 	}
@@ -118,6 +125,7 @@
 		&self,
 		sender: <T>::CrossAccountId,
 		data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo {
 		let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);
 		let data = match data {
@@ -126,7 +134,7 @@
 		};
 
 		with_weight(
-			<Pallet<T>>::create_multiple_items(self, &sender, data.into_inner()),
+			<Pallet<T>>::create_multiple_items(self, &sender, data.into_inner(), nesting_budget),
 			weight,
 		)
 	}
@@ -154,11 +162,12 @@
 		to: T::CrossAccountId,
 		token: TokenId,
 		amount: u128,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo {
 		ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
 		if amount == 1 {
 			with_weight(
-				<Pallet<T>>::transfer(self, &from, &to, token),
+				<Pallet<T>>::transfer(self, &from, &to, token, nesting_budget),
 				<CommonWeights<T>>::transfer(),
 			)
 		} else {
@@ -239,13 +248,14 @@
 		)
 	}
 
-	fn nest_token(
+	fn check_nesting(
 		&self,
 		sender: T::CrossAccountId,
-		(from, _): (CollectionId, TokenId),
+		from: CollectionId,
 		under: TokenId,
+		budget: &dyn Budget,
 	) -> sp_runtime::DispatchResult {
-		<Pallet<T>>::nest_token(self, sender, from, under)
+		<Pallet<T>>::check_nesting(self, sender, from, under, budget)
 	}
 
 	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -256,6 +256,10 @@
 		let caller = T::CrossAccountId::from_eth(caller);
 		let to = T::CrossAccountId::from_eth(to);
 		let token_id: u32 = token_id.try_into()?;
+		let budget = self
+			.recorder
+			.weight_calls_budget(<StructureWeight<T>>::find_parent());
+
 		if <TokensMinted<T>>::get(self.id)
 			.checked_add(1)
 			.ok_or("item id overflow")?
@@ -272,6 +276,7 @@
 				variable_data: BoundedVec::default(),
 				owner: to,
 			},
+			&budget,
 		)
 		.map_err(dispatch_to_evm::<T>)?;
 
@@ -296,6 +301,10 @@
 		let caller = T::CrossAccountId::from_eth(caller);
 		let to = T::CrossAccountId::from_eth(to);
 		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;
+		let budget = self
+			.recorder
+			.weight_calls_budget(<StructureWeight<T>>::find_parent());
+
 		if <TokensMinted<T>>::get(self.id)
 			.checked_add(1)
 			.ok_or("item id overflow")?
@@ -314,6 +323,7 @@
 				variable_data: BoundedVec::default(),
 				owner: to,
 			},
+			&budget,
 		)
 		.map_err(dispatch_to_evm::<T>)?;
 		Ok(true)
@@ -338,8 +348,11 @@
 		let caller = T::CrossAccountId::from_eth(caller);
 		let to = T::CrossAccountId::from_eth(to);
 		let token = token_id.try_into()?;
+		let budget = self
+			.recorder
+			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
-		<Pallet<T>>::transfer(self, &caller, &to, token).map_err(dispatch_to_evm::<T>)?;
+		<Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;
 		Ok(())
 	}
 
@@ -409,6 +422,9 @@
 		let mut expected_index = <TokensMinted<T>>::get(self.id)
 			.checked_add(1)
 			.ok_or("item id overflow")?;
+		let budget = self
+			.recorder
+			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
 		let total_tokens = token_ids.len();
 		for id in token_ids.into_iter() {
@@ -426,7 +442,8 @@
 			})
 			.collect();
 
-		<Pallet<T>>::create_multiple_items(self, &caller, data).map_err(dispatch_to_evm::<T>)?;
+		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)
+			.map_err(dispatch_to_evm::<T>)?;
 		Ok(true)
 	}
 
@@ -447,6 +464,9 @@
 		let mut expected_index = <TokensMinted<T>>::get(self.id)
 			.checked_add(1)
 			.ok_or("item id overflow")?;
+		let budget = self
+			.recorder
+			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
 		let mut data = Vec::with_capacity(tokens.len());
 		for (id, token_uri) in tokens {
@@ -465,7 +485,8 @@
 			});
 		}
 
-		<Pallet<T>>::create_multiple_items(self, &caller, data).map_err(dispatch_to_evm::<T>)?;
+		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)
+			.map_err(dispatch_to_evm::<T>)?;
 		Ok(true)
 	}
 }
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
before · pallets/nonfungible/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use erc::ERC721Events;20use frame_support::{BoundedVec, ensure, fail};21use up_data_structs::{22	AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,23	mapping::TokenAddressMapping, NestingRule, budget::Budget,24};25use pallet_evm::account::CrossAccountId;26use pallet_common::{27	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent,28	CollectionHandle, dispatch::CollectionDispatch,29};30use pallet_structure::Pallet as PalletStructure;31use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};32use sp_core::H160;33use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};34use sp_std::{vec::Vec, vec};35use core::ops::Deref;36use sp_std::collections::btree_map::BTreeMap;37use codec::{Encode, Decode, MaxEncodedLen};38use scale_info::TypeInfo;3940pub use pallet::*;41#[cfg(feature = "runtime-benchmarks")]42pub mod benchmarking;43pub mod common;44pub mod erc;45pub mod weights;4647pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;48pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4950#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]51pub struct ItemData<CrossAccountId> {52	pub const_data: BoundedVec<u8, CustomDataLimit>,53	pub variable_data: BoundedVec<u8, CustomDataLimit>,54	pub owner: CrossAccountId,55}5657#[frame_support::pallet]58pub mod pallet {59	use super::*;60	use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};61	use up_data_structs::{CollectionId, TokenId};62	use super::weights::WeightInfo;6364	#[pallet::error]65	pub enum Error<T> {66		/// Not Nonfungible item data used to mint in Nonfungible collection.67		NotNonfungibleDataUsedToMintFungibleCollectionToken,68		/// Used amount > 1 with NFT69		NonfungibleItemsHaveNoAmount,70	}7172	#[pallet::config]73	pub trait Config:74		frame_system::Config + pallet_common::Config + pallet_structure::Config75	{76		type WeightInfo: WeightInfo;77	}7879	#[pallet::pallet]80	#[pallet::generate_store(pub(super) trait Store)]81	pub struct Pallet<T>(_);8283	#[pallet::storage]84	pub type TokensMinted<T: Config> =85		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;86	#[pallet::storage]87	pub type TokensBurnt<T: Config> =88		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;8990	#[pallet::storage]91	pub type TokenData<T: Config> = StorageNMap<92		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),93		Value = ItemData<T::CrossAccountId>,94		QueryKind = OptionQuery,95	>;9697	/// Used to enumerate tokens owned by account98	#[pallet::storage]99	pub type Owned<T: Config> = StorageNMap<100		Key = (101			Key<Twox64Concat, CollectionId>,102			Key<Blake2_128Concat, T::CrossAccountId>,103			Key<Twox64Concat, TokenId>,104		),105		Value = bool,106		QueryKind = ValueQuery,107	>;108109	#[pallet::storage]110	pub type AccountBalance<T: Config> = StorageNMap<111		Key = (112			Key<Twox64Concat, CollectionId>,113			Key<Blake2_128Concat, T::CrossAccountId>,114		),115		Value = u32,116		QueryKind = ValueQuery,117	>;118119	#[pallet::storage]120	pub type Allowance<T: Config> = StorageNMap<121		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),122		Value = T::CrossAccountId,123		QueryKind = OptionQuery,124	>;125}126127pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);128impl<T: Config> NonfungibleHandle<T> {129	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {130		Self(inner)131	}132	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {133		self.0134	}135}136impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {137	fn recorder(&self) -> &SubstrateRecorder<T> {138		self.0.recorder()139	}140	fn into_recorder(self) -> SubstrateRecorder<T> {141		self.0.into_recorder()142	}143}144impl<T: Config> Deref for NonfungibleHandle<T> {145	type Target = pallet_common::CollectionHandle<T>;146147	fn deref(&self) -> &Self::Target {148		&self.0149	}150}151152impl<T: Config> Pallet<T> {153	pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {154		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)155	}156	pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {157		<TokenData<T>>::contains_key((collection.id, token))158	}159}160161// unchecked calls skips any permission checks162impl<T: Config> Pallet<T> {163	pub fn init_collection(164		owner: T::AccountId,165		data: CreateCollectionData<T::AccountId>,166	) -> Result<CollectionId, DispatchError> {167		<PalletCommon<T>>::init_collection(owner, data)168	}169	pub fn destroy_collection(170		collection: NonfungibleHandle<T>,171		sender: &T::CrossAccountId,172	) -> DispatchResult {173		let id = collection.id;174175		// =========176177		PalletCommon::destroy_collection(collection.0, sender)?;178179		<TokenData<T>>::remove_prefix((id,), None);180		<Owned<T>>::remove_prefix((id,), None);181		<TokensMinted<T>>::remove(id);182		<TokensBurnt<T>>::remove(id);183		<Allowance<T>>::remove_prefix((id,), None);184		<AccountBalance<T>>::remove_prefix((id,), None);185		Ok(())186	}187188	pub fn burn(189		collection: &NonfungibleHandle<T>,190		sender: &T::CrossAccountId,191		token: TokenId,192	) -> DispatchResult {193		let token_data =194			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;195		ensure!(196			&token_data.owner == sender197				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),198			<CommonError<T>>::NoPermission199		);200201		if collection.access == AccessMode::AllowList {202			collection.check_allowlist(sender)?;203		}204205		let burnt = <TokensBurnt<T>>::get(collection.id)206			.checked_add(1)207			.ok_or(ArithmeticError::Overflow)?;208209		let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))210			.checked_sub(1)211			.ok_or(ArithmeticError::Overflow)?;212213		if balance == 0 {214			<AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));215		} else {216			<AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);217		}218		// =========219220		<Owned<T>>::remove((collection.id, &token_data.owner, token));221		<TokensBurnt<T>>::insert(collection.id, burnt);222		<TokenData<T>>::remove((collection.id, token));223		let old_spender = <Allowance<T>>::take((collection.id, token));224225		if let Some(old_spender) = old_spender {226			<PalletCommon<T>>::deposit_event(CommonEvent::Approved(227				collection.id,228				token,229				sender.clone(),230				old_spender,231				0,232			));233		}234235		collection.log_mirrored(ERC721Events::Transfer {236			from: *token_data.owner.as_eth(),237			to: H160::default(),238			token_id: token.into(),239		});240		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(241			collection.id,242			token,243			token_data.owner,244			1,245		));246		Ok(())247	}248249	pub fn transfer(250		collection: &NonfungibleHandle<T>,251		from: &T::CrossAccountId,252		to: &T::CrossAccountId,253		token: TokenId,254	) -> DispatchResult {255		ensure!(256			collection.limits.transfers_enabled(),257			<CommonError<T>>::TransferNotAllowed258		);259260		let token_data =261			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;262		// TODO: require sender to be token, owner, require admins to go through transfer_from263		ensure!(264			&token_data.owner == from265				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),266			<CommonError<T>>::NoPermission267		);268269		if collection.access == AccessMode::AllowList {270			collection.check_allowlist(from)?;271			collection.check_allowlist(to)?;272		}273		<PalletCommon<T>>::ensure_correct_receiver(to)?;274275		let balance_from = <AccountBalance<T>>::get((collection.id, from))276			.checked_sub(1)277			.ok_or(<CommonError<T>>::TokenValueTooLow)?;278		let balance_to = if from != to {279			let balance_to = <AccountBalance<T>>::get((collection.id, to))280				.checked_add(1)281				.ok_or(ArithmeticError::Overflow)?;282283			ensure!(284				balance_to < collection.limits.account_token_ownership_limit(),285				<CommonError<T>>::AccountTokenLimitExceeded,286			);287288			Some(balance_to)289		} else {290			None291		};292293		if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {294			let handle = <CollectionHandle<T>>::try_get(target.0)?;295			let dispatch = T::CollectionDispatch::dispatch(handle);296			let dispatch = dispatch.as_dyn();297298			// =========299300			dispatch.nest_token(from.clone(), (collection.id, token), target.1)?;301		}302303		<TokenData<T>>::insert(304			(collection.id, token),305			ItemData {306				owner: to.clone(),307				..token_data308			},309		);310311		if let Some(balance_to) = balance_to {312			// from != to313			if balance_from == 0 {314				<AccountBalance<T>>::remove((collection.id, from));315			} else {316				<AccountBalance<T>>::insert((collection.id, from), balance_from);317			}318			<AccountBalance<T>>::insert((collection.id, to), balance_to);319			<Owned<T>>::remove((collection.id, from, token));320			<Owned<T>>::insert((collection.id, to, token), true);321		}322		Self::set_allowance_unchecked(collection, from, token, None, true);323324		collection.log_mirrored(ERC721Events::Transfer {325			from: *from.as_eth(),326			to: *to.as_eth(),327			token_id: token.into(),328		});329		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(330			collection.id,331			token,332			from.clone(),333			to.clone(),334			1,335		));336		Ok(())337	}338339	pub fn create_multiple_items(340		collection: &NonfungibleHandle<T>,341		sender: &T::CrossAccountId,342		data: Vec<CreateItemData<T>>,343	) -> DispatchResult {344		if !collection.is_owner_or_admin(sender) {345			ensure!(346				collection.mint_mode,347				<CommonError<T>>::PublicMintingNotAllowed348			);349			collection.check_allowlist(sender)?;350351			for item in data.iter() {352				collection.check_allowlist(&item.owner)?;353			}354		}355356		for data in data.iter() {357			<PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;358		}359360		let first_token = <TokensMinted<T>>::get(collection.id);361		let tokens_minted = first_token362			.checked_add(data.len() as u32)363			.ok_or(ArithmeticError::Overflow)?;364		ensure!(365			tokens_minted <= collection.limits.token_limit(),366			<CommonError<T>>::CollectionTokenLimitExceeded367		);368369		let mut balances = BTreeMap::new();370		for data in &data {371			let balance = balances372				.entry(&data.owner)373				.or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));374			*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;375376			ensure!(377				*balance <= collection.limits.account_token_ownership_limit(),378				<CommonError<T>>::AccountTokenLimitExceeded,379			);380		}381382		// =========383384		<TokensMinted<T>>::insert(collection.id, tokens_minted);385		for (account, balance) in balances {386			<AccountBalance<T>>::insert((collection.id, account), balance);387		}388		for (i, data) in data.into_iter().enumerate() {389			let token = first_token + i as u32 + 1;390391			<TokenData<T>>::insert(392				(collection.id, token),393				ItemData {394					const_data: data.const_data,395					variable_data: data.variable_data,396					owner: data.owner.clone(),397				},398			);399			<Owned<T>>::insert((collection.id, &data.owner, token), true);400401			collection.log_mirrored(ERC721Events::Transfer {402				from: H160::default(),403				to: *data.owner.as_eth(),404				token_id: token.into(),405			});406			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(407				collection.id,408				TokenId(token),409				data.owner.clone(),410				1,411			));412		}413		Ok(())414	}415416	pub fn set_allowance_unchecked(417		collection: &NonfungibleHandle<T>,418		sender: &T::CrossAccountId,419		token: TokenId,420		spender: Option<&T::CrossAccountId>,421		assume_implicit_eth: bool,422	) {423		if let Some(spender) = spender {424			let old_spender = <Allowance<T>>::get((collection.id, token));425			<Allowance<T>>::insert((collection.id, token), spender);426			// In ERC721 there is only one possible approved user of token, so we set427			// approved user to spender428			collection.log_mirrored(ERC721Events::Approval {429				owner: *sender.as_eth(),430				approved: *spender.as_eth(),431				token_id: token.into(),432			});433			// In Unique chain, any token can have any amount of approved users, so we need to434			// set allowance of old owner to 0, and allowance of new owner to 1435			if old_spender.as_ref() != Some(spender) {436				if let Some(old_owner) = old_spender {437					<PalletCommon<T>>::deposit_event(CommonEvent::Approved(438						collection.id,439						token,440						sender.clone(),441						old_owner,442						0,443					));444				}445				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(446					collection.id,447					token,448					sender.clone(),449					spender.clone(),450					1,451				));452			}453		} else {454			let old_spender = <Allowance<T>>::take((collection.id, token));455			if !assume_implicit_eth {456				// In ERC721 there is only one possible approved user of token, so we set457				// approved user to zero address458				collection.log_mirrored(ERC721Events::Approval {459					owner: *sender.as_eth(),460					approved: H160::default(),461					token_id: token.into(),462				});463			}464			// In Unique chain, any token can have any amount of approved users, so we need to465			// set allowance of old owner to 0466			if let Some(old_spender) = old_spender {467				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(468					collection.id,469					token,470					sender.clone(),471					old_spender,472					0,473				));474			}475		}476	}477478	pub fn set_allowance(479		collection: &NonfungibleHandle<T>,480		sender: &T::CrossAccountId,481		token: TokenId,482		spender: Option<&T::CrossAccountId>,483	) -> DispatchResult {484		if collection.access == AccessMode::AllowList {485			collection.check_allowlist(sender)?;486			if let Some(spender) = spender {487				collection.check_allowlist(spender)?;488			}489		}490491		if let Some(spender) = spender {492			<PalletCommon<T>>::ensure_correct_receiver(spender)?;493		}494		let token_data =495			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;496		if &token_data.owner != sender {497			ensure!(498				collection.ignores_owned_amount(sender),499				<CommonError<T>>::CantApproveMoreThanOwned500			);501		}502503		// =========504505		Self::set_allowance_unchecked(collection, sender, token, spender, false);506		Ok(())507	}508509	fn check_allowed(510		collection: &NonfungibleHandle<T>,511		spender: &T::CrossAccountId,512		from: &T::CrossAccountId,513		token: TokenId,514		nesting_budget: &dyn Budget,515	) -> DispatchResult {516		if spender.conv_eq(from) {517			return Ok(());518		}519		if collection.access == AccessMode::AllowList {520			// `from`, `to` checked in [`transfer`]521			collection.check_allowlist(spender)?;522		}523		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {524			// TODO: should collection owner be allowed to perform this transfer?525			ensure!(526				<PalletStructure<T>>::indirectly_owned(527					spender.clone(),528					source.0,529					source.1,530					nesting_budget531				)?,532				<CommonError<T>>::ApprovedValueTooLow,533			);534			return Ok(());535		}536		if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {537			return Ok(());538		}539		ensure!(540			collection.ignores_allowance(spender),541			<CommonError<T>>::ApprovedValueTooLow542		);543		Ok(())544	}545546	pub fn transfer_from(547		collection: &NonfungibleHandle<T>,548		spender: &T::CrossAccountId,549		from: &T::CrossAccountId,550		to: &T::CrossAccountId,551		token: TokenId,552		nesting_budget: &dyn Budget,553	) -> DispatchResult {554		Self::check_allowed(collection, spender, from, token, nesting_budget)?;555556		// =========557558		// Allowance is reset in [`transfer`]559		Self::transfer(collection, from, to, token)560	}561562	pub fn burn_from(563		collection: &NonfungibleHandle<T>,564		spender: &T::CrossAccountId,565		from: &T::CrossAccountId,566		token: TokenId,567		nesting_budget: &dyn Budget,568	) -> DispatchResult {569		Self::check_allowed(collection, spender, from, token, nesting_budget)?;570571		// =========572573		Self::burn(collection, from, token)574	}575576	pub fn set_variable_metadata(577		collection: &NonfungibleHandle<T>,578		sender: &T::CrossAccountId,579		token: TokenId,580		data: BoundedVec<u8, CustomDataLimit>,581	) -> DispatchResult {582		let token_data =583			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;584		collection.check_can_update_meta(sender, &token_data.owner)?;585586		// =========587588		<TokenData<T>>::insert(589			(collection.id, token),590			ItemData {591				variable_data: data,592				..token_data593			},594		);595		Ok(())596	}597598	pub fn nest_token(599		handle: &NonfungibleHandle<T>,600		sender: T::CrossAccountId,601		from: CollectionId,602		under: TokenId,603	) -> DispatchResult {604		fn ensure_sender_allowed<T: Config>(605			collection: CollectionId,606			token: TokenId,607			sender: T::CrossAccountId,608		) -> DispatchResult {609			ensure!(610				<TokenData<T>>::get((collection, token))611					.ok_or(<CommonError<T>>::TokenNotFound)?612					.owner613					.conv_eq(&sender),614				<CommonError<T>>::OnlyOwnerAllowedToNest,615			);616			Ok(())617		}618		match handle.limits.nesting_rule() {619			NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),620			NestingRule::Owner => ensure_sender_allowed::<T>(from, under, sender)?,621			NestingRule::OwnerRestricted(whitelist) => {622				ensure!(623					whitelist.contains(&from),624					<CommonError<T>>::SourceCollectionIsNotAllowedToNest625				);626				ensure_sender_allowed::<T>(from, under, sender)?627			}628		}629		Ok(())630	}631632	/// Delegated to `create_multiple_items`633	pub fn create_item(634		collection: &NonfungibleHandle<T>,635		sender: &T::CrossAccountId,636		data: CreateItemData<T>,637	) -> DispatchResult {638		Self::create_multiple_items(collection, sender, vec![data])639	}640}
after · pallets/nonfungible/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use erc::ERC721Events;20use frame_support::{BoundedVec, ensure, fail};21use up_data_structs::{22	AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,23	mapping::TokenAddressMapping, NestingRule, budget::Budget,24};25use pallet_evm::account::CrossAccountId;26use pallet_common::{27	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent,28	CollectionHandle, dispatch::CollectionDispatch,29};30use pallet_structure::Pallet as PalletStructure;31use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};32use sp_core::H160;33use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};34use sp_std::{vec::Vec, vec};35use core::ops::Deref;36use sp_std::collections::btree_map::BTreeMap;37use codec::{Encode, Decode, MaxEncodedLen};38use scale_info::TypeInfo;3940pub use pallet::*;41#[cfg(feature = "runtime-benchmarks")]42pub mod benchmarking;43pub mod common;44pub mod erc;45pub mod weights;4647pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;48pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4950#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]51pub struct ItemData<CrossAccountId> {52	pub const_data: BoundedVec<u8, CustomDataLimit>,53	pub variable_data: BoundedVec<u8, CustomDataLimit>,54	pub owner: CrossAccountId,55}5657#[frame_support::pallet]58pub mod pallet {59	use super::*;60	use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};61	use up_data_structs::{CollectionId, TokenId};62	use super::weights::WeightInfo;6364	#[pallet::error]65	pub enum Error<T> {66		/// Not Nonfungible item data used to mint in Nonfungible collection.67		NotNonfungibleDataUsedToMintFungibleCollectionToken,68		/// Used amount > 1 with NFT69		NonfungibleItemsHaveNoAmount,70	}7172	#[pallet::config]73	pub trait Config:74		frame_system::Config + pallet_common::Config + pallet_structure::Config75	{76		type WeightInfo: WeightInfo;77	}7879	#[pallet::pallet]80	#[pallet::generate_store(pub(super) trait Store)]81	pub struct Pallet<T>(_);8283	#[pallet::storage]84	pub type TokensMinted<T: Config> =85		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;86	#[pallet::storage]87	pub type TokensBurnt<T: Config> =88		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;8990	#[pallet::storage]91	pub type TokenData<T: Config> = StorageNMap<92		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),93		Value = ItemData<T::CrossAccountId>,94		QueryKind = OptionQuery,95	>;9697	/// Used to enumerate tokens owned by account98	#[pallet::storage]99	pub type Owned<T: Config> = StorageNMap<100		Key = (101			Key<Twox64Concat, CollectionId>,102			Key<Blake2_128Concat, T::CrossAccountId>,103			Key<Twox64Concat, TokenId>,104		),105		Value = bool,106		QueryKind = ValueQuery,107	>;108109	#[pallet::storage]110	pub type AccountBalance<T: Config> = StorageNMap<111		Key = (112			Key<Twox64Concat, CollectionId>,113			Key<Blake2_128Concat, T::CrossAccountId>,114		),115		Value = u32,116		QueryKind = ValueQuery,117	>;118119	#[pallet::storage]120	pub type Allowance<T: Config> = StorageNMap<121		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),122		Value = T::CrossAccountId,123		QueryKind = OptionQuery,124	>;125}126127pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);128impl<T: Config> NonfungibleHandle<T> {129	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {130		Self(inner)131	}132	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {133		self.0134	}135}136impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {137	fn recorder(&self) -> &SubstrateRecorder<T> {138		self.0.recorder()139	}140	fn into_recorder(self) -> SubstrateRecorder<T> {141		self.0.into_recorder()142	}143}144impl<T: Config> Deref for NonfungibleHandle<T> {145	type Target = pallet_common::CollectionHandle<T>;146147	fn deref(&self) -> &Self::Target {148		&self.0149	}150}151152impl<T: Config> Pallet<T> {153	pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {154		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)155	}156	pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {157		<TokenData<T>>::contains_key((collection.id, token))158	}159}160161// unchecked calls skips any permission checks162impl<T: Config> Pallet<T> {163	pub fn init_collection(164		owner: T::AccountId,165		data: CreateCollectionData<T::AccountId>,166	) -> Result<CollectionId, DispatchError> {167		<PalletCommon<T>>::init_collection(owner, data)168	}169	pub fn destroy_collection(170		collection: NonfungibleHandle<T>,171		sender: &T::CrossAccountId,172	) -> DispatchResult {173		let id = collection.id;174175		// =========176177		PalletCommon::destroy_collection(collection.0, sender)?;178179		<TokenData<T>>::remove_prefix((id,), None);180		<Owned<T>>::remove_prefix((id,), None);181		<TokensMinted<T>>::remove(id);182		<TokensBurnt<T>>::remove(id);183		<Allowance<T>>::remove_prefix((id,), None);184		<AccountBalance<T>>::remove_prefix((id,), None);185		Ok(())186	}187188	pub fn burn(189		collection: &NonfungibleHandle<T>,190		sender: &T::CrossAccountId,191		token: TokenId,192	) -> DispatchResult {193		let token_data =194			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;195		ensure!(196			&token_data.owner == sender197				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),198			<CommonError<T>>::NoPermission199		);200201		if collection.access == AccessMode::AllowList {202			collection.check_allowlist(sender)?;203		}204205		let burnt = <TokensBurnt<T>>::get(collection.id)206			.checked_add(1)207			.ok_or(ArithmeticError::Overflow)?;208209		let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))210			.checked_sub(1)211			.ok_or(ArithmeticError::Overflow)?;212213		if balance == 0 {214			<AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));215		} else {216			<AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);217		}218		// =========219220		<Owned<T>>::remove((collection.id, &token_data.owner, token));221		<TokensBurnt<T>>::insert(collection.id, burnt);222		<TokenData<T>>::remove((collection.id, token));223		let old_spender = <Allowance<T>>::take((collection.id, token));224225		if let Some(old_spender) = old_spender {226			<PalletCommon<T>>::deposit_event(CommonEvent::Approved(227				collection.id,228				token,229				sender.clone(),230				old_spender,231				0,232			));233		}234235		collection.log_mirrored(ERC721Events::Transfer {236			from: *token_data.owner.as_eth(),237			to: H160::default(),238			token_id: token.into(),239		});240		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(241			collection.id,242			token,243			token_data.owner,244			1,245		));246		Ok(())247	}248249	pub fn transfer(250		collection: &NonfungibleHandle<T>,251		from: &T::CrossAccountId,252		to: &T::CrossAccountId,253		token: TokenId,254		nesting_budget: &dyn Budget,255	) -> DispatchResult {256		ensure!(257			collection.limits.transfers_enabled(),258			<CommonError<T>>::TransferNotAllowed259		);260261		let token_data =262			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;263		// TODO: require sender to be token, owner, require admins to go through transfer_from264		ensure!(265			&token_data.owner == from266				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),267			<CommonError<T>>::NoPermission268		);269270		if collection.access == AccessMode::AllowList {271			collection.check_allowlist(from)?;272			collection.check_allowlist(to)?;273		}274		<PalletCommon<T>>::ensure_correct_receiver(to)?;275276		let balance_from = <AccountBalance<T>>::get((collection.id, from))277			.checked_sub(1)278			.ok_or(<CommonError<T>>::TokenValueTooLow)?;279		let balance_to = if from != to {280			let balance_to = <AccountBalance<T>>::get((collection.id, to))281				.checked_add(1)282				.ok_or(ArithmeticError::Overflow)?;283284			ensure!(285				balance_to < collection.limits.account_token_ownership_limit(),286				<CommonError<T>>::AccountTokenLimitExceeded,287			);288289			Some(balance_to)290		} else {291			None292		};293294		if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {295			let handle = <CollectionHandle<T>>::try_get(target.0)?;296			let dispatch = T::CollectionDispatch::dispatch(handle);297			let dispatch = dispatch.as_dyn();298299			dispatch.check_nesting(from.clone(), collection.id, target.1, nesting_budget)?;300		}301302		// =========303304		<TokenData<T>>::insert(305			(collection.id, token),306			ItemData {307				owner: to.clone(),308				..token_data309			},310		);311312		if let Some(balance_to) = balance_to {313			// from != to314			if balance_from == 0 {315				<AccountBalance<T>>::remove((collection.id, from));316			} else {317				<AccountBalance<T>>::insert((collection.id, from), balance_from);318			}319			<AccountBalance<T>>::insert((collection.id, to), balance_to);320			<Owned<T>>::remove((collection.id, from, token));321			<Owned<T>>::insert((collection.id, to, token), true);322		}323		Self::set_allowance_unchecked(collection, from, token, None, true);324325		collection.log_mirrored(ERC721Events::Transfer {326			from: *from.as_eth(),327			to: *to.as_eth(),328			token_id: token.into(),329		});330		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(331			collection.id,332			token,333			from.clone(),334			to.clone(),335			1,336		));337		Ok(())338	}339340	pub fn create_multiple_items(341		collection: &NonfungibleHandle<T>,342		sender: &T::CrossAccountId,343		data: Vec<CreateItemData<T>>,344		nesting_budget: &dyn Budget,345	) -> DispatchResult {346		if !collection.is_owner_or_admin(sender) {347			ensure!(348				collection.mint_mode,349				<CommonError<T>>::PublicMintingNotAllowed350			);351			collection.check_allowlist(sender)?;352353			for item in data.iter() {354				collection.check_allowlist(&item.owner)?;355			}356		}357358		for data in data.iter() {359			<PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;360		}361362		let first_token = <TokensMinted<T>>::get(collection.id);363		let tokens_minted = first_token364			.checked_add(data.len() as u32)365			.ok_or(ArithmeticError::Overflow)?;366		ensure!(367			tokens_minted <= collection.limits.token_limit(),368			<CommonError<T>>::CollectionTokenLimitExceeded369		);370371		let mut balances = BTreeMap::new();372		for data in &data {373			let balance = balances374				.entry(&data.owner)375				.or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));376			*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;377378			ensure!(379				*balance <= collection.limits.account_token_ownership_limit(),380				<CommonError<T>>::AccountTokenLimitExceeded,381			);382		}383384		for (to, _) in balances.iter() {385			if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {386				let handle = <CollectionHandle<T>>::try_get(target.0)?;387				let dispatch = T::CollectionDispatch::dispatch(handle);388				let dispatch = dispatch.as_dyn();389390				dispatch.check_nesting(sender.clone(), collection.id, target.1, nesting_budget)?;391			}392		}393394		// =========395396		<TokensMinted<T>>::insert(collection.id, tokens_minted);397		for (account, balance) in balances {398			<AccountBalance<T>>::insert((collection.id, account), balance);399		}400		for (i, data) in data.into_iter().enumerate() {401			let token = first_token + i as u32 + 1;402403			<TokenData<T>>::insert(404				(collection.id, token),405				ItemData {406					const_data: data.const_data,407					variable_data: data.variable_data,408					owner: data.owner.clone(),409				},410			);411			<Owned<T>>::insert((collection.id, &data.owner, token), true);412413			collection.log_mirrored(ERC721Events::Transfer {414				from: H160::default(),415				to: *data.owner.as_eth(),416				token_id: token.into(),417			});418			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(419				collection.id,420				TokenId(token),421				data.owner.clone(),422				1,423			));424		}425		Ok(())426	}427428	pub fn set_allowance_unchecked(429		collection: &NonfungibleHandle<T>,430		sender: &T::CrossAccountId,431		token: TokenId,432		spender: Option<&T::CrossAccountId>,433		assume_implicit_eth: bool,434	) {435		if let Some(spender) = spender {436			let old_spender = <Allowance<T>>::get((collection.id, token));437			<Allowance<T>>::insert((collection.id, token), spender);438			// In ERC721 there is only one possible approved user of token, so we set439			// approved user to spender440			collection.log_mirrored(ERC721Events::Approval {441				owner: *sender.as_eth(),442				approved: *spender.as_eth(),443				token_id: token.into(),444			});445			// In Unique chain, any token can have any amount of approved users, so we need to446			// set allowance of old owner to 0, and allowance of new owner to 1447			if old_spender.as_ref() != Some(spender) {448				if let Some(old_owner) = old_spender {449					<PalletCommon<T>>::deposit_event(CommonEvent::Approved(450						collection.id,451						token,452						sender.clone(),453						old_owner,454						0,455					));456				}457				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(458					collection.id,459					token,460					sender.clone(),461					spender.clone(),462					1,463				));464			}465		} else {466			let old_spender = <Allowance<T>>::take((collection.id, token));467			if !assume_implicit_eth {468				// In ERC721 there is only one possible approved user of token, so we set469				// approved user to zero address470				collection.log_mirrored(ERC721Events::Approval {471					owner: *sender.as_eth(),472					approved: H160::default(),473					token_id: token.into(),474				});475			}476			// In Unique chain, any token can have any amount of approved users, so we need to477			// set allowance of old owner to 0478			if let Some(old_spender) = old_spender {479				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(480					collection.id,481					token,482					sender.clone(),483					old_spender,484					0,485				));486			}487		}488	}489490	pub fn set_allowance(491		collection: &NonfungibleHandle<T>,492		sender: &T::CrossAccountId,493		token: TokenId,494		spender: Option<&T::CrossAccountId>,495	) -> DispatchResult {496		if collection.access == AccessMode::AllowList {497			collection.check_allowlist(sender)?;498			if let Some(spender) = spender {499				collection.check_allowlist(spender)?;500			}501		}502503		if let Some(spender) = spender {504			<PalletCommon<T>>::ensure_correct_receiver(spender)?;505		}506		let token_data =507			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;508		if &token_data.owner != sender {509			ensure!(510				collection.ignores_owned_amount(sender),511				<CommonError<T>>::CantApproveMoreThanOwned512			);513		}514515		// =========516517		Self::set_allowance_unchecked(collection, sender, token, spender, false);518		Ok(())519	}520521	fn check_allowed(522		collection: &NonfungibleHandle<T>,523		spender: &T::CrossAccountId,524		from: &T::CrossAccountId,525		token: TokenId,526		nesting_budget: &dyn Budget,527	) -> DispatchResult {528		if spender.conv_eq(from) {529			return Ok(());530		}531		if collection.access == AccessMode::AllowList {532			// `from`, `to` checked in [`transfer`]533			collection.check_allowlist(spender)?;534		}535		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {536			// TODO: should collection owner be allowed to perform this transfer?537			ensure!(538				<PalletStructure<T>>::indirectly_owned(539					spender.clone(),540					source.0,541					source.1,542					nesting_budget543				)?,544				<CommonError<T>>::ApprovedValueTooLow,545			);546			return Ok(());547		}548		if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {549			return Ok(());550		}551		ensure!(552			collection.ignores_allowance(spender),553			<CommonError<T>>::ApprovedValueTooLow554		);555		Ok(())556	}557558	pub fn transfer_from(559		collection: &NonfungibleHandle<T>,560		spender: &T::CrossAccountId,561		from: &T::CrossAccountId,562		to: &T::CrossAccountId,563		token: TokenId,564		nesting_budget: &dyn Budget,565	) -> DispatchResult {566		Self::check_allowed(collection, spender, from, token, nesting_budget)?;567568		// =========569570		// Allowance is reset in [`transfer`]571		Self::transfer(collection, from, to, token, nesting_budget)572	}573574	pub fn burn_from(575		collection: &NonfungibleHandle<T>,576		spender: &T::CrossAccountId,577		from: &T::CrossAccountId,578		token: TokenId,579		nesting_budget: &dyn Budget,580	) -> DispatchResult {581		Self::check_allowed(collection, spender, from, token, nesting_budget)?;582583		// =========584585		Self::burn(collection, from, token)586	}587588	pub fn set_variable_metadata(589		collection: &NonfungibleHandle<T>,590		sender: &T::CrossAccountId,591		token: TokenId,592		data: BoundedVec<u8, CustomDataLimit>,593	) -> DispatchResult {594		let token_data =595			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;596		collection.check_can_update_meta(sender, &token_data.owner)?;597598		// =========599600		<TokenData<T>>::insert(601			(collection.id, token),602			ItemData {603				variable_data: data,604				..token_data605			},606		);607		Ok(())608	}609610	pub fn check_nesting(611		handle: &NonfungibleHandle<T>,612		sender: T::CrossAccountId,613		from: CollectionId,614		under: TokenId,615		nesting_budget: &dyn Budget,616	) -> DispatchResult {617		fn ensure_sender_allowed<T: Config>(618			collection: CollectionId,619			token: TokenId,620			sender: T::CrossAccountId,621			budget: &dyn Budget,622		) -> DispatchResult {623			ensure!(624				<PalletStructure<T>>::indirectly_owned(sender, collection, token, budget)?,625				<CommonError<T>>::OnlyOwnerAllowedToNest,626			);627			Ok(())628		}629		match handle.limits.nesting_rule() {630			NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),631			NestingRule::Owner => ensure_sender_allowed::<T>(from, under, sender, nesting_budget)?,632			NestingRule::OwnerRestricted(whitelist) => {633				ensure!(634					whitelist.contains(&from),635					<CommonError<T>>::SourceCollectionIsNotAllowedToNest636				);637				ensure_sender_allowed::<T>(from, under, sender, nesting_budget)?638			}639		}640		Ok(())641	}642643	/// Delegated to `create_multiple_items`644	pub fn create_item(645		collection: &NonfungibleHandle<T>,646		sender: &T::CrossAccountId,647		data: CreateItemData<T>,648		nesting_budget: &dyn Budget,649	) -> DispatchResult {650		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)651	}652}
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -19,7 +19,8 @@
 use sp_std::collections::btree_map::BTreeMap;
 use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight, BoundedVec};
 use up_data_structs::{
-	TokenId, CustomDataLimit, CreateItemExData, CreateRefungibleExData, budget::Budget,
+	CollectionId, TokenId, CustomDataLimit, CreateItemExData, CreateRefungibleExData,
+	budget::Budget,
 };
 use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
 use sp_runtime::DispatchError;
@@ -120,9 +121,15 @@
 		sender: T::CrossAccountId,
 		to: T::CrossAccountId,
 		data: up_data_structs::CreateItemData,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo {
 		with_weight(
-			<Pallet<T>>::create_item(self, &sender, map_create_data::<T>(data, &to)?),
+			<Pallet<T>>::create_item(
+				self,
+				&sender,
+				map_create_data::<T>(data, &to)?,
+				nesting_budget,
+			),
 			<CommonWeights<T>>::create_item(),
 		)
 	}
@@ -132,6 +139,7 @@
 		sender: T::CrossAccountId,
 		to: T::CrossAccountId,
 		data: Vec<up_data_structs::CreateItemData>,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo {
 		let data = data
 			.into_iter()
@@ -140,7 +148,7 @@
 
 		let amount = data.len();
 		with_weight(
-			<Pallet<T>>::create_multiple_items(self, &sender, data),
+			<Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),
 			<CommonWeights<T>>::create_multiple_items(amount as u32),
 		)
 	}
@@ -149,6 +157,7 @@
 		&self,
 		sender: <T>::CrossAccountId,
 		data: CreateItemExData<T::CrossAccountId>,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo {
 		let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);
 		let data = match data {
@@ -162,7 +171,7 @@
 		};
 
 		with_weight(
-			<Pallet<T>>::create_multiple_items(self, &sender, data),
+			<Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),
 			weight,
 		)
 	}
@@ -185,9 +194,10 @@
 		to: T::CrossAccountId,
 		token: TokenId,
 		amount: u128,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo {
 		with_weight(
-			<Pallet<T>>::transfer(self, &from, &to, token, amount),
+			<Pallet<T>>::transfer(self, &from, &to, token, amount, nesting_budget),
 			<CommonWeights<T>>::transfer(),
 		)
 	}
@@ -247,11 +257,12 @@
 		)
 	}
 
-	fn nest_token(
+	fn check_nesting(
 		&self,
 		_sender: <T>::CrossAccountId,
-		_from: (up_data_structs::CollectionId, TokenId),
+		_from: CollectionId,
 		_under: TokenId,
+		_budget: &dyn Budget,
 	) -> sp_runtime::DispatchResult {
 		fail!(<Error<T>>::RefungibleDisallowsNesting)
 	}
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -289,6 +289,7 @@
 		to: &T::CrossAccountId,
 		token: TokenId,
 		amount: u128,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
 		ensure!(
 			collection.limits.transfers_enabled(),
@@ -351,10 +352,10 @@
 			let dispatch = T::CollectionDispatch::dispatch(handle);
 			let dispatch = dispatch.as_dyn();
 
-			// =========
+			dispatch.check_nesting(from.clone(), collection.id, target.1, nesting_budget)?;
+		}
 
-			dispatch.nest_token(from.clone(), (collection.id, token), target.1)?;
-		}
+		// =========
 
 		if let Some(balance_to) = balance_to {
 			// from != to
@@ -389,6 +390,7 @@
 		collection: &RefungibleHandle<T>,
 		sender: &T::CrossAccountId,
 		data: Vec<CreateRefungibleExData<T::CrossAccountId>>,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
 		if !collection.is_owner_or_admin(sender) {
 			ensure!(
@@ -453,6 +455,23 @@
 			}
 		}
 
+		for token in data.iter() {
+			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,
+						target.1,
+						nesting_budget,
+					)?;
+				}
+			}
+		}
+
 		// =========
 
 		<TokensMinted<T>>::insert(collection.id, tokens_minted);
@@ -591,7 +610,7 @@
 
 		// =========
 
-		Self::transfer(collection, from, to, token, amount)?;
+		Self::transfer(collection, from, to, token, amount, nesting_budget)?;
 		if let Some(allowance) = allowance {
 			Self::set_allowance_unchecked(collection, from, spender, token, allowance);
 		}
@@ -648,7 +667,8 @@
 		collection: &RefungibleHandle<T>,
 		sender: &T::CrossAccountId,
 		data: CreateRefungibleExData<T::CrossAccountId>,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
-		Self::create_multiple_items(collection, sender, vec![data])
+		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)
 	}
 }
modifiedpallets/structure/src/lib.rsdiffbeforeafterboth
--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -19,7 +19,6 @@
 	use frame_support::Parameter;
 	use frame_support::dispatch::{GetDispatchInfo, UnfilteredDispatchable};
 	use frame_support::pallet_prelude::*;
-	use frame_system::pallet_prelude::*;
 
 	use super::*;
 
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -693,8 +693,9 @@
 		#[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);
 
-			dispatch_call::<T, _>(collection_id, |d| d.create_item(sender, owner, data))
+			dispatch_call::<T, _>(collection_id, |d| d.create_item(sender, owner, data, &budget))
 		}
 
 		/// This method creates multiple items in a collection created with CreateCollection method.
@@ -720,16 +721,18 @@
 		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);
 
-			dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items(sender, owner, items_data))
+			dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items(sender, owner, items_data, &budget))
 		}
 
 		#[weight = <CommonWeights<T>>::create_multiple_items_ex(&data)]
 		#[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);
 
-			dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items_ex(sender, data))
+			dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items_ex(sender, data, &budget))
 		}
 
 		// TODO! transaction weight
@@ -839,8 +842,9 @@
 		#[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);
 
-			dispatch_call::<T, _>(collection_id, |d| d.transfer(sender, recipient, item_id, value))
+			dispatch_call::<T, _>(collection_id, |d| d.transfer(sender, recipient, item_id, value, &budget))
 		}
 
 		/// Set, change, or remove approved address to transfer the ownership of the NFT.