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

difftreelog

source

pallets/nonfungible/src/lib.rs41.9 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,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 frame_system::pallet_prelude::*;155	use up_data_structs::{CollectionId, TokenId};156	use super::weights::WeightInfo;157158	#[pallet::error]159	pub enum Error<T> {160		/// Not Nonfungible item data used to mint in Nonfungible collection.161		NotNonfungibleDataUsedToMintFungibleCollectionToken,162		/// Used amount > 1 with NFT163		NonfungibleItemsHaveNoAmount,164		/// Unable to burn NFT with children165		CantBurnNftWithChildren,166	}167168	#[pallet::config]169	pub trait Config:170		frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config171	{172		type WeightInfo: WeightInfo;173	}174175	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);176177	#[pallet::pallet]178	#[pallet::storage_version(STORAGE_VERSION)]179	pub struct Pallet<T>(_);180181	/// Total amount of minted tokens in a collection.182	#[pallet::storage]183	pub type TokensMinted<T: Config> =184		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;185186	/// Amount of burnt tokens in a collection.187	#[pallet::storage]188	pub type TokensBurnt<T: Config> =189		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;190191	/// Token data, used to partially describe a token.192	#[pallet::storage]193	pub type TokenData<T: Config> = StorageNMap<194		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),195		Value = ItemData<T::CrossAccountId>,196		QueryKind = OptionQuery,197	>;198199	/// Map of key-value pairs, describing the metadata of a token.200	#[pallet::storage]201	#[pallet::getter(fn token_properties)]202	pub type TokenProperties<T: Config> = StorageNMap<203		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),204		Value = TokenPropertiesT,205		QueryKind = ValueQuery,206	>;207208	/// Custom data of a token that is serialized to bytes,209	/// primarily reserved for on-chain operations,210	/// normally obscured from the external users.211	///212	/// Auxiliary properties are slightly different from213	/// usual [`TokenProperties`] due to an unlimited number214	/// and separately stored and written-to key-value pairs.215	///216	/// Currently unused.217	#[pallet::storage]218	#[pallet::getter(fn token_aux_property)]219	pub type TokenAuxProperties<T: Config> = StorageNMap<220		Key = (221			Key<Twox64Concat, CollectionId>,222			Key<Twox64Concat, TokenId>,223			Key<Twox64Concat, PropertyScope>,224			Key<Twox64Concat, PropertyKey>,225		),226		Value = AuxPropertyValue,227		QueryKind = OptionQuery,228	>;229230	/// Used to enumerate tokens owned by account.231	#[pallet::storage]232	pub type Owned<T: Config> = StorageNMap<233		Key = (234			Key<Twox64Concat, CollectionId>,235			Key<Blake2_128Concat, T::CrossAccountId>,236			Key<Twox64Concat, TokenId>,237		),238		Value = bool,239		QueryKind = ValueQuery,240	>;241242	/// Used to enumerate token's children.243	#[pallet::storage]244	#[pallet::getter(fn token_children)]245	pub type TokenChildren<T: Config> = StorageNMap<246		Key = (247			Key<Twox64Concat, CollectionId>,248			Key<Twox64Concat, TokenId>,249			Key<Twox64Concat, (CollectionId, TokenId)>,250		),251		Value = bool,252		QueryKind = ValueQuery,253	>;254255	/// Amount of tokens owned by an account in a collection.256	#[pallet::storage]257	pub type AccountBalance<T: Config> = StorageNMap<258		Key = (259			Key<Twox64Concat, CollectionId>,260			Key<Blake2_128Concat, T::CrossAccountId>,261		),262		Value = u32,263		QueryKind = ValueQuery,264	>;265266	/// Allowance set by a token owner for another user to perform one of certain transactions on a token.267	#[pallet::storage]268	pub type Allowance<T: Config> = StorageNMap<269		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),270		Value = T::CrossAccountId,271		QueryKind = OptionQuery,272	>;273274	/// Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.275	#[pallet::storage]276	pub type CollectionAllowance<T: Config> = StorageNMap<277		Key = (278			Key<Twox64Concat, CollectionId>,279			Key<Blake2_128Concat, T::CrossAccountId>,280			Key<Blake2_128Concat, T::CrossAccountId>,281		),282		Value = bool,283		QueryKind = ValueQuery,284	>;285286	/// Upgrade from the old schema to properties.287	#[pallet::hooks]288	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {289		fn on_runtime_upgrade() -> Weight {290			StorageVersion::new(1).put::<Pallet<T>>();291292			Weight::zero()293		}294	}295}296297pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);298impl<T: Config> NonfungibleHandle<T> {299	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {300		Self(inner)301	}302	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {303		self.0304	}305	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {306		&mut self.0307	}308}309310impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {311	fn recorder(&self) -> &SubstrateRecorder<T> {312		self.0.recorder()313	}314	fn into_recorder(self) -> SubstrateRecorder<T> {315		self.0.into_recorder()316	}317}318impl<T: Config> Deref for NonfungibleHandle<T> {319	type Target = pallet_common::CollectionHandle<T>;320321	fn deref(&self) -> &Self::Target {322		&self.0323	}324}325326impl<T: Config> Pallet<T> {327	/// Get number of NFT tokens in collection.328	pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {329		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)330	}331332	/// Check that NFT token exists.333	///334	/// - `token`: Token ID.335	pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {336		<TokenData<T>>::contains_key((collection.id, token))337	}338339	/// Set the token property with the scope.340	///341	/// - `property`: Contains key-value pair.342	pub fn set_scoped_token_property(343		collection_id: CollectionId,344		token_id: TokenId,345		scope: PropertyScope,346		property: Property,347	) -> DispatchResult {348		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {349			properties.try_scoped_set(scope, property.key, property.value)350		})351		.map_err(<CommonError<T>>::from)?;352353		Ok(())354	}355356	/// Batch operation to set multiple properties with the same scope.357	pub fn set_scoped_token_properties(358		collection_id: CollectionId,359		token_id: TokenId,360		scope: PropertyScope,361		properties: impl Iterator<Item = Property>,362	) -> DispatchResult {363		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {364			stored_properties.try_scoped_set_from_iter(scope, properties)365		})366		.map_err(<CommonError<T>>::from)?;367368		Ok(())369	}370371	/// Add or edit auxiliary data for the property.372	///373	/// - `f`: function that adds or edits auxiliary data.374	pub fn try_mutate_token_aux_property<R, E>(375		collection_id: CollectionId,376		token_id: TokenId,377		scope: PropertyScope,378		key: PropertyKey,379		f: impl FnOnce(&mut Option<AuxPropertyValue>) -> Result<R, E>,380	) -> Result<R, E> {381		<TokenAuxProperties<T>>::try_mutate((collection_id, token_id, scope, key), f)382	}383384	/// Remove auxiliary data for the property.385	pub fn remove_token_aux_property(386		collection_id: CollectionId,387		token_id: TokenId,388		scope: PropertyScope,389		key: PropertyKey,390	) {391		<TokenAuxProperties<T>>::remove((collection_id, token_id, scope, key));392	}393394	/// Get all auxiliary data in a given scope.395	///396	/// Returns iterator over Property Key - Data pairs.397	pub fn iterate_token_aux_properties(398		collection_id: CollectionId,399		token_id: TokenId,400		scope: PropertyScope,401	) -> impl Iterator<Item = (PropertyKey, AuxPropertyValue)> {402		<TokenAuxProperties<T>>::iter_prefix((collection_id, token_id, scope))403	}404405	/// Get ID of the last minted token406	pub fn current_token_id(collection_id: CollectionId) -> TokenId {407		TokenId(<TokensMinted<T>>::get(collection_id))408	}409}410411// unchecked calls skips any permission checks412impl<T: Config> Pallet<T> {413	/// Create NFT collection414	///415	/// `init_collection` will take non-refundable deposit for collection creation.416	///417	/// - `data`: Contains settings for collection limits and permissions.418	pub fn init_collection(419		owner: T::CrossAccountId,420		payer: T::CrossAccountId,421		data: CreateCollectionData<T::AccountId>,422		flags: CollectionFlags,423	) -> Result<CollectionId, DispatchError> {424		<PalletCommon<T>>::init_collection(owner, payer, data, flags)425	}426427	/// Destroy NFT collection428	///429	/// `destroy_collection` will throw error if collection contains any tokens.430	/// Only owner can destroy collection.431	pub fn destroy_collection(432		collection: NonfungibleHandle<T>,433		sender: &T::CrossAccountId,434	) -> DispatchResult {435		let id = collection.id;436437		if Self::collection_has_tokens(id) {438			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());439		}440441		// =========442443		PalletCommon::destroy_collection(collection.0, sender)?;444445		let _ = <TokenData<T>>::clear_prefix((id,), u32::MAX, None);446		let _ = <TokenChildren<T>>::clear_prefix((id,), u32::MAX, None);447		let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);448		<TokensMinted<T>>::remove(id);449		<TokensBurnt<T>>::remove(id);450		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);451		let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);452		let _ = <CollectionAllowance<T>>::clear_prefix((id,), u32::MAX, None);453		Ok(())454	}455456	/// Burn NFT token457	///458	/// `burn` removes `token` from the `collection`, from it's owner and from the parent token459	/// if the token is nested.460	/// Only the owner can `burn` the token. The `token` shouldn't have any nested tokens.461	/// Also removes all corresponding properties and auxiliary properties.462	///463	/// - `token`: Token that should be burned464	/// - `collection`: Collection that contains the token465	pub fn burn(466		collection: &NonfungibleHandle<T>,467		sender: &T::CrossAccountId,468		token: TokenId,469	) -> DispatchResult {470		let token_data =471			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;472		ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);473474		if collection.permissions.access() == AccessMode::AllowList {475			collection.check_allowlist(sender)?;476		}477478		if Self::token_has_children(collection.id, token) {479			return Err(<Error<T>>::CantBurnNftWithChildren.into());480		}481482		let burnt = <TokensBurnt<T>>::get(collection.id)483			.checked_add(1)484			.ok_or(ArithmeticError::Overflow)?;485486		let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))487			.checked_sub(1)488			.ok_or(ArithmeticError::Overflow)?;489490		// =========491492		if balance == 0 {493			<AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));494		} else {495			<AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);496		}497498		<PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);499500		<Owned<T>>::remove((collection.id, &token_data.owner, token));501		<TokensBurnt<T>>::insert(collection.id, burnt);502		<TokenData<T>>::remove((collection.id, token));503		<TokenProperties<T>>::remove((collection.id, token));504		let _ = <TokenAuxProperties<T>>::clear_prefix((collection.id, token), u32::MAX, None);505		let old_spender = <Allowance<T>>::take((collection.id, token));506507		if let Some(old_spender) = old_spender {508			<PalletCommon<T>>::deposit_event(CommonEvent::Approved(509				collection.id,510				token,511				token_data.owner.clone(),512				old_spender,513				0,514			));515		}516517		<PalletEvm<T>>::deposit_log(518			ERC721Events::Transfer {519				from: *token_data.owner.as_eth(),520				to: H160::default(),521				token_id: token.into(),522			}523			.to_log(collection_id_to_address(collection.id)),524		);525		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(526			collection.id,527			token,528			token_data.owner,529			1,530		));531		Ok(())532	}533534	/// Same as [`burn`] but burns all the tokens that are nested in the token first535	///536	/// - `self_budget`: Limit for searching children in depth.537	/// - `breadth_budget`: Limit of breadth of searching children.538	///539	/// [`burn`]: struct.Pallet.html#method.burn540	#[transactional]541	pub fn burn_recursively(542		collection: &NonfungibleHandle<T>,543		sender: &T::CrossAccountId,544		token: TokenId,545		self_budget: &dyn Budget,546		breadth_budget: &dyn Budget,547	) -> DispatchResultWithPostInfo {548		ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);549550		let current_token_account =551			T::CrossTokenAddressMapping::token_to_address(collection.id, token);552553		let mut weight = Weight::zero();554555		// This method is transactional, if user in fact doesn't have permissions to remove token -556		// tokens removed here will be restored after rejected transaction557		for ((collection, token), _) in <TokenChildren<T>>::iter_prefix((collection.id, token)) {558			ensure!(breadth_budget.consume(), <StructureError<T>>::BreadthLimit,);559			let PostDispatchInfo { actual_weight, .. } =560				<PalletStructure<T>>::burn_item_recursively(561					current_token_account.clone(),562					collection,563					token,564					self_budget,565					breadth_budget,566				)?;567			if let Some(actual_weight) = actual_weight {568				weight = weight.saturating_add(actual_weight);569			}570		}571572		Self::burn(collection, sender, token)?;573		DispatchResultWithPostInfo::Ok(PostDispatchInfo {574			actual_weight: Some(weight + <SelfWeightOf<T>>::burn_item()),575			pays_fee: Pays::Yes,576		})577	}578579	/// A batch operation to add, edit or remove properties for a token.580	///581	/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.582	/// - `is_token_create`: Indicates that method is called during token initialization.583	///   Allows to bypass ownership check.584	///585	/// All affected properties should have `mutable` permission586	/// to be **deleted** or to be **set more than once**,587	/// and the sender should have permission to edit those properties.588	///589	/// This function fires an event for each property change.590	/// In case of an error, all the changes (including the events) will be reverted591	/// since the function is transactional.592	#[transactional]593	fn modify_token_properties(594		collection: &NonfungibleHandle<T>,595		sender: &T::CrossAccountId,596		token_id: TokenId,597		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,598		is_token_create: bool,599		nesting_budget: &dyn Budget,600	) -> DispatchResult {601		let is_token_owner = || {602			let is_owned = <PalletStructure<T>>::check_indirectly_owned(603				sender.clone(),604				collection.id,605				token_id,606				None,607				nesting_budget,608			)?;609610			Ok(is_owned)611		};612613		let stored_properties = <TokenProperties<T>>::get((collection.id, token_id));614615		<PalletCommon<T>>::modify_token_properties(616			collection,617			sender,618			token_id,619			properties_updates,620			is_token_create,621			stored_properties,622			is_token_owner,623			|properties| <TokenProperties<T>>::set((collection.id, token_id), properties),624			erc::ERC721TokenEvent::TokenChanged {625				token_id: token_id.into(),626			}627			.to_log(T::ContractAddress::get()),628		)629	}630631	/// Batch operation to add or edit properties for the token632	///633	/// Same as [`modify_token_properties`] but doesn't allow to remove properties634	///635	/// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties636	pub fn set_token_properties(637		collection: &NonfungibleHandle<T>,638		sender: &T::CrossAccountId,639		token_id: TokenId,640		properties: impl Iterator<Item = Property>,641		is_token_create: bool,642		nesting_budget: &dyn Budget,643	) -> DispatchResult {644		Self::modify_token_properties(645			collection,646			sender,647			token_id,648			properties.map(|p| (p.key, Some(p.value))),649			is_token_create,650			nesting_budget,651		)652	}653654	/// Add or edit single property for the token655	///656	/// Calls [`set_token_properties`] internally657	///658	/// [`set_token_properties`]: struct.Pallet.html#method.set_token_properties659	pub fn set_token_property(660		collection: &NonfungibleHandle<T>,661		sender: &T::CrossAccountId,662		token_id: TokenId,663		property: Property,664		nesting_budget: &dyn Budget,665	) -> DispatchResult {666		let is_token_create = false;667668		Self::set_token_properties(669			collection,670			sender,671			token_id,672			[property].into_iter(),673			is_token_create,674			nesting_budget,675		)676	}677678	/// Batch operation to remove properties from the token679	///680	/// Same as [`modify_token_properties`] but doesn't allow to add or edit properties681	///682	/// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties683	pub fn delete_token_properties(684		collection: &NonfungibleHandle<T>,685		sender: &T::CrossAccountId,686		token_id: TokenId,687		property_keys: impl Iterator<Item = PropertyKey>,688		nesting_budget: &dyn Budget,689	) -> DispatchResult {690		let is_token_create = false;691692		Self::modify_token_properties(693			collection,694			sender,695			token_id,696			property_keys.into_iter().map(|key| (key, None)),697			is_token_create,698			nesting_budget,699		)700	}701702	/// Remove single property from the token703	///704	/// Calls [`delete_token_properties`] internally705	///706	/// [`delete_token_properties`]: struct.Pallet.html#method.delete_token_properties707	pub fn delete_token_property(708		collection: &NonfungibleHandle<T>,709		sender: &T::CrossAccountId,710		token_id: TokenId,711		property_key: PropertyKey,712		nesting_budget: &dyn Budget,713	) -> DispatchResult {714		Self::delete_token_properties(715			collection,716			sender,717			token_id,718			[property_key].into_iter(),719			nesting_budget,720		)721	}722723	/// Add or edit properties for the collection724	pub fn set_collection_properties(725		collection: &NonfungibleHandle<T>,726		sender: &T::CrossAccountId,727		properties: Vec<Property>,728	) -> DispatchResult {729		<PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())730	}731732	/// Remove properties from the collection733	pub fn delete_collection_properties(734		collection: &CollectionHandle<T>,735		sender: &T::CrossAccountId,736		property_keys: Vec<PropertyKey>,737	) -> DispatchResult {738		<PalletCommon<T>>::delete_collection_properties(739			collection,740			sender,741			property_keys.into_iter(),742		)743	}744745	/// Set property permissions for the token.746	///747	/// Sender should be the owner or admin of token's collection.748	pub fn set_token_property_permissions(749		collection: &CollectionHandle<T>,750		sender: &T::CrossAccountId,751		property_permissions: Vec<PropertyKeyPermission>,752	) -> DispatchResult {753		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)754	}755756	/// Set property permissions for the token with scope.757	///758	/// Sender should be the owner or admin of token's collection.759	pub fn set_scoped_token_property_permissions(760		collection: &CollectionHandle<T>,761		sender: &T::CrossAccountId,762		scope: PropertyScope,763		property_permissions: Vec<PropertyKeyPermission>,764	) -> DispatchResult {765		<PalletCommon<T>>::set_scoped_token_property_permissions(766			collection,767			sender,768			scope,769			property_permissions,770		)771	}772773	pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {774		<PalletCommon<T>>::property_permissions(collection_id)775	}776777	pub fn check_token_immediate_ownership(778		collection: &NonfungibleHandle<T>,779		token: TokenId,780		possible_owner: &T::CrossAccountId,781	) -> DispatchResult {782		let token_data =783			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;784		ensure!(785			&token_data.owner == possible_owner,786			<CommonError<T>>::NoPermission787		);788		Ok(())789	}790791	/// Transfer NFT token from one account to another.792	///793	/// `from` account stops being the owner and `to` account becomes the owner of the token.794	/// If `to` is token than `to` becomes owner of the token and the token become nested.795	/// Unnests token from previous parent if it was nested before.796	/// Removes allowance for the token if there was any.797	/// Throws if transfers aren't allowed for collection or if receiver reached token ownership limit.798	///799	/// - `nesting_budget`: Limit for token nesting depth800	pub fn transfer(801		collection: &NonfungibleHandle<T>,802		from: &T::CrossAccountId,803		to: &T::CrossAccountId,804		token: TokenId,805		nesting_budget: &dyn Budget,806	) -> DispatchResultWithPostInfo {807		ensure!(808			collection.limits.transfers_enabled(),809			<CommonError<T>>::TransferNotAllowed810		);811812		let token_data =813			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;814		ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);815816		let is_allow_list_mode = collection.permissions.access() == AccessMode::AllowList;817		if is_allow_list_mode {818			collection.check_allowlist(from)?;819			collection.check_allowlist(to)?;820		}821		<PalletCommon<T>>::ensure_correct_receiver(to)?;822823		let balance_from = <AccountBalance<T>>::get((collection.id, from))824			.checked_sub(1)825			.ok_or(<CommonError<T>>::TokenValueTooLow)?;826		let balance_to = if from != to {827			let balance_to = <AccountBalance<T>>::get((collection.id, to))828				.checked_add(1)829				.ok_or(ArithmeticError::Overflow)?;830831			ensure!(832				balance_to < collection.limits.account_token_ownership_limit(),833				<CommonError<T>>::AccountTokenLimitExceeded,834			);835836			Some(balance_to)837		} else {838			None839		};840841		<PalletStructure<T>>::nest_if_sent_to_token(842			from.clone(),843			to,844			collection.id,845			token,846			nesting_budget,847		)?;848849		// =========850851		<PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);852853		<TokenData<T>>::insert(854			(collection.id, token),855			ItemData {856				owner: to.clone(),857				..token_data858			},859		);860861		if let Some(balance_to) = balance_to {862			// from != to863			if balance_from == 0 {864				<AccountBalance<T>>::remove((collection.id, from));865			} else {866				<AccountBalance<T>>::insert((collection.id, from), balance_from);867			}868			<AccountBalance<T>>::insert((collection.id, to), balance_to);869			<Owned<T>>::remove((collection.id, from, token));870			<Owned<T>>::insert((collection.id, to, token), true);871		}872		Self::set_allowance_unchecked(collection, from, token, None, true);873874		<PalletEvm<T>>::deposit_log(875			ERC721Events::Transfer {876				from: *from.as_eth(),877				to: *to.as_eth(),878				token_id: token.into(),879			}880			.to_log(collection_id_to_address(collection.id)),881		);882		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(883			collection.id,884			token,885			from.clone(),886			to.clone(),887			1,888		));889890		let actual_weight = match is_allow_list_mode {891			true => Some(892				<SelfWeightOf<T>>::transfer() + <PalletCommonWeightOf<T>>::check_accesslist() * 2,893			),894			false => Some(<SelfWeightOf<T>>::transfer()),895		};896897		Ok(PostDispatchInfo {898			actual_weight,899			pays_fee: Pays::Yes,900		})901	}902903	/// Batch operation to mint multiple NFT tokens.904	///905	/// The sender should be the owner/admin of the collection or collection should be configured906	/// to allow public minting.907	/// Throws if amount of tokens reached it's limit for the collection or if caller reached908	/// token ownership limit.909	///910	/// - `data`: Contains list of token properties and users who will become the owners of the911	///   corresponging tokens.912	/// - `nesting_budget`: Limit for token nesting depth913	pub fn create_multiple_items(914		collection: &NonfungibleHandle<T>,915		sender: &T::CrossAccountId,916		data: Vec<CreateItemData<T>>,917		nesting_budget: &dyn Budget,918	) -> DispatchResult {919		if !collection.is_owner_or_admin(sender) {920			ensure!(921				collection.permissions.mint_mode(),922				<CommonError<T>>::PublicMintingNotAllowed923			);924			collection.check_allowlist(sender)?;925926			for item in data.iter() {927				collection.check_allowlist(&item.owner)?;928			}929		}930931		for data in data.iter() {932			<PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;933		}934935		let first_token = <TokensMinted<T>>::get(collection.id);936		let tokens_minted = first_token937			.checked_add(data.len() as u32)938			.ok_or(ArithmeticError::Overflow)?;939		ensure!(940			tokens_minted <= collection.limits.token_limit(),941			<CommonError<T>>::CollectionTokenLimitExceeded942		);943944		let mut balances = BTreeMap::new();945		for data in &data {946			let balance = balances947				.entry(&data.owner)948				.or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));949			*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;950951			ensure!(952				*balance <= collection.limits.account_token_ownership_limit(),953				<CommonError<T>>::AccountTokenLimitExceeded,954			);955		}956957		for (i, data) in data.iter().enumerate() {958			let token = TokenId(first_token + i as u32 + 1);959960			<PalletStructure<T>>::check_nesting(961				sender.clone(),962				&data.owner,963				collection.id,964				token,965				nesting_budget,966			)?;967		}968969		// =========970971		with_transaction(|| {972			for (i, data) in data.iter().enumerate() {973				let token = first_token + i as u32 + 1;974975				<TokenData<T>>::insert(976					(collection.id, token),977					ItemData {978						// const_data: data.const_data.clone(),979						owner: data.owner.clone(),980					},981				);982983				<PalletStructure<T>>::nest_if_sent_to_token_unchecked(984					&data.owner,985					collection.id,986					TokenId(token),987				);988989				if let Err(e) = Self::set_token_properties(990					collection,991					sender,992					TokenId(token),993					data.properties.clone().into_iter(),994					true,995					nesting_budget,996				) {997					return TransactionOutcome::Rollback(Err(e));998				}999			}1000			TransactionOutcome::Commit(Ok(()))1001		})?;10021003		<TokensMinted<T>>::insert(collection.id, tokens_minted);1004		for (account, balance) in balances {1005			<AccountBalance<T>>::insert((collection.id, account), balance);1006		}1007		for (i, data) in data.into_iter().enumerate() {1008			let token = first_token + i as u32 + 1;1009			<Owned<T>>::insert((collection.id, &data.owner, token), true);10101011			<PalletEvm<T>>::deposit_log(1012				ERC721Events::Transfer {1013					from: H160::default(),1014					to: *data.owner.as_eth(),1015					token_id: token.into(),1016				}1017				.to_log(collection_id_to_address(collection.id)),1018			);1019			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1020				collection.id,1021				TokenId(token),1022				data.owner.clone(),1023				1,1024			));1025		}1026		Ok(())1027	}10281029	pub fn set_allowance_unchecked(1030		collection: &NonfungibleHandle<T>,1031		sender: &T::CrossAccountId,1032		token: TokenId,1033		spender: Option<&T::CrossAccountId>,1034		assume_implicit_eth: bool,1035	) {1036		if let Some(spender) = spender {1037			let old_spender = <Allowance<T>>::get((collection.id, token));1038			<Allowance<T>>::insert((collection.id, token), spender);1039			// In ERC721 there is only one possible approved user of token, so we set1040			// approved user to spender1041			<PalletEvm<T>>::deposit_log(1042				ERC721Events::Approval {1043					owner: *sender.as_eth(),1044					approved: *spender.as_eth(),1045					token_id: token.into(),1046				}1047				.to_log(collection_id_to_address(collection.id)),1048			);1049			// In Unique chain, any token can have any amount of approved users, so we need to1050			// set allowance of old owner to 0, and allowance of new owner to 11051			if old_spender.as_ref() != Some(spender) {1052				if let Some(old_owner) = old_spender {1053					<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1054						collection.id,1055						token,1056						sender.clone(),1057						old_owner,1058						0,1059					));1060				}1061				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1062					collection.id,1063					token,1064					sender.clone(),1065					spender.clone(),1066					1,1067				));1068			}1069		} else {1070			let old_spender = <Allowance<T>>::take((collection.id, token));1071			if !assume_implicit_eth {1072				// In ERC721 there is only one possible approved user of token, so we set1073				// approved user to zero address1074				<PalletEvm<T>>::deposit_log(1075					ERC721Events::Approval {1076						owner: *sender.as_eth(),1077						approved: H160::default(),1078						token_id: token.into(),1079					}1080					.to_log(collection_id_to_address(collection.id)),1081				);1082			}1083			// In Unique chain, any token can have any amount of approved users, so we need to1084			// set allowance of old owner to 01085			if let Some(old_spender) = old_spender {1086				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1087					collection.id,1088					token,1089					sender.clone(),1090					old_spender,1091					0,1092				));1093			}1094		}1095	}10961097	pub fn get_allowance(1098		collection: &NonfungibleHandle<T>,1099		token_id: TokenId,1100	) -> Result<Option<T::CrossAccountId>, DispatchError> {1101		ensure!(1102			<TokenData<T>>::get((collection.id, token_id)).is_some(),1103			<CommonError<T>>::TokenNotFound1104		);1105		Ok(<Allowance<T>>::get((collection.id, token_id)))1106	}11071108	/// Set allowance for the spender to `transfer` or `burn` sender's token.1109	///1110	/// - `token`: Token the spender is allowed to `transfer` or `burn`.1111	pub fn set_allowance(1112		collection: &NonfungibleHandle<T>,1113		sender: &T::CrossAccountId,1114		token: TokenId,1115		spender: Option<&T::CrossAccountId>,1116	) -> DispatchResult {1117		if collection.permissions.access() == AccessMode::AllowList {1118			collection.check_allowlist(sender)?;1119			if let Some(spender) = spender {1120				collection.check_allowlist(spender)?;1121			}1122		}11231124		if let Some(spender) = spender {1125			<PalletCommon<T>>::ensure_correct_receiver(spender)?;1126		}11271128		let token_data =1129			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1130		if &token_data.owner != sender {1131			ensure!(1132				collection.ignores_owned_amount(sender),1133				<CommonError<T>>::CantApproveMoreThanOwned1134			);1135		}11361137		// =========11381139		Self::set_allowance_unchecked(collection, sender, token, spender, false);1140		Ok(())1141	}11421143	/// Set allowance for the spender to `transfer` or `burn` sender's token from eth mirror.1144	///1145	/// - `from`: Address of sender's eth mirror.1146	/// - `to`: Adress of spender.1147	/// - `token`: Token the spender is allowed to `transfer` or `burn`.1148	pub fn set_allowance_from(1149		collection: &NonfungibleHandle<T>,1150		sender: &T::CrossAccountId,1151		from: &T::CrossAccountId,1152		token: TokenId,1153		to: Option<&T::CrossAccountId>,1154	) -> DispatchResult {1155		if collection.permissions.access() == AccessMode::AllowList {1156			collection.check_allowlist(sender)?;1157			collection.check_allowlist(from)?;1158			if let Some(to) = to {1159				collection.check_allowlist(to)?;1160			}1161		}11621163		if let Some(to) = to {1164			<PalletCommon<T>>::ensure_correct_receiver(to)?;1165		}11661167		ensure!(1168			sender.conv_eq(from),1169			<CommonError<T>>::AddressIsNotEthMirror1170		);11711172		let token_data =1173			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1174		if token_data.owner != *from {1175			ensure!(1176				collection.limits.owner_can_transfer()1177					&& (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),1178				<CommonError<T>>::CantApproveMoreThanOwned1179			);1180		}11811182		// =========11831184		Self::set_allowance_unchecked(collection, from, token, to, false);1185		Ok(())1186	}11871188	/// Checks allowance for the spender to use the token.1189	fn check_allowed(1190		collection: &NonfungibleHandle<T>,1191		spender: &T::CrossAccountId,1192		from: &T::CrossAccountId,1193		token: TokenId,1194		nesting_budget: &dyn Budget,1195	) -> DispatchResult {1196		if spender.conv_eq(from) {1197			return Ok(());1198		}1199		if collection.permissions.access() == AccessMode::AllowList {1200			// `from`, `to` checked in [`transfer`]1201			collection.check_allowlist(spender)?;1202		}12031204		if collection.ignores_token_restrictions(spender) {1205			return Ok(());1206		}12071208		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1209			ensure!(1210				<PalletStructure<T>>::check_indirectly_owned(1211					spender.clone(),1212					source.0,1213					source.1,1214					None,1215					nesting_budget1216				)?,1217				<CommonError<T>>::ApprovedValueTooLow,1218			);1219			return Ok(());1220		}1221		if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {1222			return Ok(());1223		}1224		if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1225			return Ok(());1226		}12271228		Err(<CommonError<T>>::ApprovedValueTooLow.into())1229	}12301231	/// Transfer NFT token from one account to another.1232	///1233	/// Same as the [`transfer`] but spender doesn't needs to be the owner of the token.1234	/// The owner should set allowance for the spender to transfer token.1235	///1236	/// [`transfer`]: struct.Pallet.html#method.transfer1237	pub fn transfer_from(1238		collection: &NonfungibleHandle<T>,1239		spender: &T::CrossAccountId,1240		from: &T::CrossAccountId,1241		to: &T::CrossAccountId,1242		token: TokenId,1243		nesting_budget: &dyn Budget,1244	) -> DispatchResultWithPostInfo {1245		Self::check_allowed(collection, spender, from, token, nesting_budget)?;12461247		// =========12481249		// Allowance is reset in [`transfer`]1250		Self::transfer(collection, from, to, token, nesting_budget).map(|mut p| {1251			p.actual_weight = Some(1252				p.actual_weight.unwrap_or_default() + <SelfWeightOf<T>>::checks_for_transfer_from(),1253			);1254			p1255		})1256	}12571258	/// Burn NFT token for `from` account.1259	///1260	/// Same as the [`burn`] but spender doesn't need to be an owner of the token. The owner should1261	/// set allowance for the spender to burn token.1262	///1263	/// [`burn`]: struct.Pallet.html#method.burn1264	pub fn burn_from(1265		collection: &NonfungibleHandle<T>,1266		spender: &T::CrossAccountId,1267		from: &T::CrossAccountId,1268		token: TokenId,1269		nesting_budget: &dyn Budget,1270	) -> DispatchResult {1271		Self::check_allowed(collection, spender, from, token, nesting_budget)?;12721273		// =========12741275		Self::burn(collection, from, token)1276	}12771278	/// Check that `from` token could be nested in `under` token.1279	///1280	pub fn check_nesting(1281		handle: &NonfungibleHandle<T>,1282		sender: T::CrossAccountId,1283		from: (CollectionId, TokenId),1284		under: TokenId,1285		nesting_budget: &dyn Budget,1286	) -> DispatchResult {1287		let nesting = handle.permissions.nesting();12881289		#[cfg(not(feature = "runtime-benchmarks"))]1290		let permissive = false;1291		#[cfg(feature = "runtime-benchmarks")]1292		let permissive = nesting.permissive;12931294		if permissive {1295			ensure!(1296				<TokenData<T>>::contains_key((handle.id, under)),1297				<CommonError<T>>::TokenNotFound1298			);1299		} else if nesting.token_owner1300			&& <PalletStructure<T>>::check_indirectly_owned(1301				sender.clone(),1302				handle.id,1303				under,1304				Some(from),1305				nesting_budget,1306			)? {1307			// Pass, token existence and ouroboros checks are done in `check_indirectly_owned`1308		} else if nesting.collection_admin && handle.is_owner_or_admin(&sender) {1309			// token existence and ouroboros checks are done in `get_checked_topmost_owner`1310			let _ = <PalletStructure<T>>::get_checked_topmost_owner(1311				handle.id,1312				under,1313				Some(from),1314				nesting_budget,1315			)?1316			.ok_or(<CommonError<T>>::TokenNotFound)?;1317		} else {1318			fail!(<CommonError<T>>::UserIsNotAllowedToNest);1319		}13201321		if let Some(whitelist) = &nesting.restricted {1322			ensure!(1323				whitelist.contains(&from.0),1324				<CommonError<T>>::SourceCollectionIsNotAllowedToNest1325			);1326		}1327		Ok(())1328	}13291330	fn nest(under: (CollectionId, TokenId), to_nest: (CollectionId, TokenId)) {1331		<TokenChildren<T>>::insert((under.0, under.1, (to_nest.0, to_nest.1)), true);1332	}13331334	fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {1335		<TokenChildren<T>>::remove((under.0, under.1, to_unnest));1336	}13371338	fn collection_has_tokens(collection_id: CollectionId) -> bool {1339		<TokenData<T>>::iter_prefix((collection_id,))1340			.next()1341			.is_some()1342	}13431344	fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {1345		<TokenChildren<T>>::iter_prefix((collection_id, token_id))1346			.next()1347			.is_some()1348	}13491350	pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {1351		<TokenChildren<T>>::iter_prefix((collection_id, token_id))1352			.map(|((child_collection_id, child_id), _)| TokenChild {1353				collection: child_collection_id,1354				token: child_id,1355			})1356			.collect()1357	}13581359	/// Mint single NFT token.1360	///1361	/// Delegated to [`create_multiple_items`]1362	///1363	/// [`create_multiple_items`]: struct.Pallet.html#method.create_multiple_items1364	pub fn create_item(1365		collection: &NonfungibleHandle<T>,1366		sender: &T::CrossAccountId,1367		data: CreateItemData<T>,1368		nesting_budget: &dyn Budget,1369	) -> DispatchResult {1370		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1371	}13721373	/// Sets or unsets the approval of a given operator.1374	///1375	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1376	/// - `owner`: Token owner1377	/// - `operator`: Operator1378	/// - `approve`: Should operator status be granted or revoked?1379	pub fn set_allowance_for_all(1380		collection: &NonfungibleHandle<T>,1381		owner: &T::CrossAccountId,1382		operator: &T::CrossAccountId,1383		approve: bool,1384	) -> DispatchResult {1385		<PalletCommon<T>>::set_allowance_for_all(1386			collection,1387			owner,1388			operator,1389			approve,1390			|| <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve),1391			ERC721Events::ApprovalForAll {1392				owner: *owner.as_eth(),1393				operator: *operator.as_eth(),1394				approved: approve,1395			}1396			.to_log(collection_id_to_address(collection.id)),1397		)1398	}13991400	/// Tells whether the given `owner` approves the `operator`.1401	pub fn allowance_for_all(1402		collection: &NonfungibleHandle<T>,1403		owner: &T::CrossAccountId,1404		operator: &T::CrossAccountId,1405	) -> bool {1406		<CollectionAllowance<T>>::get((collection.id, owner, operator))1407	}14081409	pub fn repair_item(collection: &NonfungibleHandle<T>, token: TokenId) -> DispatchResult {1410		<TokenProperties<T>>::mutate((collection.id, token), |properties| {1411			properties.recompute_consumed_space();1412		});14131414		Ok(())1415	}1416}