git.delta.rocks / unique-network / refs/commits / 4e0b740f5ec1

difftreelog

fix remove properties when item destroyed

Daniel Shiposha2022-05-18parent: #30e6f4b.patch.diff
in: master

2 files changed

modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -762,6 +762,7 @@
 		<AdminAmount<T>>::remove(collection.id);
 		<IsAdmin<T>>::remove_prefix((collection.id,), None);
 		<Allowlist<T>>::remove_prefix((collection.id,), None);
+		<CollectionProperties<T>>::remove(collection.id);
 
 		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));
 		Ok(())
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 evm_coder::ToLog;21use frame_support::{BoundedVec, ensure, fail, transactional};22use up_data_structs::{23	AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,24	mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,25	PropertyKey, PropertyKeyPermission, Properties, TrySetProperty,26};27use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};28use pallet_common::{29	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,30	dispatch::CollectionDispatch, eth::collection_id_to_address,31};32use pallet_structure::Pallet as PalletStructure;33use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};34use sp_core::H160;35use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};36use sp_std::{vec::Vec, vec};37use core::ops::Deref;38use sp_std::collections::btree_map::BTreeMap;39use codec::{Encode, Decode, MaxEncodedLen};40use scale_info::TypeInfo;4142pub use pallet::*;43#[cfg(feature = "runtime-benchmarks")]44pub mod benchmarking;45pub mod common;46pub mod erc;47pub mod weights;4849pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;50pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;5152#[struct_versioning::versioned(version = 2, upper)]53#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]54pub struct ItemData<CrossAccountId> {55	pub const_data: BoundedVec<u8, CustomDataLimit>,5657	#[version(..2)]58	pub variable_data: BoundedVec<u8, CustomDataLimit>,5960	pub owner: CrossAccountId,61}6263#[frame_support::pallet]64pub mod pallet {65	use super::*;66	use frame_support::{67		Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,68	};69	use frame_system::pallet_prelude::*;70	use up_data_structs::{CollectionId, TokenId};71	use super::weights::WeightInfo;7273	#[pallet::error]74	pub enum Error<T> {75		/// Not Nonfungible item data used to mint in Nonfungible collection.76		NotNonfungibleDataUsedToMintFungibleCollectionToken,77		/// Used amount > 1 with NFT78		NonfungibleItemsHaveNoAmount,79	}8081	#[pallet::config]82	pub trait Config:83		frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config84	{85		type WeightInfo: WeightInfo;86	}8788	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);8990	#[pallet::pallet]91	#[pallet::storage_version(STORAGE_VERSION)]92	#[pallet::generate_store(pub(super) trait Store)]93	pub struct Pallet<T>(_);9495	#[pallet::storage]96	pub type TokensMinted<T: Config> =97		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;98	#[pallet::storage]99	pub type TokensBurnt<T: Config> =100		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;101102	#[pallet::storage]103	pub type TokenData<T: Config> = StorageNMap<104		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),105		Value = ItemData<T::CrossAccountId>,106		QueryKind = OptionQuery,107	>;108109	#[pallet::storage]110	#[pallet::getter(fn token_properties)]111	pub type TokenProperties<T: Config> = StorageNMap<112		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),113		Value = Properties,114		QueryKind = ValueQuery,115		OnEmpty = up_data_structs::TokenProperties,116	>;117118	/// Used to enumerate tokens owned by account119	#[pallet::storage]120	pub type Owned<T: Config> = StorageNMap<121		Key = (122			Key<Twox64Concat, CollectionId>,123			Key<Blake2_128Concat, T::CrossAccountId>,124			Key<Twox64Concat, TokenId>,125		),126		Value = bool,127		QueryKind = ValueQuery,128	>;129130	#[pallet::storage]131	pub type AccountBalance<T: Config> = StorageNMap<132		Key = (133			Key<Twox64Concat, CollectionId>,134			Key<Blake2_128Concat, T::CrossAccountId>,135		),136		Value = u32,137		QueryKind = ValueQuery,138	>;139140	#[pallet::storage]141	pub type Allowance<T: Config> = StorageNMap<142		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),143		Value = T::CrossAccountId,144		QueryKind = OptionQuery,145	>;146147	#[pallet::hooks]148	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {149		fn on_runtime_upgrade() -> Weight {150			if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {151				<TokenData<T>>::translate_values::<ItemDataVersion1<T::CrossAccountId>, _>(|v| {152					Some(<ItemDataVersion2<T::CrossAccountId>>::from(v))153				})154			}155156			0157		}158	}159}160161pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);162impl<T: Config> NonfungibleHandle<T> {163	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {164		Self(inner)165	}166	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {167		self.0168	}169	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {170		&mut self.0171	}172}173impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {174	fn recorder(&self) -> &SubstrateRecorder<T> {175		self.0.recorder()176	}177	fn into_recorder(self) -> SubstrateRecorder<T> {178		self.0.into_recorder()179	}180}181impl<T: Config> Deref for NonfungibleHandle<T> {182	type Target = pallet_common::CollectionHandle<T>;183184	fn deref(&self) -> &Self::Target {185		&self.0186	}187}188189impl<T: Config> Pallet<T> {190	pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {191		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)192	}193	pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {194		<TokenData<T>>::contains_key((collection.id, token))195	}196}197198// unchecked calls skips any permission checks199impl<T: Config> Pallet<T> {200	pub fn init_collection(201		owner: T::AccountId,202		data: CreateCollectionData<T::AccountId>,203	) -> Result<CollectionId, DispatchError> {204		<PalletCommon<T>>::init_collection(owner, data)205	}206	pub fn destroy_collection(207		collection: NonfungibleHandle<T>,208		sender: &T::CrossAccountId,209	) -> DispatchResult {210		let id = collection.id;211212		// =========213214		PalletCommon::destroy_collection(collection.0, sender)?;215216		<TokenData<T>>::remove_prefix((id,), None);217		<Owned<T>>::remove_prefix((id,), None);218		<TokensMinted<T>>::remove(id);219		<TokensBurnt<T>>::remove(id);220		<Allowance<T>>::remove_prefix((id,), None);221		<AccountBalance<T>>::remove_prefix((id,), None);222		Ok(())223	}224225	pub fn burn(226		collection: &NonfungibleHandle<T>,227		sender: &T::CrossAccountId,228		token: TokenId,229	) -> DispatchResult {230		let token_data =231			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;232		ensure!(233			&token_data.owner == sender234				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),235			<CommonError<T>>::NoPermission236		);237238		if collection.access == AccessMode::AllowList {239			collection.check_allowlist(sender)?;240		}241242		let burnt = <TokensBurnt<T>>::get(collection.id)243			.checked_add(1)244			.ok_or(ArithmeticError::Overflow)?;245246		let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))247			.checked_sub(1)248			.ok_or(ArithmeticError::Overflow)?;249250		if balance == 0 {251			<AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));252		} else {253			<AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);254		}255		// =========256257		<Owned<T>>::remove((collection.id, &token_data.owner, token));258		<TokensBurnt<T>>::insert(collection.id, burnt);259		<TokenData<T>>::remove((collection.id, token));260		let old_spender = <Allowance<T>>::take((collection.id, token));261262		if let Some(old_spender) = old_spender {263			<PalletCommon<T>>::deposit_event(CommonEvent::Approved(264				collection.id,265				token,266				sender.clone(),267				old_spender,268				0,269			));270		}271272		<PalletEvm<T>>::deposit_log(273			ERC721Events::Transfer {274				from: *token_data.owner.as_eth(),275				to: H160::default(),276				token_id: token.into(),277			}278			.to_log(collection_id_to_address(collection.id)),279		);280		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(281			collection.id,282			token,283			token_data.owner,284			1,285		));286		Ok(())287	}288289	pub fn set_token_property(290		collection: &NonfungibleHandle<T>,291		sender: &T::CrossAccountId,292		token_id: TokenId,293		property: Property,294	) -> DispatchResult {295		Self::check_token_change_permission(collection, sender, token_id, &property.key)?;296297		<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {298			let property = property.clone();299			properties.try_set(property.key, property.value)300		})301		.map_err(<CommonError<T>>::from)?;302303		<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(304			collection.id,305			token_id,306			property.key,307		));308309		Ok(())310	}311312	#[transactional]313	pub fn set_token_properties(314		collection: &NonfungibleHandle<T>,315		sender: &T::CrossAccountId,316		token_id: TokenId,317		properties: Vec<Property>,318	) -> DispatchResult {319		for property in properties {320			Self::set_token_property(collection, sender, token_id, property)?;321		}322323		Ok(())324	}325326	pub fn delete_token_property(327		collection: &NonfungibleHandle<T>,328		sender: &T::CrossAccountId,329		token_id: TokenId,330		property_key: PropertyKey,331	) -> DispatchResult {332		Self::check_token_change_permission(collection, sender, token_id, &property_key)?;333334		<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {335			properties.remove(&property_key)336		})337		.map_err(<CommonError<T>>::from)?;338339		<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(340			collection.id,341			token_id,342			property_key,343		));344345		Ok(())346	}347348	fn check_token_change_permission(349		collection: &NonfungibleHandle<T>,350		sender: &T::CrossAccountId,351		token_id: TokenId,352		property_key: &PropertyKey,353	) -> DispatchResult {354		let permission = <PalletCommon<T>>::property_permissions(collection.id)355			.get(property_key)356			.cloned()357			.unwrap_or_else(PropertyPermission::none);358359		let token_data = <TokenData<T>>::get((collection.id, token_id))360			.ok_or(<CommonError<T>>::TokenNotFound)?;361362		let check_token_owner = || -> DispatchResult {363			ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);364			Ok(())365		};366367		let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))368			.get(property_key)369			.is_some();370371		match permission {372			PropertyPermission { mutable: false, .. } if is_property_exists => {373				Err(<CommonError<T>>::NoPermission.into())374			}375376			PropertyPermission {377				collection_admin,378				token_owner,379				..380			} => {381				let mut check_result = Err(<CommonError<T>>::NoPermission.into());382383				if collection_admin {384					check_result = collection.check_is_owner_or_admin(sender);385				}386387				if token_owner {388					check_result.or_else(|_| check_token_owner())389				} else {390					check_result391				}392			}393		}394	}395396	#[transactional]397	pub fn delete_token_properties(398		collection: &NonfungibleHandle<T>,399		sender: &T::CrossAccountId,400		token_id: TokenId,401		property_keys: Vec<PropertyKey>,402	) -> DispatchResult {403		for key in property_keys {404			Self::delete_token_property(collection, sender, token_id, key)?;405		}406407		Ok(())408	}409410	pub fn set_collection_properties(411		collection: &NonfungibleHandle<T>,412		sender: &T::CrossAccountId,413		properties: Vec<Property>,414	) -> DispatchResult {415		<PalletCommon<T>>::set_collection_properties(collection, sender, properties)416	}417418	pub fn delete_collection_properties(419		collection: &CollectionHandle<T>,420		sender: &T::CrossAccountId,421		property_keys: Vec<PropertyKey>,422	) -> DispatchResult {423		<PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)424	}425426	pub fn set_property_permissions(427		collection: &CollectionHandle<T>,428		sender: &T::CrossAccountId,429		property_permissions: Vec<PropertyKeyPermission>,430	) -> DispatchResult {431		<PalletCommon<T>>::set_property_permissions(collection, sender, property_permissions)432	}433434	pub fn set_property_permission(435		collection: &CollectionHandle<T>,436		sender: &T::CrossAccountId,437		permission: PropertyKeyPermission,438	) -> DispatchResult {439		<PalletCommon<T>>::set_property_permission(collection, sender, permission)440	}441442	pub fn transfer(443		collection: &NonfungibleHandle<T>,444		from: &T::CrossAccountId,445		to: &T::CrossAccountId,446		token: TokenId,447		nesting_budget: &dyn Budget,448	) -> DispatchResult {449		ensure!(450			collection.limits.transfers_enabled(),451			<CommonError<T>>::TransferNotAllowed452		);453454		let token_data =455			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;456		// TODO: require sender to be token, owner, require admins to go through transfer_from457		ensure!(458			&token_data.owner == from459				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),460			<CommonError<T>>::NoPermission461		);462463		if collection.access == AccessMode::AllowList {464			collection.check_allowlist(from)?;465			collection.check_allowlist(to)?;466		}467		<PalletCommon<T>>::ensure_correct_receiver(to)?;468469		let balance_from = <AccountBalance<T>>::get((collection.id, from))470			.checked_sub(1)471			.ok_or(<CommonError<T>>::TokenValueTooLow)?;472		let balance_to = if from != to {473			let balance_to = <AccountBalance<T>>::get((collection.id, to))474				.checked_add(1)475				.ok_or(ArithmeticError::Overflow)?;476477			ensure!(478				balance_to < collection.limits.account_token_ownership_limit(),479				<CommonError<T>>::AccountTokenLimitExceeded,480			);481482			Some(balance_to)483		} else {484			None485		};486487		if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {488			let handle = <CollectionHandle<T>>::try_get(target.0)?;489			let dispatch = T::CollectionDispatch::dispatch(handle);490			let dispatch = dispatch.as_dyn();491492			dispatch.check_nesting(493				from.clone(),494				(collection.id, token),495				target.1,496				nesting_budget,497			)?;498		}499500		// =========501502		<TokenData<T>>::insert(503			(collection.id, token),504			ItemData {505				owner: to.clone(),506				..token_data507			},508		);509510		if let Some(balance_to) = balance_to {511			// from != to512			if balance_from == 0 {513				<AccountBalance<T>>::remove((collection.id, from));514			} else {515				<AccountBalance<T>>::insert((collection.id, from), balance_from);516			}517			<AccountBalance<T>>::insert((collection.id, to), balance_to);518			<Owned<T>>::remove((collection.id, from, token));519			<Owned<T>>::insert((collection.id, to, token), true);520		}521		Self::set_allowance_unchecked(collection, from, token, None, true);522523		<PalletEvm<T>>::deposit_log(524			ERC721Events::Transfer {525				from: *from.as_eth(),526				to: *to.as_eth(),527				token_id: token.into(),528			}529			.to_log(collection_id_to_address(collection.id)),530		);531		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(532			collection.id,533			token,534			from.clone(),535			to.clone(),536			1,537		));538		Ok(())539	}540541	pub fn create_multiple_items(542		collection: &NonfungibleHandle<T>,543		sender: &T::CrossAccountId,544		data: Vec<CreateItemData<T>>,545		nesting_budget: &dyn Budget,546	) -> DispatchResult {547		if !collection.is_owner_or_admin(sender) {548			ensure!(549				collection.mint_mode,550				<CommonError<T>>::PublicMintingNotAllowed551			);552			collection.check_allowlist(sender)?;553554			for item in data.iter() {555				collection.check_allowlist(&item.owner)?;556			}557		}558559		for data in data.iter() {560			<PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;561		}562563		let first_token = <TokensMinted<T>>::get(collection.id);564		let tokens_minted = first_token565			.checked_add(data.len() as u32)566			.ok_or(ArithmeticError::Overflow)?;567		ensure!(568			tokens_minted <= collection.limits.token_limit(),569			<CommonError<T>>::CollectionTokenLimitExceeded570		);571572		let mut balances = BTreeMap::new();573		for data in &data {574			let balance = balances575				.entry(&data.owner)576				.or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));577			*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;578579			ensure!(580				*balance <= collection.limits.account_token_ownership_limit(),581				<CommonError<T>>::AccountTokenLimitExceeded,582			);583		}584585		for (i, data) in data.iter().enumerate() {586			let token = TokenId(first_token + i as u32 + 1);587			if let Some(target) = T::CrossTokenAddressMapping::address_to_token(&data.owner) {588				let handle = <CollectionHandle<T>>::try_get(target.0)?;589				let dispatch = T::CollectionDispatch::dispatch(handle);590				let dispatch = dispatch.as_dyn();591				dispatch.check_nesting(592					sender.clone(),593					(collection.id, token),594					target.1,595					nesting_budget,596				)?;597			}598		}599600		// =========601602		<TokensMinted<T>>::insert(collection.id, tokens_minted);603		for (account, balance) in balances {604			<AccountBalance<T>>::insert((collection.id, account), balance);605		}606		for (i, data) in data.into_iter().enumerate() {607			let token = first_token + i as u32 + 1;608609			<TokenData<T>>::insert(610				(collection.id, token),611				ItemData {612					const_data: data.const_data,613					owner: data.owner.clone(),614				},615			);616			<Owned<T>>::insert((collection.id, &data.owner, token), true);617618			Self::set_token_properties(619				collection,620				sender,621				TokenId(token),622				data.properties.into_inner(),623			)?;624625			<PalletEvm<T>>::deposit_log(626				ERC721Events::Transfer {627					from: H160::default(),628					to: *data.owner.as_eth(),629					token_id: token.into(),630				}631				.to_log(collection_id_to_address(collection.id)),632			);633			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(634				collection.id,635				TokenId(token),636				data.owner.clone(),637				1,638			));639		}640		Ok(())641	}642643	pub fn set_allowance_unchecked(644		collection: &NonfungibleHandle<T>,645		sender: &T::CrossAccountId,646		token: TokenId,647		spender: Option<&T::CrossAccountId>,648		assume_implicit_eth: bool,649	) {650		if let Some(spender) = spender {651			let old_spender = <Allowance<T>>::get((collection.id, token));652			<Allowance<T>>::insert((collection.id, token), spender);653			// In ERC721 there is only one possible approved user of token, so we set654			// approved user to spender655			<PalletEvm<T>>::deposit_log(656				ERC721Events::Approval {657					owner: *sender.as_eth(),658					approved: *spender.as_eth(),659					token_id: token.into(),660				}661				.to_log(collection_id_to_address(collection.id)),662			);663			// In Unique chain, any token can have any amount of approved users, so we need to664			// set allowance of old owner to 0, and allowance of new owner to 1665			if old_spender.as_ref() != Some(spender) {666				if let Some(old_owner) = old_spender {667					<PalletCommon<T>>::deposit_event(CommonEvent::Approved(668						collection.id,669						token,670						sender.clone(),671						old_owner,672						0,673					));674				}675				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(676					collection.id,677					token,678					sender.clone(),679					spender.clone(),680					1,681				));682			}683		} else {684			let old_spender = <Allowance<T>>::take((collection.id, token));685			if !assume_implicit_eth {686				// In ERC721 there is only one possible approved user of token, so we set687				// approved user to zero address688				<PalletEvm<T>>::deposit_log(689					ERC721Events::Approval {690						owner: *sender.as_eth(),691						approved: H160::default(),692						token_id: token.into(),693					}694					.to_log(collection_id_to_address(collection.id)),695				);696			}697			// In Unique chain, any token can have any amount of approved users, so we need to698			// set allowance of old owner to 0699			if let Some(old_spender) = old_spender {700				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(701					collection.id,702					token,703					sender.clone(),704					old_spender,705					0,706				));707			}708		}709	}710711	pub fn set_allowance(712		collection: &NonfungibleHandle<T>,713		sender: &T::CrossAccountId,714		token: TokenId,715		spender: Option<&T::CrossAccountId>,716	) -> DispatchResult {717		if collection.access == AccessMode::AllowList {718			collection.check_allowlist(sender)?;719			if let Some(spender) = spender {720				collection.check_allowlist(spender)?;721			}722		}723724		if let Some(spender) = spender {725			<PalletCommon<T>>::ensure_correct_receiver(spender)?;726		}727		let token_data =728			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;729		if &token_data.owner != sender {730			ensure!(731				collection.ignores_owned_amount(sender),732				<CommonError<T>>::CantApproveMoreThanOwned733			);734		}735736		// =========737738		Self::set_allowance_unchecked(collection, sender, token, spender, false);739		Ok(())740	}741742	fn check_allowed(743		collection: &NonfungibleHandle<T>,744		spender: &T::CrossAccountId,745		from: &T::CrossAccountId,746		token: TokenId,747		nesting_budget: &dyn Budget,748	) -> DispatchResult {749		if spender.conv_eq(from) {750			return Ok(());751		}752		if collection.access == AccessMode::AllowList {753			// `from`, `to` checked in [`transfer`]754			collection.check_allowlist(spender)?;755		}756		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {757			// TODO: should collection owner be allowed to perform this transfer?758			ensure!(759				<PalletStructure<T>>::check_indirectly_owned(760					spender.clone(),761					source.0,762					source.1,763					None,764					nesting_budget765				)?,766				<CommonError<T>>::ApprovedValueTooLow,767			);768			return Ok(());769		}770		if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {771			return Ok(());772		}773		ensure!(774			collection.ignores_allowance(spender),775			<CommonError<T>>::ApprovedValueTooLow776		);777		Ok(())778	}779780	pub fn transfer_from(781		collection: &NonfungibleHandle<T>,782		spender: &T::CrossAccountId,783		from: &T::CrossAccountId,784		to: &T::CrossAccountId,785		token: TokenId,786		nesting_budget: &dyn Budget,787	) -> DispatchResult {788		Self::check_allowed(collection, spender, from, token, nesting_budget)?;789790		// =========791792		// Allowance is reset in [`transfer`]793		Self::transfer(collection, from, to, token, nesting_budget)794	}795796	pub fn burn_from(797		collection: &NonfungibleHandle<T>,798		spender: &T::CrossAccountId,799		from: &T::CrossAccountId,800		token: TokenId,801		nesting_budget: &dyn Budget,802	) -> DispatchResult {803		Self::check_allowed(collection, spender, from, token, nesting_budget)?;804805		// =========806807		Self::burn(collection, from, token)808	}809810	pub fn check_nesting(811		handle: &NonfungibleHandle<T>,812		sender: T::CrossAccountId,813		from: (CollectionId, TokenId),814		under: TokenId,815		nesting_budget: &dyn Budget,816	) -> DispatchResult {817		fn ensure_sender_allowed<T: Config>(818			collection: CollectionId,819			token: TokenId,820			for_nest: (CollectionId, TokenId),821			sender: T::CrossAccountId,822			budget: &dyn Budget,823		) -> DispatchResult {824			ensure!(825				<PalletStructure<T>>::check_indirectly_owned(826					sender,827					collection,828					token,829					Some(for_nest),830					budget831				)?,832				<CommonError<T>>::OnlyOwnerAllowedToNest,833			);834			Ok(())835		}836		match handle.limits.nesting_rule() {837			NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),838			NestingRule::Owner => {839				ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?840			}841			NestingRule::OwnerRestricted(whitelist) => {842				ensure!(843					whitelist.contains(&from.0),844					<CommonError<T>>::SourceCollectionIsNotAllowedToNest845				);846				ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?847			}848		}849		Ok(())850	}851852	/// Delegated to `create_multiple_items`853	pub fn create_item(854		collection: &NonfungibleHandle<T>,855		sender: &T::CrossAccountId,856		data: CreateItemData<T>,857		nesting_budget: &dyn Budget,858	) -> DispatchResult {859		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)860	}861}
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 evm_coder::ToLog;21use frame_support::{BoundedVec, ensure, fail, transactional};22use up_data_structs::{23	AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,24	mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,25	PropertyKey, PropertyKeyPermission, Properties, TrySetProperty,26};27use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};28use pallet_common::{29	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,30	dispatch::CollectionDispatch, eth::collection_id_to_address,31};32use pallet_structure::Pallet as PalletStructure;33use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};34use sp_core::H160;35use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};36use sp_std::{vec::Vec, vec};37use core::ops::Deref;38use sp_std::collections::btree_map::BTreeMap;39use codec::{Encode, Decode, MaxEncodedLen};40use scale_info::TypeInfo;4142pub use pallet::*;43#[cfg(feature = "runtime-benchmarks")]44pub mod benchmarking;45pub mod common;46pub mod erc;47pub mod weights;4849pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;50pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;5152#[struct_versioning::versioned(version = 2, upper)]53#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]54pub struct ItemData<CrossAccountId> {55	pub const_data: BoundedVec<u8, CustomDataLimit>,5657	#[version(..2)]58	pub variable_data: BoundedVec<u8, CustomDataLimit>,5960	pub owner: CrossAccountId,61}6263#[frame_support::pallet]64pub mod pallet {65	use super::*;66	use frame_support::{67		Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,68	};69	use frame_system::pallet_prelude::*;70	use up_data_structs::{CollectionId, TokenId};71	use super::weights::WeightInfo;7273	#[pallet::error]74	pub enum Error<T> {75		/// Not Nonfungible item data used to mint in Nonfungible collection.76		NotNonfungibleDataUsedToMintFungibleCollectionToken,77		/// Used amount > 1 with NFT78		NonfungibleItemsHaveNoAmount,79	}8081	#[pallet::config]82	pub trait Config:83		frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config84	{85		type WeightInfo: WeightInfo;86	}8788	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);8990	#[pallet::pallet]91	#[pallet::storage_version(STORAGE_VERSION)]92	#[pallet::generate_store(pub(super) trait Store)]93	pub struct Pallet<T>(_);9495	#[pallet::storage]96	pub type TokensMinted<T: Config> =97		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;98	#[pallet::storage]99	pub type TokensBurnt<T: Config> =100		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;101102	#[pallet::storage]103	pub type TokenData<T: Config> = StorageNMap<104		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),105		Value = ItemData<T::CrossAccountId>,106		QueryKind = OptionQuery,107	>;108109	#[pallet::storage]110	#[pallet::getter(fn token_properties)]111	pub type TokenProperties<T: Config> = StorageNMap<112		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),113		Value = Properties,114		QueryKind = ValueQuery,115		OnEmpty = up_data_structs::TokenProperties,116	>;117118	/// Used to enumerate tokens owned by account119	#[pallet::storage]120	pub type Owned<T: Config> = StorageNMap<121		Key = (122			Key<Twox64Concat, CollectionId>,123			Key<Blake2_128Concat, T::CrossAccountId>,124			Key<Twox64Concat, TokenId>,125		),126		Value = bool,127		QueryKind = ValueQuery,128	>;129130	#[pallet::storage]131	pub type AccountBalance<T: Config> = StorageNMap<132		Key = (133			Key<Twox64Concat, CollectionId>,134			Key<Blake2_128Concat, T::CrossAccountId>,135		),136		Value = u32,137		QueryKind = ValueQuery,138	>;139140	#[pallet::storage]141	pub type Allowance<T: Config> = StorageNMap<142		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),143		Value = T::CrossAccountId,144		QueryKind = OptionQuery,145	>;146147	#[pallet::hooks]148	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {149		fn on_runtime_upgrade() -> Weight {150			if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {151				<TokenData<T>>::translate_values::<ItemDataVersion1<T::CrossAccountId>, _>(|v| {152					Some(<ItemDataVersion2<T::CrossAccountId>>::from(v))153				})154			}155156			0157		}158	}159}160161pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);162impl<T: Config> NonfungibleHandle<T> {163	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {164		Self(inner)165	}166	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {167		self.0168	}169	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {170		&mut self.0171	}172}173impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {174	fn recorder(&self) -> &SubstrateRecorder<T> {175		self.0.recorder()176	}177	fn into_recorder(self) -> SubstrateRecorder<T> {178		self.0.into_recorder()179	}180}181impl<T: Config> Deref for NonfungibleHandle<T> {182	type Target = pallet_common::CollectionHandle<T>;183184	fn deref(&self) -> &Self::Target {185		&self.0186	}187}188189impl<T: Config> Pallet<T> {190	pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {191		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)192	}193	pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {194		<TokenData<T>>::contains_key((collection.id, token))195	}196}197198// unchecked calls skips any permission checks199impl<T: Config> Pallet<T> {200	pub fn init_collection(201		owner: T::AccountId,202		data: CreateCollectionData<T::AccountId>,203	) -> Result<CollectionId, DispatchError> {204		<PalletCommon<T>>::init_collection(owner, data)205	}206	pub fn destroy_collection(207		collection: NonfungibleHandle<T>,208		sender: &T::CrossAccountId,209	) -> DispatchResult {210		let id = collection.id;211212		// =========213214		PalletCommon::destroy_collection(collection.0, sender)?;215216		<TokenData<T>>::remove_prefix((id,), None);217		<Owned<T>>::remove_prefix((id,), None);218		<TokensMinted<T>>::remove(id);219		<TokensBurnt<T>>::remove(id);220		<Allowance<T>>::remove_prefix((id,), None);221		<AccountBalance<T>>::remove_prefix((id,), None);222		Ok(())223	}224225	pub fn burn(226		collection: &NonfungibleHandle<T>,227		sender: &T::CrossAccountId,228		token: TokenId,229	) -> DispatchResult {230		let token_data =231			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;232		ensure!(233			&token_data.owner == sender234				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),235			<CommonError<T>>::NoPermission236		);237238		if collection.access == AccessMode::AllowList {239			collection.check_allowlist(sender)?;240		}241242		let burnt = <TokensBurnt<T>>::get(collection.id)243			.checked_add(1)244			.ok_or(ArithmeticError::Overflow)?;245246		let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))247			.checked_sub(1)248			.ok_or(ArithmeticError::Overflow)?;249250		if balance == 0 {251			<AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));252		} else {253			<AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);254		}255		// =========256257		<Owned<T>>::remove((collection.id, &token_data.owner, token));258		<TokensBurnt<T>>::insert(collection.id, burnt);259		<TokenData<T>>::remove((collection.id, token));260		<TokenProperties<T>>::remove((collection.id, token));261		let old_spender = <Allowance<T>>::take((collection.id, token));262263		if let Some(old_spender) = old_spender {264			<PalletCommon<T>>::deposit_event(CommonEvent::Approved(265				collection.id,266				token,267				sender.clone(),268				old_spender,269				0,270			));271		}272273		<PalletEvm<T>>::deposit_log(274			ERC721Events::Transfer {275				from: *token_data.owner.as_eth(),276				to: H160::default(),277				token_id: token.into(),278			}279			.to_log(collection_id_to_address(collection.id)),280		);281		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(282			collection.id,283			token,284			token_data.owner,285			1,286		));287		Ok(())288	}289290	pub fn set_token_property(291		collection: &NonfungibleHandle<T>,292		sender: &T::CrossAccountId,293		token_id: TokenId,294		property: Property,295	) -> DispatchResult {296		Self::check_token_change_permission(collection, sender, token_id, &property.key)?;297298		<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {299			let property = property.clone();300			properties.try_set(property.key, property.value)301		})302		.map_err(<CommonError<T>>::from)?;303304		<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(305			collection.id,306			token_id,307			property.key,308		));309310		Ok(())311	}312313	#[transactional]314	pub fn set_token_properties(315		collection: &NonfungibleHandle<T>,316		sender: &T::CrossAccountId,317		token_id: TokenId,318		properties: Vec<Property>,319	) -> DispatchResult {320		for property in properties {321			Self::set_token_property(collection, sender, token_id, property)?;322		}323324		Ok(())325	}326327	pub fn delete_token_property(328		collection: &NonfungibleHandle<T>,329		sender: &T::CrossAccountId,330		token_id: TokenId,331		property_key: PropertyKey,332	) -> DispatchResult {333		Self::check_token_change_permission(collection, sender, token_id, &property_key)?;334335		<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {336			properties.remove(&property_key)337		})338		.map_err(<CommonError<T>>::from)?;339340		<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(341			collection.id,342			token_id,343			property_key,344		));345346		Ok(())347	}348349	fn check_token_change_permission(350		collection: &NonfungibleHandle<T>,351		sender: &T::CrossAccountId,352		token_id: TokenId,353		property_key: &PropertyKey,354	) -> DispatchResult {355		let permission = <PalletCommon<T>>::property_permissions(collection.id)356			.get(property_key)357			.cloned()358			.unwrap_or_else(PropertyPermission::none);359360		let token_data = <TokenData<T>>::get((collection.id, token_id))361			.ok_or(<CommonError<T>>::TokenNotFound)?;362363		let check_token_owner = || -> DispatchResult {364			ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);365			Ok(())366		};367368		let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))369			.get(property_key)370			.is_some();371372		match permission {373			PropertyPermission { mutable: false, .. } if is_property_exists => {374				Err(<CommonError<T>>::NoPermission.into())375			}376377			PropertyPermission {378				collection_admin,379				token_owner,380				..381			} => {382				let mut check_result = Err(<CommonError<T>>::NoPermission.into());383384				if collection_admin {385					check_result = collection.check_is_owner_or_admin(sender);386				}387388				if token_owner {389					check_result.or_else(|_| check_token_owner())390				} else {391					check_result392				}393			}394		}395	}396397	#[transactional]398	pub fn delete_token_properties(399		collection: &NonfungibleHandle<T>,400		sender: &T::CrossAccountId,401		token_id: TokenId,402		property_keys: Vec<PropertyKey>,403	) -> DispatchResult {404		for key in property_keys {405			Self::delete_token_property(collection, sender, token_id, key)?;406		}407408		Ok(())409	}410411	pub fn set_collection_properties(412		collection: &NonfungibleHandle<T>,413		sender: &T::CrossAccountId,414		properties: Vec<Property>,415	) -> DispatchResult {416		<PalletCommon<T>>::set_collection_properties(collection, sender, properties)417	}418419	pub fn delete_collection_properties(420		collection: &CollectionHandle<T>,421		sender: &T::CrossAccountId,422		property_keys: Vec<PropertyKey>,423	) -> DispatchResult {424		<PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)425	}426427	pub fn set_property_permissions(428		collection: &CollectionHandle<T>,429		sender: &T::CrossAccountId,430		property_permissions: Vec<PropertyKeyPermission>,431	) -> DispatchResult {432		<PalletCommon<T>>::set_property_permissions(collection, sender, property_permissions)433	}434435	pub fn set_property_permission(436		collection: &CollectionHandle<T>,437		sender: &T::CrossAccountId,438		permission: PropertyKeyPermission,439	) -> DispatchResult {440		<PalletCommon<T>>::set_property_permission(collection, sender, permission)441	}442443	pub fn transfer(444		collection: &NonfungibleHandle<T>,445		from: &T::CrossAccountId,446		to: &T::CrossAccountId,447		token: TokenId,448		nesting_budget: &dyn Budget,449	) -> DispatchResult {450		ensure!(451			collection.limits.transfers_enabled(),452			<CommonError<T>>::TransferNotAllowed453		);454455		let token_data =456			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;457		// TODO: require sender to be token, owner, require admins to go through transfer_from458		ensure!(459			&token_data.owner == from460				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),461			<CommonError<T>>::NoPermission462		);463464		if collection.access == AccessMode::AllowList {465			collection.check_allowlist(from)?;466			collection.check_allowlist(to)?;467		}468		<PalletCommon<T>>::ensure_correct_receiver(to)?;469470		let balance_from = <AccountBalance<T>>::get((collection.id, from))471			.checked_sub(1)472			.ok_or(<CommonError<T>>::TokenValueTooLow)?;473		let balance_to = if from != to {474			let balance_to = <AccountBalance<T>>::get((collection.id, to))475				.checked_add(1)476				.ok_or(ArithmeticError::Overflow)?;477478			ensure!(479				balance_to < collection.limits.account_token_ownership_limit(),480				<CommonError<T>>::AccountTokenLimitExceeded,481			);482483			Some(balance_to)484		} else {485			None486		};487488		if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {489			let handle = <CollectionHandle<T>>::try_get(target.0)?;490			let dispatch = T::CollectionDispatch::dispatch(handle);491			let dispatch = dispatch.as_dyn();492493			dispatch.check_nesting(494				from.clone(),495				(collection.id, token),496				target.1,497				nesting_budget,498			)?;499		}500501		// =========502503		<TokenData<T>>::insert(504			(collection.id, token),505			ItemData {506				owner: to.clone(),507				..token_data508			},509		);510511		if let Some(balance_to) = balance_to {512			// from != to513			if balance_from == 0 {514				<AccountBalance<T>>::remove((collection.id, from));515			} else {516				<AccountBalance<T>>::insert((collection.id, from), balance_from);517			}518			<AccountBalance<T>>::insert((collection.id, to), balance_to);519			<Owned<T>>::remove((collection.id, from, token));520			<Owned<T>>::insert((collection.id, to, token), true);521		}522		Self::set_allowance_unchecked(collection, from, token, None, true);523524		<PalletEvm<T>>::deposit_log(525			ERC721Events::Transfer {526				from: *from.as_eth(),527				to: *to.as_eth(),528				token_id: token.into(),529			}530			.to_log(collection_id_to_address(collection.id)),531		);532		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(533			collection.id,534			token,535			from.clone(),536			to.clone(),537			1,538		));539		Ok(())540	}541542	pub fn create_multiple_items(543		collection: &NonfungibleHandle<T>,544		sender: &T::CrossAccountId,545		data: Vec<CreateItemData<T>>,546		nesting_budget: &dyn Budget,547	) -> DispatchResult {548		if !collection.is_owner_or_admin(sender) {549			ensure!(550				collection.mint_mode,551				<CommonError<T>>::PublicMintingNotAllowed552			);553			collection.check_allowlist(sender)?;554555			for item in data.iter() {556				collection.check_allowlist(&item.owner)?;557			}558		}559560		for data in data.iter() {561			<PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;562		}563564		let first_token = <TokensMinted<T>>::get(collection.id);565		let tokens_minted = first_token566			.checked_add(data.len() as u32)567			.ok_or(ArithmeticError::Overflow)?;568		ensure!(569			tokens_minted <= collection.limits.token_limit(),570			<CommonError<T>>::CollectionTokenLimitExceeded571		);572573		let mut balances = BTreeMap::new();574		for data in &data {575			let balance = balances576				.entry(&data.owner)577				.or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));578			*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;579580			ensure!(581				*balance <= collection.limits.account_token_ownership_limit(),582				<CommonError<T>>::AccountTokenLimitExceeded,583			);584		}585586		for (i, data) in data.iter().enumerate() {587			let token = TokenId(first_token + i as u32 + 1);588			if let Some(target) = T::CrossTokenAddressMapping::address_to_token(&data.owner) {589				let handle = <CollectionHandle<T>>::try_get(target.0)?;590				let dispatch = T::CollectionDispatch::dispatch(handle);591				let dispatch = dispatch.as_dyn();592				dispatch.check_nesting(593					sender.clone(),594					(collection.id, token),595					target.1,596					nesting_budget,597				)?;598			}599		}600601		// =========602603		<TokensMinted<T>>::insert(collection.id, tokens_minted);604		for (account, balance) in balances {605			<AccountBalance<T>>::insert((collection.id, account), balance);606		}607		for (i, data) in data.into_iter().enumerate() {608			let token = first_token + i as u32 + 1;609610			<TokenData<T>>::insert(611				(collection.id, token),612				ItemData {613					const_data: data.const_data,614					owner: data.owner.clone(),615				},616			);617			<Owned<T>>::insert((collection.id, &data.owner, token), true);618619			Self::set_token_properties(620				collection,621				sender,622				TokenId(token),623				data.properties.into_inner(),624			)?;625626			<PalletEvm<T>>::deposit_log(627				ERC721Events::Transfer {628					from: H160::default(),629					to: *data.owner.as_eth(),630					token_id: token.into(),631				}632				.to_log(collection_id_to_address(collection.id)),633			);634			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(635				collection.id,636				TokenId(token),637				data.owner.clone(),638				1,639			));640		}641		Ok(())642	}643644	pub fn set_allowance_unchecked(645		collection: &NonfungibleHandle<T>,646		sender: &T::CrossAccountId,647		token: TokenId,648		spender: Option<&T::CrossAccountId>,649		assume_implicit_eth: bool,650	) {651		if let Some(spender) = spender {652			let old_spender = <Allowance<T>>::get((collection.id, token));653			<Allowance<T>>::insert((collection.id, token), spender);654			// In ERC721 there is only one possible approved user of token, so we set655			// approved user to spender656			<PalletEvm<T>>::deposit_log(657				ERC721Events::Approval {658					owner: *sender.as_eth(),659					approved: *spender.as_eth(),660					token_id: token.into(),661				}662				.to_log(collection_id_to_address(collection.id)),663			);664			// In Unique chain, any token can have any amount of approved users, so we need to665			// set allowance of old owner to 0, and allowance of new owner to 1666			if old_spender.as_ref() != Some(spender) {667				if let Some(old_owner) = old_spender {668					<PalletCommon<T>>::deposit_event(CommonEvent::Approved(669						collection.id,670						token,671						sender.clone(),672						old_owner,673						0,674					));675				}676				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(677					collection.id,678					token,679					sender.clone(),680					spender.clone(),681					1,682				));683			}684		} else {685			let old_spender = <Allowance<T>>::take((collection.id, token));686			if !assume_implicit_eth {687				// In ERC721 there is only one possible approved user of token, so we set688				// approved user to zero address689				<PalletEvm<T>>::deposit_log(690					ERC721Events::Approval {691						owner: *sender.as_eth(),692						approved: H160::default(),693						token_id: token.into(),694					}695					.to_log(collection_id_to_address(collection.id)),696				);697			}698			// In Unique chain, any token can have any amount of approved users, so we need to699			// set allowance of old owner to 0700			if let Some(old_spender) = old_spender {701				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(702					collection.id,703					token,704					sender.clone(),705					old_spender,706					0,707				));708			}709		}710	}711712	pub fn set_allowance(713		collection: &NonfungibleHandle<T>,714		sender: &T::CrossAccountId,715		token: TokenId,716		spender: Option<&T::CrossAccountId>,717	) -> DispatchResult {718		if collection.access == AccessMode::AllowList {719			collection.check_allowlist(sender)?;720			if let Some(spender) = spender {721				collection.check_allowlist(spender)?;722			}723		}724725		if let Some(spender) = spender {726			<PalletCommon<T>>::ensure_correct_receiver(spender)?;727		}728		let token_data =729			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;730		if &token_data.owner != sender {731			ensure!(732				collection.ignores_owned_amount(sender),733				<CommonError<T>>::CantApproveMoreThanOwned734			);735		}736737		// =========738739		Self::set_allowance_unchecked(collection, sender, token, spender, false);740		Ok(())741	}742743	fn check_allowed(744		collection: &NonfungibleHandle<T>,745		spender: &T::CrossAccountId,746		from: &T::CrossAccountId,747		token: TokenId,748		nesting_budget: &dyn Budget,749	) -> DispatchResult {750		if spender.conv_eq(from) {751			return Ok(());752		}753		if collection.access == AccessMode::AllowList {754			// `from`, `to` checked in [`transfer`]755			collection.check_allowlist(spender)?;756		}757		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {758			// TODO: should collection owner be allowed to perform this transfer?759			ensure!(760				<PalletStructure<T>>::check_indirectly_owned(761					spender.clone(),762					source.0,763					source.1,764					None,765					nesting_budget766				)?,767				<CommonError<T>>::ApprovedValueTooLow,768			);769			return Ok(());770		}771		if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {772			return Ok(());773		}774		ensure!(775			collection.ignores_allowance(spender),776			<CommonError<T>>::ApprovedValueTooLow777		);778		Ok(())779	}780781	pub fn transfer_from(782		collection: &NonfungibleHandle<T>,783		spender: &T::CrossAccountId,784		from: &T::CrossAccountId,785		to: &T::CrossAccountId,786		token: TokenId,787		nesting_budget: &dyn Budget,788	) -> DispatchResult {789		Self::check_allowed(collection, spender, from, token, nesting_budget)?;790791		// =========792793		// Allowance is reset in [`transfer`]794		Self::transfer(collection, from, to, token, nesting_budget)795	}796797	pub fn burn_from(798		collection: &NonfungibleHandle<T>,799		spender: &T::CrossAccountId,800		from: &T::CrossAccountId,801		token: TokenId,802		nesting_budget: &dyn Budget,803	) -> DispatchResult {804		Self::check_allowed(collection, spender, from, token, nesting_budget)?;805806		// =========807808		Self::burn(collection, from, token)809	}810811	pub fn check_nesting(812		handle: &NonfungibleHandle<T>,813		sender: T::CrossAccountId,814		from: (CollectionId, TokenId),815		under: TokenId,816		nesting_budget: &dyn Budget,817	) -> DispatchResult {818		fn ensure_sender_allowed<T: Config>(819			collection: CollectionId,820			token: TokenId,821			for_nest: (CollectionId, TokenId),822			sender: T::CrossAccountId,823			budget: &dyn Budget,824		) -> DispatchResult {825			ensure!(826				<PalletStructure<T>>::check_indirectly_owned(827					sender,828					collection,829					token,830					Some(for_nest),831					budget832				)?,833				<CommonError<T>>::OnlyOwnerAllowedToNest,834			);835			Ok(())836		}837		match handle.limits.nesting_rule() {838			NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),839			NestingRule::Owner => {840				ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?841			}842			NestingRule::OwnerRestricted(whitelist) => {843				ensure!(844					whitelist.contains(&from.0),845					<CommonError<T>>::SourceCollectionIsNotAllowedToNest846				);847				ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?848			}849		}850		Ok(())851	}852853	/// Delegated to `create_multiple_items`854	pub fn create_item(855		collection: &NonfungibleHandle<T>,856		sender: &T::CrossAccountId,857		data: CreateItemData<T>,858		nesting_budget: &dyn Budget,859	) -> DispatchResult {860		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)861	}862}