git.delta.rocks / unique-network / refs/commits / 950d276ffd36

difftreelog

source

pallets/nonfungible/src/lib.rs42.5 KiBsourcehistory
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//! # Nonfungible Pallet18//!19//! The Nonfungible pallet provides functionality for handling nonfungible collections and tokens.20//!21//! - [`Config`]22//! - [`NonfungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`](common::CommonWeights)25//!26//! ## Overview27//!28//! The Nonfungible pallet provides functions for:29//!30//! - NFT collection creation and removal31//! - Minting and burning of NFT tokens32//! - Retrieving account balances33//! - Transfering NFT tokens34//! - Setting and checking allowance for NFT tokens35//! - Setting properties and permissions for NFT collections and tokens36//! - Nesting and unnesting tokens37//!38//! ### Terminology39//!40//! - **NFT token:** Non fungible token.41//!42//! - **NFT Collection:** A collection of NFT tokens. All NFT tokens are part of a collection.43//!   Each collection can define it's own properties, properties for it's tokens and set of permissions.44//!45//! - **Balance:** Number of NFT tokens owned by an account46//!47//! - **Allowance:** NFT tokens owned by one account that another account is allowed to make operations on48//!49//! - **Burning:** The process of “deleting” a token from a collection and from50//!   an account balance of the owner.51//!52//! - **Nesting:** Setting up parent-child relationship between tokens. Nested tokens are inhereting53//!   owner from their parent. There could be multiple levels of nesting. Token couldn't be nested in54//!   it's child token i.e. parent-child relationship graph shouldn't have cycles.55//!56//! - **Properties:** Key-Values pairs. Token properties are attached to a token. Collection properties are57//!   attached to a collection. Set of permissions could be defined for each property.58//!59//! ### Implementations60//!61//! The Nonfungible pallet provides implementations for the following traits. If these traits provide62//! the functionality that you need, then you can avoid coupling with the Nonfungible pallet.63//!64//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight65//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing66//!   with collections67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create NFT collection. NFT collection can be configured to allow or deny access for73//!   some accounts.74//! - `destroy_collection` - Destroy exising NFT collection. There should be no tokens in the collection.75//! - `burn` - Burn NFT token owned by account.76//! - `transfer` - Transfer NFT token. Transfers should be enabled for NFT collection.77//!   Nests the NFT token if it is sent to another token.78//! - `create_item` - Mint NFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account.80//! - `set_token_property` - Set token property value.81//! - `delete_token_property` - Remove property from the token.82//! - `set_collection_properties` - Set collection properties.83//! - `delete_collection_properties` - Remove properties from the collection.84//! - `set_property_permission` - Set collection property permission.85//! - `set_token_property_permissions` - Set token property permissions.86//!87//! ## Assumptions88//!89//! * To perform operations on tokens sender should be in collection's allow list if collection access mode is `AllowList`.9091#![cfg_attr(not(feature = "std"), no_std)]9293use erc::ERC721Events;94use evm_coder::ToLog;95use frame_support::{96	BoundedVec, ensure, fail, transactional,97	storage::with_transaction,98	pallet_prelude::DispatchResultWithPostInfo,99	pallet_prelude::Weight,100	dispatch::{PostDispatchInfo, Pays},101};102use up_data_structs::{103	AccessMode, CollectionId, CollectionFlags, CustomDataLimit, TokenId, CreateCollectionData,104	CreateNftExData, mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey,105	PropertyValue, PropertyKeyPermission, PropertyScope, TrySetProperty, TokenChild,106	AuxPropertyValue, PropertiesPermissionMap, TokenProperties as TokenPropertiesT,107};108use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};109use pallet_common::{110	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,111	eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,112	weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info, SetPropertyMode,113};114use pallet_structure::{Pallet as PalletStructure, Error as StructureError};115use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};116use sp_core::{Get, H160};117use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};118use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};119use core::ops::Deref;120use codec::{Encode, Decode, MaxEncodedLen};121use scale_info::TypeInfo;122123pub use pallet::*;124use weights::WeightInfo;125#[cfg(feature = "runtime-benchmarks")]126pub mod benchmarking;127pub mod common;128pub mod erc;129pub mod weights;130131pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::Config>::CrossAccountId>;132pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;133134/// Token data, stored independently from other data used to describe it135/// for the convenience of database access. Notably contains the owner account address.136#[struct_versioning::versioned(version = 2, upper)]137#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]138pub struct ItemData<CrossAccountId> {139	#[version(..2)]140	pub const_data: BoundedVec<u8, CustomDataLimit>,141142	#[version(..2)]143	pub variable_data: BoundedVec<u8, CustomDataLimit>,144145	pub owner: CrossAccountId,146}147148#[frame_support::pallet]149pub mod pallet {150	use super::*;151	use frame_support::{152		Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,153	};154	use up_data_structs::{CollectionId, TokenId};155	use super::weights::WeightInfo;156157	#[pallet::error]158	pub enum Error<T> {159		/// Not Nonfungible item data used to mint in Nonfungible collection.160		NotNonfungibleDataUsedToMintFungibleCollectionToken,161		/// Used amount > 1 with NFT162		NonfungibleItemsHaveNoAmount,163		/// Unable to burn NFT with children164		CantBurnNftWithChildren,165	}166167	#[pallet::config]168	pub trait Config:169		frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config170	{171		type WeightInfo: WeightInfo;172	}173174	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);175176	#[pallet::pallet]177	#[pallet::storage_version(STORAGE_VERSION)]178	pub struct Pallet<T>(_);179180	/// Total amount of minted tokens in a collection.181	#[pallet::storage]182	pub type TokensMinted<T: Config> =183		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;184185	/// Amount of burnt tokens in a collection.186	#[pallet::storage]187	pub type TokensBurnt<T: Config> =188		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;189190	/// Token data, used to partially describe a token.191	#[pallet::storage]192	pub type TokenData<T: Config> = StorageNMap<193		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),194		Value = ItemData<T::CrossAccountId>,195		QueryKind = OptionQuery,196	>;197198	/// Map of key-value pairs, describing the metadata of a token.199	#[pallet::storage]200	#[pallet::getter(fn token_properties)]201	pub type TokenProperties<T: Config> = StorageNMap<202		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),203		Value = TokenPropertiesT,204		QueryKind = ValueQuery,205	>;206207	/// Custom data of a token that is serialized to bytes,208	/// primarily reserved for on-chain operations,209	/// normally obscured from the external users.210	///211	/// Auxiliary properties are slightly different from212	/// usual [`TokenProperties`] due to an unlimited number213	/// and separately stored and written-to key-value pairs.214	///215	/// Currently unused.216	#[pallet::storage]217	#[pallet::getter(fn token_aux_property)]218	pub type TokenAuxProperties<T: Config> = StorageNMap<219		Key = (220			Key<Twox64Concat, CollectionId>,221			Key<Twox64Concat, TokenId>,222			Key<Twox64Concat, PropertyScope>,223			Key<Twox64Concat, PropertyKey>,224		),225		Value = AuxPropertyValue,226		QueryKind = OptionQuery,227	>;228229	/// Used to enumerate tokens owned by account.230	#[pallet::storage]231	pub type Owned<T: Config> = StorageNMap<232		Key = (233			Key<Twox64Concat, CollectionId>,234			Key<Blake2_128Concat, T::CrossAccountId>,235			Key<Twox64Concat, TokenId>,236		),237		Value = bool,238		QueryKind = ValueQuery,239	>;240241	/// Used to enumerate token's children.242	#[pallet::storage]243	#[pallet::getter(fn token_children)]244	pub type TokenChildren<T: Config> = StorageNMap<245		Key = (246			Key<Twox64Concat, CollectionId>,247			Key<Twox64Concat, TokenId>,248			Key<Twox64Concat, (CollectionId, TokenId)>,249		),250		Value = bool,251		QueryKind = ValueQuery,252	>;253254	/// Amount of tokens owned by an account in a collection.255	#[pallet::storage]256	pub type AccountBalance<T: Config> = StorageNMap<257		Key = (258			Key<Twox64Concat, CollectionId>,259			Key<Blake2_128Concat, T::CrossAccountId>,260		),261		Value = u32,262		QueryKind = ValueQuery,263	>;264265	/// Allowance set by a token owner for another user to perform one of certain transactions on a token.266	#[pallet::storage]267	pub type Allowance<T: Config> = StorageNMap<268		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),269		Value = T::CrossAccountId,270		QueryKind = OptionQuery,271	>;272273	/// Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.274	#[pallet::storage]275	pub type CollectionAllowance<T: Config> = StorageNMap<276		Key = (277			Key<Twox64Concat, CollectionId>,278			Key<Blake2_128Concat, T::CrossAccountId>,279			Key<Blake2_128Concat, T::CrossAccountId>,280		),281		Value = bool,282		QueryKind = ValueQuery,283	>;284285	#[pallet::genesis_config]286	pub struct GenesisConfig<T>(PhantomData<T>);287288	#[cfg(feature = "std")]289	impl<T: Config> Default for GenesisConfig<T> {290		fn default() -> Self {291			Self(Default::default())292		}293	}294295	#[pallet::genesis_build]296	impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {297		fn build(&self) {298			StorageVersion::new(1).put::<Pallet<T>>();299		}300	}301}302303pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);304impl<T: Config> NonfungibleHandle<T> {305	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {306		Self(inner)307	}308	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {309		self.0310	}311	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {312		&mut self.0313	}314}315316impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {317	fn recorder(&self) -> &SubstrateRecorder<T> {318		self.0.recorder()319	}320	fn into_recorder(self) -> SubstrateRecorder<T> {321		self.0.into_recorder()322	}323}324impl<T: Config> Deref for NonfungibleHandle<T> {325	type Target = pallet_common::CollectionHandle<T>;326327	fn deref(&self) -> &Self::Target {328		&self.0329	}330}331332impl<T: Config> Pallet<T> {333	/// Get number of NFT tokens in collection.334	pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {335		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)336	}337338	/// Check that NFT token exists.339	///340	/// - `token`: Token ID.341	pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {342		<TokenData<T>>::contains_key((collection.id, token))343	}344345	/// Set the token property with the scope.346	///347	/// - `property`: Contains key-value pair.348	pub fn set_scoped_token_property(349		collection_id: CollectionId,350		token_id: TokenId,351		scope: PropertyScope,352		property: Property,353	) -> DispatchResult {354		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {355			properties.try_scoped_set(scope, property.key, property.value)356		})357		.map_err(<CommonError<T>>::from)?;358359		Ok(())360	}361362	/// Batch operation to set multiple properties with the same scope.363	pub fn set_scoped_token_properties(364		collection_id: CollectionId,365		token_id: TokenId,366		scope: PropertyScope,367		properties: impl Iterator<Item = Property>,368	) -> DispatchResult {369		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {370			stored_properties.try_scoped_set_from_iter(scope, properties)371		})372		.map_err(<CommonError<T>>::from)?;373374		Ok(())375	}376377	/// Add or edit auxiliary data for the property.378	///379	/// - `f`: function that adds or edits auxiliary data.380	pub fn try_mutate_token_aux_property<R, E>(381		collection_id: CollectionId,382		token_id: TokenId,383		scope: PropertyScope,384		key: PropertyKey,385		f: impl FnOnce(&mut Option<AuxPropertyValue>) -> Result<R, E>,386	) -> Result<R, E> {387		<TokenAuxProperties<T>>::try_mutate((collection_id, token_id, scope, key), f)388	}389390	/// Remove auxiliary data for the property.391	pub fn remove_token_aux_property(392		collection_id: CollectionId,393		token_id: TokenId,394		scope: PropertyScope,395		key: PropertyKey,396	) {397		<TokenAuxProperties<T>>::remove((collection_id, token_id, scope, key));398	}399400	/// Get all auxiliary data in a given scope.401	///402	/// Returns iterator over Property Key - Data pairs.403	pub fn iterate_token_aux_properties(404		collection_id: CollectionId,405		token_id: TokenId,406		scope: PropertyScope,407	) -> impl Iterator<Item = (PropertyKey, AuxPropertyValue)> {408		<TokenAuxProperties<T>>::iter_prefix((collection_id, token_id, scope))409	}410411	/// Get ID of the last minted token412	pub fn current_token_id(collection_id: CollectionId) -> TokenId {413		TokenId(<TokensMinted<T>>::get(collection_id))414	}415}416417// unchecked calls skips any permission checks418impl<T: Config> Pallet<T> {419	/// Create NFT collection420	///421	/// `init_collection` will take non-refundable deposit for collection creation.422	///423	/// - `data`: Contains settings for collection limits and permissions.424	pub fn init_collection(425		owner: T::CrossAccountId,426		payer: T::CrossAccountId,427		data: CreateCollectionData<T::AccountId>,428		flags: CollectionFlags,429	) -> Result<CollectionId, DispatchError> {430		<PalletCommon<T>>::init_collection(owner, payer, data, flags)431	}432433	/// Destroy NFT collection434	///435	/// `destroy_collection` will throw error if collection contains any tokens.436	/// Only owner can destroy collection.437	pub fn destroy_collection(438		collection: NonfungibleHandle<T>,439		sender: &T::CrossAccountId,440	) -> DispatchResult {441		let id = collection.id;442443		if Self::collection_has_tokens(id) {444			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());445		}446447		// =========448449		PalletCommon::destroy_collection(collection.0, sender)?;450451		let _ = <TokenData<T>>::clear_prefix((id,), u32::MAX, None);452		let _ = <TokenChildren<T>>::clear_prefix((id,), u32::MAX, None);453		let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);454		<TokensMinted<T>>::remove(id);455		<TokensBurnt<T>>::remove(id);456		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);457		let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);458		let _ = <CollectionAllowance<T>>::clear_prefix((id,), u32::MAX, None);459		Ok(())460	}461462	/// Burn NFT token463	///464	/// `burn` removes `token` from the `collection`, from it's owner and from the parent token465	/// if the token is nested.466	/// Only the owner can `burn` the token. The `token` shouldn't have any nested tokens.467	/// Also removes all corresponding properties and auxiliary properties.468	///469	/// - `token`: Token that should be burned470	/// - `collection`: Collection that contains the token471	pub fn burn(472		collection: &NonfungibleHandle<T>,473		sender: &T::CrossAccountId,474		token: TokenId,475	) -> DispatchResult {476		let token_data =477			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;478		ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);479480		if collection.permissions.access() == AccessMode::AllowList {481			collection.check_allowlist(sender)?;482		}483484		if Self::token_has_children(collection.id, token) {485			return Err(<Error<T>>::CantBurnNftWithChildren.into());486		}487488		let burnt = <TokensBurnt<T>>::get(collection.id)489			.checked_add(1)490			.ok_or(ArithmeticError::Overflow)?;491492		let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))493			.checked_sub(1)494			.ok_or(ArithmeticError::Overflow)?;495496		// =========497498		if balance == 0 {499			<AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));500		} else {501			<AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);502		}503504		<PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);505506		<Owned<T>>::remove((collection.id, &token_data.owner, token));507		<TokensBurnt<T>>::insert(collection.id, burnt);508		<TokenData<T>>::remove((collection.id, token));509		<TokenProperties<T>>::remove((collection.id, token));510		let _ = <TokenAuxProperties<T>>::clear_prefix((collection.id, token), u32::MAX, None);511		let old_spender = <Allowance<T>>::take((collection.id, token));512513		if let Some(old_spender) = old_spender {514			<PalletCommon<T>>::deposit_event(CommonEvent::Approved(515				collection.id,516				token,517				token_data.owner.clone(),518				old_spender,519				0,520			));521		}522523		<PalletEvm<T>>::deposit_log(524			ERC721Events::Transfer {525				from: *token_data.owner.as_eth(),526				to: H160::default(),527				token_id: token.into(),528			}529			.to_log(collection_id_to_address(collection.id)),530		);531		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(532			collection.id,533			token,534			token_data.owner,535			1,536		));537		Ok(())538	}539540	/// Same as [`burn`] but burns all the tokens that are nested in the token first541	///542	/// - `self_budget`: Limit for searching children in depth.543	/// - `breadth_budget`: Limit of breadth of searching children.544	///545	/// [`burn`]: struct.Pallet.html#method.burn546	#[transactional]547	pub fn burn_recursively(548		collection: &NonfungibleHandle<T>,549		sender: &T::CrossAccountId,550		token: TokenId,551		self_budget: &dyn Budget,552		breadth_budget: &dyn Budget,553	) -> DispatchResultWithPostInfo {554		ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);555556		let current_token_account =557			T::CrossTokenAddressMapping::token_to_address(collection.id, token);558559		let mut weight = Weight::zero();560561		// This method is transactional, if user in fact doesn't have permissions to remove token -562		// tokens removed here will be restored after rejected transaction563		for ((collection, token), _) in <TokenChildren<T>>::iter_prefix((collection.id, token)) {564			ensure!(breadth_budget.consume(), <StructureError<T>>::BreadthLimit,);565			let PostDispatchInfo { actual_weight, .. } =566				<PalletStructure<T>>::burn_item_recursively(567					current_token_account.clone(),568					collection,569					token,570					self_budget,571					breadth_budget,572				)?;573			if let Some(actual_weight) = actual_weight {574				weight = weight.saturating_add(actual_weight);575			}576		}577578		Self::burn(collection, sender, token)?;579		DispatchResultWithPostInfo::Ok(PostDispatchInfo {580			actual_weight: Some(weight + <SelfWeightOf<T>>::burn_item()),581			pays_fee: Pays::Yes,582		})583	}584585	/// A batch operation to add, edit or remove properties for a token.586	///587	/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.588	///589	/// All affected properties should have `mutable` permission590	/// to be **deleted** or to be **set more than once**,591	/// and the sender should have permission to edit those properties.592	///593	/// This function fires an event for each property change.594	/// In case of an error, all the changes (including the events) will be reverted595	/// since the function is transactional.596	#[transactional]597	fn modify_token_properties(598		collection: &NonfungibleHandle<T>,599		sender: &T::CrossAccountId,600		token_id: TokenId,601		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,602		mode: SetPropertyMode,603		nesting_budget: &dyn Budget,604	) -> DispatchResult {605		let mut is_token_owner = pallet_common::LazyValue::new(|| {606			if let SetPropertyMode::NewToken {607				mint_target_is_sender,608			} = mode609			{610				return Ok(mint_target_is_sender);611			}612613			let is_owned = <PalletStructure<T>>::check_indirectly_owned(614				sender.clone(),615				collection.id,616				token_id,617				None,618				nesting_budget,619			)?;620621			Ok(is_owned)622		});623624		let mut is_token_exist =625			pallet_common::LazyValue::new(|| Self::token_exists(collection, token_id));626627		let stored_properties = <TokenProperties<T>>::get((collection.id, token_id));628629		<PalletCommon<T>>::modify_token_properties(630			collection,631			sender,632			token_id,633			&mut is_token_exist,634			properties_updates,635			stored_properties,636			&mut is_token_owner,637			|properties| <TokenProperties<T>>::set((collection.id, token_id), properties),638			erc::ERC721TokenEvent::TokenChanged {639				token_id: token_id.into(),640			}641			.to_log(T::ContractAddress::get()),642		)643	}644645	pub fn next_token_id(collection: &NonfungibleHandle<T>) -> Result<TokenId, DispatchError> {646		let next_token_id = <TokensMinted<T>>::get(collection.id)647			.checked_add(1)648			.ok_or(<CommonError<T>>::CollectionTokenLimitExceeded)?;649650		ensure!(651			collection.limits.token_limit() >= next_token_id,652			<CommonError<T>>::CollectionTokenLimitExceeded653		);654655		Ok(TokenId(next_token_id))656	}657658	/// Batch operation to add or edit properties for the token659	///660	/// Same as [`modify_token_properties`] but doesn't allow to remove properties661	///662	/// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties663	pub fn set_token_properties(664		collection: &NonfungibleHandle<T>,665		sender: &T::CrossAccountId,666		token_id: TokenId,667		properties: impl Iterator<Item = Property>,668		mode: SetPropertyMode,669		nesting_budget: &dyn Budget,670	) -> DispatchResult {671		Self::modify_token_properties(672			collection,673			sender,674			token_id,675			properties.map(|p| (p.key, Some(p.value))),676			mode,677			nesting_budget,678		)679	}680681	/// Add or edit single property for the token682	///683	/// Calls [`set_token_properties`] internally684	///685	/// [`set_token_properties`]: struct.Pallet.html#method.set_token_properties686	pub fn set_token_property(687		collection: &NonfungibleHandle<T>,688		sender: &T::CrossAccountId,689		token_id: TokenId,690		property: Property,691		nesting_budget: &dyn Budget,692	) -> DispatchResult {693		Self::set_token_properties(694			collection,695			sender,696			token_id,697			[property].into_iter(),698			SetPropertyMode::ExistingToken,699			nesting_budget,700		)701	}702703	/// Batch operation to remove properties from the token704	///705	/// Same as [`modify_token_properties`] but doesn't allow to add or edit properties706	///707	/// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties708	pub fn delete_token_properties(709		collection: &NonfungibleHandle<T>,710		sender: &T::CrossAccountId,711		token_id: TokenId,712		property_keys: impl Iterator<Item = PropertyKey>,713		nesting_budget: &dyn Budget,714	) -> DispatchResult {715		Self::modify_token_properties(716			collection,717			sender,718			token_id,719			property_keys.into_iter().map(|key| (key, None)),720			SetPropertyMode::ExistingToken,721			nesting_budget,722		)723	}724725	/// Remove single property from the token726	///727	/// Calls [`delete_token_properties`] internally728	///729	/// [`delete_token_properties`]: struct.Pallet.html#method.delete_token_properties730	pub fn delete_token_property(731		collection: &NonfungibleHandle<T>,732		sender: &T::CrossAccountId,733		token_id: TokenId,734		property_key: PropertyKey,735		nesting_budget: &dyn Budget,736	) -> DispatchResult {737		Self::delete_token_properties(738			collection,739			sender,740			token_id,741			[property_key].into_iter(),742			nesting_budget,743		)744	}745746	/// Add or edit properties for the collection747	pub fn set_collection_properties(748		collection: &NonfungibleHandle<T>,749		sender: &T::CrossAccountId,750		properties: Vec<Property>,751	) -> DispatchResult {752		<PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())753	}754755	/// Remove properties from the collection756	pub fn delete_collection_properties(757		collection: &CollectionHandle<T>,758		sender: &T::CrossAccountId,759		property_keys: Vec<PropertyKey>,760	) -> DispatchResult {761		<PalletCommon<T>>::delete_collection_properties(762			collection,763			sender,764			property_keys.into_iter(),765		)766	}767768	/// Set property permissions for the token.769	///770	/// Sender should be the owner or admin of token's collection.771	pub fn set_token_property_permissions(772		collection: &CollectionHandle<T>,773		sender: &T::CrossAccountId,774		property_permissions: Vec<PropertyKeyPermission>,775	) -> DispatchResult {776		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)777	}778779	/// Set property permissions for the token with scope.780	///781	/// Sender should be the owner or admin of token's collection.782	pub fn set_scoped_token_property_permissions(783		collection: &CollectionHandle<T>,784		sender: &T::CrossAccountId,785		scope: PropertyScope,786		property_permissions: Vec<PropertyKeyPermission>,787	) -> DispatchResult {788		<PalletCommon<T>>::set_scoped_token_property_permissions(789			collection,790			sender,791			scope,792			property_permissions,793		)794	}795796	pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {797		<PalletCommon<T>>::property_permissions(collection_id)798	}799800	pub fn check_token_immediate_ownership(801		collection: &NonfungibleHandle<T>,802		token: TokenId,803		possible_owner: &T::CrossAccountId,804	) -> DispatchResult {805		let token_data =806			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;807		ensure!(808			&token_data.owner == possible_owner,809			<CommonError<T>>::NoPermission810		);811		Ok(())812	}813814	/// Transfer NFT token from one account to another.815	///816	/// `from` account stops being the owner and `to` account becomes the owner of the token.817	/// If `to` is token than `to` becomes owner of the token and the token become nested.818	/// Unnests token from previous parent if it was nested before.819	/// Removes allowance for the token if there was any.820	/// Throws if transfers aren't allowed for collection or if receiver reached token ownership limit.821	///822	/// - `nesting_budget`: Limit for token nesting depth823	pub fn transfer(824		collection: &NonfungibleHandle<T>,825		from: &T::CrossAccountId,826		to: &T::CrossAccountId,827		token: TokenId,828		nesting_budget: &dyn Budget,829	) -> DispatchResultWithPostInfo {830		ensure!(831			collection.limits.transfers_enabled(),832			<CommonError<T>>::TransferNotAllowed833		);834835		let mut actual_weight = <SelfWeightOf<T>>::transfer_raw();836		let token_data =837			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;838		ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);839840		if collection.permissions.access() == AccessMode::AllowList {841			collection.check_allowlist(from)?;842			collection.check_allowlist(to)?;843			actual_weight += <PalletCommonWeightOf<T>>::check_accesslist() * 2;844		}845		<PalletCommon<T>>::ensure_correct_receiver(to)?;846847		let balance_from = <AccountBalance<T>>::get((collection.id, from))848			.checked_sub(1)849			.ok_or(<CommonError<T>>::TokenValueTooLow)?;850		let balance_to = if from != to {851			let balance_to = <AccountBalance<T>>::get((collection.id, to))852				.checked_add(1)853				.ok_or(ArithmeticError::Overflow)?;854855			ensure!(856				balance_to < collection.limits.account_token_ownership_limit(),857				<CommonError<T>>::AccountTokenLimitExceeded,858			);859860			Some(balance_to)861		} else {862			None863		};864865		<PalletStructure<T>>::nest_if_sent_to_token(866			from.clone(),867			to,868			collection.id,869			token,870			nesting_budget,871		)?;872873		// =========874875		<PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);876877		<TokenData<T>>::insert((collection.id, token), ItemData { owner: to.clone() });878879		if let Some(balance_to) = balance_to {880			// from != to881			if balance_from == 0 {882				<AccountBalance<T>>::remove((collection.id, from));883			} else {884				<AccountBalance<T>>::insert((collection.id, from), balance_from);885			}886			<AccountBalance<T>>::insert((collection.id, to), balance_to);887			<Owned<T>>::remove((collection.id, from, token));888			<Owned<T>>::insert((collection.id, to, token), true);889		}890		Self::set_allowance_unchecked(collection, from, token, None, true);891892		<PalletEvm<T>>::deposit_log(893			ERC721Events::Transfer {894				from: *from.as_eth(),895				to: *to.as_eth(),896				token_id: token.into(),897			}898			.to_log(collection_id_to_address(collection.id)),899		);900		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(901			collection.id,902			token,903			from.clone(),904			to.clone(),905			1,906		));907908		Ok(PostDispatchInfo {909			actual_weight: Some(actual_weight),910			pays_fee: Pays::Yes,911		})912	}913914	/// Batch operation to mint multiple NFT tokens.915	///916	/// The sender should be the owner/admin of the collection or collection should be configured917	/// to allow public minting.918	/// Throws if amount of tokens reached it's limit for the collection or if caller reached919	/// token ownership limit.920	///921	/// - `data`: Contains list of token properties and users who will become the owners of the922	///   corresponging tokens.923	/// - `nesting_budget`: Limit for token nesting depth924	pub fn create_multiple_items(925		collection: &NonfungibleHandle<T>,926		sender: &T::CrossAccountId,927		data: Vec<CreateItemData<T>>,928		nesting_budget: &dyn Budget,929	) -> DispatchResult {930		if !collection.is_owner_or_admin(sender) {931			ensure!(932				collection.permissions.mint_mode(),933				<CommonError<T>>::PublicMintingNotAllowed934			);935			collection.check_allowlist(sender)?;936937			for item in data.iter() {938				collection.check_allowlist(&item.owner)?;939			}940		}941942		for data in data.iter() {943			<PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;944		}945946		let first_token = <TokensMinted<T>>::get(collection.id);947		let tokens_minted = first_token948			.checked_add(data.len() as u32)949			.ok_or(ArithmeticError::Overflow)?;950		ensure!(951			tokens_minted <= collection.limits.token_limit(),952			<CommonError<T>>::CollectionTokenLimitExceeded953		);954955		let mut balances = BTreeMap::new();956		for data in &data {957			let balance = balances958				.entry(&data.owner)959				.or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));960			*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;961962			ensure!(963				*balance <= collection.limits.account_token_ownership_limit(),964				<CommonError<T>>::AccountTokenLimitExceeded,965			);966		}967968		for (i, data) in data.iter().enumerate() {969			let token = TokenId(first_token + i as u32 + 1);970971			<PalletStructure<T>>::check_nesting(972				sender.clone(),973				&data.owner,974				collection.id,975				token,976				nesting_budget,977			)?;978		}979980		// =========981982		with_transaction(|| {983			for (i, data) in data.iter().enumerate() {984				let token = first_token + i as u32 + 1;985986				<TokenData<T>>::insert(987					(collection.id, token),988					ItemData {989						// const_data: data.const_data.clone(),990						owner: data.owner.clone(),991					},992				);993994				<PalletStructure<T>>::nest_if_sent_to_token_unchecked(995					&data.owner,996					collection.id,997					TokenId(token),998				);9991000				if let Err(e) = Self::set_token_properties(1001					collection,1002					sender,1003					TokenId(token),1004					data.properties.clone().into_iter(),1005					SetPropertyMode::NewToken {1006						mint_target_is_sender: sender.conv_eq(&data.owner),1007					},1008					nesting_budget,1009				) {1010					return TransactionOutcome::Rollback(Err(e));1011				}1012			}1013			TransactionOutcome::Commit(Ok(()))1014		})?;10151016		<TokensMinted<T>>::insert(collection.id, tokens_minted);1017		for (account, balance) in balances {1018			<AccountBalance<T>>::insert((collection.id, account), balance);1019		}1020		for (i, data) in data.into_iter().enumerate() {1021			let token = first_token + i as u32 + 1;1022			<Owned<T>>::insert((collection.id, &data.owner, token), true);10231024			<PalletEvm<T>>::deposit_log(1025				ERC721Events::Transfer {1026					from: H160::default(),1027					to: *data.owner.as_eth(),1028					token_id: token.into(),1029				}1030				.to_log(collection_id_to_address(collection.id)),1031			);1032			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1033				collection.id,1034				TokenId(token),1035				data.owner.clone(),1036				1,1037			));1038		}1039		Ok(())1040	}10411042	pub fn set_allowance_unchecked(1043		collection: &NonfungibleHandle<T>,1044		sender: &T::CrossAccountId,1045		token: TokenId,1046		spender: Option<&T::CrossAccountId>,1047		assume_implicit_eth: bool,1048	) {1049		if let Some(spender) = spender {1050			let old_spender = <Allowance<T>>::get((collection.id, token));1051			<Allowance<T>>::insert((collection.id, token), spender);1052			// In ERC721 there is only one possible approved user of token, so we set1053			// approved user to spender1054			<PalletEvm<T>>::deposit_log(1055				ERC721Events::Approval {1056					owner: *sender.as_eth(),1057					approved: *spender.as_eth(),1058					token_id: token.into(),1059				}1060				.to_log(collection_id_to_address(collection.id)),1061			);1062			// In Unique chain, any token can have any amount of approved users, so we need to1063			// set allowance of old owner to 0, and allowance of new owner to 11064			if old_spender.as_ref() != Some(spender) {1065				if let Some(old_owner) = old_spender {1066					<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1067						collection.id,1068						token,1069						sender.clone(),1070						old_owner,1071						0,1072					));1073				}1074				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1075					collection.id,1076					token,1077					sender.clone(),1078					spender.clone(),1079					1,1080				));1081			}1082		} else {1083			let old_spender = <Allowance<T>>::take((collection.id, token));1084			if !assume_implicit_eth {1085				// In ERC721 there is only one possible approved user of token, so we set1086				// approved user to zero address1087				<PalletEvm<T>>::deposit_log(1088					ERC721Events::Approval {1089						owner: *sender.as_eth(),1090						approved: H160::default(),1091						token_id: token.into(),1092					}1093					.to_log(collection_id_to_address(collection.id)),1094				);1095			}1096			// In Unique chain, any token can have any amount of approved users, so we need to1097			// set allowance of old owner to 01098			if let Some(old_spender) = old_spender {1099				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1100					collection.id,1101					token,1102					sender.clone(),1103					old_spender,1104					0,1105				));1106			}1107		}1108	}11091110	pub fn get_allowance(1111		collection: &NonfungibleHandle<T>,1112		token_id: TokenId,1113	) -> Result<Option<T::CrossAccountId>, DispatchError> {1114		ensure!(1115			<TokenData<T>>::get((collection.id, token_id)).is_some(),1116			<CommonError<T>>::TokenNotFound1117		);1118		Ok(<Allowance<T>>::get((collection.id, token_id)))1119	}11201121	/// Set allowance for the spender to `transfer` or `burn` sender's token.1122	///1123	/// - `token`: Token the spender is allowed to `transfer` or `burn`.1124	pub fn set_allowance(1125		collection: &NonfungibleHandle<T>,1126		sender: &T::CrossAccountId,1127		token: TokenId,1128		spender: Option<&T::CrossAccountId>,1129	) -> DispatchResult {1130		if collection.permissions.access() == AccessMode::AllowList {1131			collection.check_allowlist(sender)?;1132			if let Some(spender) = spender {1133				collection.check_allowlist(spender)?;1134			}1135		}11361137		if let Some(spender) = spender {1138			<PalletCommon<T>>::ensure_correct_receiver(spender)?;1139		}11401141		let token_data =1142			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1143		if &token_data.owner != sender {1144			ensure!(1145				collection.ignores_owned_amount(sender),1146				<CommonError<T>>::CantApproveMoreThanOwned1147			);1148		}11491150		// =========11511152		Self::set_allowance_unchecked(collection, sender, token, spender, false);1153		Ok(())1154	}11551156	/// Set allowance for the spender to `transfer` or `burn` sender's token from eth mirror.1157	///1158	/// - `from`: Address of sender's eth mirror.1159	/// - `to`: Adress of spender.1160	/// - `token`: Token the spender is allowed to `transfer` or `burn`.1161	pub fn set_allowance_from(1162		collection: &NonfungibleHandle<T>,1163		sender: &T::CrossAccountId,1164		from: &T::CrossAccountId,1165		token: TokenId,1166		to: Option<&T::CrossAccountId>,1167	) -> DispatchResult {1168		if collection.permissions.access() == AccessMode::AllowList {1169			collection.check_allowlist(sender)?;1170			collection.check_allowlist(from)?;1171			if let Some(to) = to {1172				collection.check_allowlist(to)?;1173			}1174		}11751176		if let Some(to) = to {1177			<PalletCommon<T>>::ensure_correct_receiver(to)?;1178		}11791180		ensure!(1181			sender.conv_eq(from),1182			<CommonError<T>>::AddressIsNotEthMirror1183		);11841185		let token_data =1186			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1187		if token_data.owner != *from {1188			ensure!(1189				collection.limits.owner_can_transfer()1190					&& (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),1191				<CommonError<T>>::CantApproveMoreThanOwned1192			);1193		}11941195		// =========11961197		Self::set_allowance_unchecked(collection, from, token, to, false);1198		Ok(())1199	}12001201	/// Checks allowance for the spender to use the token.1202	fn check_allowed(1203		collection: &NonfungibleHandle<T>,1204		spender: &T::CrossAccountId,1205		from: &T::CrossAccountId,1206		token: TokenId,1207		nesting_budget: &dyn Budget,1208	) -> DispatchResult {1209		if spender.conv_eq(from) {1210			return Ok(());1211		}1212		if collection.permissions.access() == AccessMode::AllowList {1213			// `from`, `to` checked in [`transfer`]1214			collection.check_allowlist(spender)?;1215		}12161217		if collection.ignores_token_restrictions(spender) {1218			return Ok(());1219		}12201221		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1222			ensure!(1223				<PalletStructure<T>>::check_indirectly_owned(1224					spender.clone(),1225					source.0,1226					source.1,1227					None,1228					nesting_budget1229				)?,1230				<CommonError<T>>::ApprovedValueTooLow,1231			);1232			return Ok(());1233		}1234		if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {1235			return Ok(());1236		}1237		if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1238			return Ok(());1239		}12401241		Err(<CommonError<T>>::ApprovedValueTooLow.into())1242	}12431244	/// Transfer NFT token from one account to another.1245	///1246	/// Same as the [`transfer`] but spender doesn't needs to be the owner of the token.1247	/// The owner should set allowance for the spender to transfer token.1248	///1249	/// [`transfer`]: struct.Pallet.html#method.transfer1250	pub fn transfer_from(1251		collection: &NonfungibleHandle<T>,1252		spender: &T::CrossAccountId,1253		from: &T::CrossAccountId,1254		to: &T::CrossAccountId,1255		token: TokenId,1256		nesting_budget: &dyn Budget,1257	) -> DispatchResultWithPostInfo {1258		Self::check_allowed(collection, spender, from, token, nesting_budget)?;12591260		// =========12611262		// Allowance is reset in [`transfer`]1263		let mut result = Self::transfer(collection, from, to, token, nesting_budget);1264		add_weight_to_post_info(&mut result, <SelfWeightOf<T>>::check_allowed_raw());1265		result1266	}12671268	/// Burn NFT token for `from` account.1269	///1270	/// Same as the [`burn`] but spender doesn't need to be an owner of the token. The owner should1271	/// set allowance for the spender to burn token.1272	///1273	/// [`burn`]: struct.Pallet.html#method.burn1274	pub fn burn_from(1275		collection: &NonfungibleHandle<T>,1276		spender: &T::CrossAccountId,1277		from: &T::CrossAccountId,1278		token: TokenId,1279		nesting_budget: &dyn Budget,1280	) -> DispatchResult {1281		Self::check_allowed(collection, spender, from, token, nesting_budget)?;12821283		// =========12841285		Self::burn(collection, from, token)1286	}12871288	/// Check that `from` token could be nested in `under` token.1289	///1290	pub fn check_nesting(1291		handle: &NonfungibleHandle<T>,1292		sender: T::CrossAccountId,1293		from: (CollectionId, TokenId),1294		under: TokenId,1295		nesting_budget: &dyn Budget,1296	) -> DispatchResult {1297		let nesting = handle.permissions.nesting();12981299		#[cfg(not(feature = "runtime-benchmarks"))]1300		let permissive = false;1301		#[cfg(feature = "runtime-benchmarks")]1302		let permissive = nesting.permissive;13031304		if permissive {1305			ensure!(1306				<TokenData<T>>::contains_key((handle.id, under)),1307				<CommonError<T>>::TokenNotFound1308			);1309		} else if nesting.token_owner1310			&& <PalletStructure<T>>::check_indirectly_owned(1311				sender.clone(),1312				handle.id,1313				under,1314				Some(from),1315				nesting_budget,1316			)? {1317			// Pass, token existence and ouroboros checks are done in `check_indirectly_owned`1318		} else if nesting.collection_admin && handle.is_owner_or_admin(&sender) {1319			// token existence and ouroboros checks are done in `get_checked_topmost_owner`1320			let _ = <PalletStructure<T>>::get_checked_topmost_owner(1321				handle.id,1322				under,1323				Some(from),1324				nesting_budget,1325			)?1326			.ok_or(<CommonError<T>>::TokenNotFound)?;1327		} else {1328			fail!(<CommonError<T>>::UserIsNotAllowedToNest);1329		}13301331		if let Some(whitelist) = &nesting.restricted {1332			ensure!(1333				whitelist.contains(&from.0),1334				<CommonError<T>>::SourceCollectionIsNotAllowedToNest1335			);1336		}1337		Ok(())1338	}13391340	fn nest(under: (CollectionId, TokenId), to_nest: (CollectionId, TokenId)) {1341		if to_nest.0 != pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {1342			<TokenChildren<T>>::insert((under.0, under.1, to_nest), true);1343		}1344	}13451346	fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {1347		if to_unnest.0 != pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {1348			<TokenChildren<T>>::remove((under.0, under.1, to_unnest));1349		}1350	}13511352	fn collection_has_tokens(collection_id: CollectionId) -> bool {1353		<TokenData<T>>::iter_prefix((collection_id,))1354			.next()1355			.is_some()1356	}13571358	fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {1359		<TokenChildren<T>>::iter_prefix((collection_id, token_id))1360			.next()1361			.is_some()1362	}13631364	pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {1365		<TokenChildren<T>>::iter_prefix((collection_id, token_id))1366			.map(|((child_collection_id, child_id), _)| TokenChild {1367				collection: child_collection_id,1368				token: child_id,1369			})1370			.collect()1371	}13721373	/// Mint single NFT token.1374	///1375	/// Delegated to [`create_multiple_items`]1376	///1377	/// [`create_multiple_items`]: struct.Pallet.html#method.create_multiple_items1378	pub fn create_item(1379		collection: &NonfungibleHandle<T>,1380		sender: &T::CrossAccountId,1381		data: CreateItemData<T>,1382		nesting_budget: &dyn Budget,1383	) -> DispatchResult {1384		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1385	}13861387	/// Sets or unsets the approval of a given operator.1388	///1389	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1390	/// - `owner`: Token owner1391	/// - `operator`: Operator1392	/// - `approve`: Should operator status be granted or revoked?1393	pub fn set_allowance_for_all(1394		collection: &NonfungibleHandle<T>,1395		owner: &T::CrossAccountId,1396		operator: &T::CrossAccountId,1397		approve: bool,1398	) -> DispatchResult {1399		<PalletCommon<T>>::set_allowance_for_all(1400			collection,1401			owner,1402			operator,1403			approve,1404			|| <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve),1405			ERC721Events::ApprovalForAll {1406				owner: *owner.as_eth(),1407				operator: *operator.as_eth(),1408				approved: approve,1409			}1410			.to_log(collection_id_to_address(collection.id)),1411		)1412	}14131414	/// Tells whether the given `owner` approves the `operator`.1415	pub fn allowance_for_all(1416		collection: &NonfungibleHandle<T>,1417		owner: &T::CrossAccountId,1418		operator: &T::CrossAccountId,1419	) -> bool {1420		<CollectionAllowance<T>>::get((collection.id, owner, operator))1421	}14221423	pub fn repair_item(collection: &NonfungibleHandle<T>, token: TokenId) -> DispatchResult {1424		<TokenProperties<T>>::mutate((collection.id, token), |properties| {1425			properties.recompute_consumed_space();1426		});14271428		Ok(())1429	}1430}