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

difftreelog

Merge pull request #920 from UniqueNetwork/fix/on-runtime-upgrade

Yaroslav Bolyukin2023-04-20parents: #2eecdab #81e4404.patch.diff
in: master

9 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5996,7 +5996,7 @@
 
 [[package]]
 name = "pallet-app-promotion"
-version = "0.1.5"
+version = "0.1.6"
 dependencies = [
  "frame-benchmarking",
  "frame-support",
modifiednode/cli/src/chain_spec.rsdiffbeforeafterboth
--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -167,6 +167,8 @@
 					.map(|k| (k, 1 << 100))
 					.collect(),
 			},
+			common: Default::default(),
+			nonfungible: Default::default(),
 			treasury: Default::default(),
 			tokens: TokensConfig { balances: vec![] },
 			sudo: SudoConfig {
@@ -225,6 +227,8 @@
 					.expect("WASM binary was not build, please build it!")
 					.to_vec(),
 			},
+			common: Default::default(),
+			nonfungible: Default::default(),
 			balances: BalancesConfig {
 				balances: $endowed_accounts
 					.iter()
modifiedpallets/app-promotion/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/app-promotion/CHANGELOG.md
+++ b/pallets/app-promotion/CHANGELOG.md
@@ -3,6 +3,11 @@
 All notable changes to this project will be documented in this file.
 
 <!-- bureaucrate goes here -->
+## [0.1.6] - 2023-04-19
+
+- ### Fixed
+
+- Useless `on_runtime_upgrade()` has been removed
 
 ## [0.1.5] - 2023-02-14
 
modifiedpallets/app-promotion/Cargo.tomldiffbeforeafterboth
--- a/pallets/app-promotion/Cargo.toml
+++ b/pallets/app-promotion/Cargo.toml
@@ -9,7 +9,7 @@
 license = 'GPLv3'
 name = 'pallet-app-promotion'
 repository = 'https://github.com/UniqueNetwork/unique-chain'
-version = '0.1.5'
+version = '0.1.6'
 
 [package.metadata.docs.rs]
 targets = ['x86_64-unknown-linux-gnu']
modifiedpallets/app-promotion/src/lib.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/lib.rs
+++ b/pallets/app-promotion/src/lib.rs
@@ -263,10 +263,6 @@
 	pub type PreviousCalculatedRecord<T: Config> =
 		StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;
 
-	#[pallet::storage]
-	pub(crate) type UpgradedToReserves<T: Config> =
-		StorageValue<Value = bool, QueryKind = ValueQuery>;
-
 	#[pallet::hooks]
 	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
 		/// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize
@@ -289,12 +285,6 @@
 			}
 
 			<T as Config>::WeightInfo::on_initialize(counter)
-		}
-
-		fn on_runtime_upgrade() -> Weight {
-			<UpgradedToReserves<T>>::kill();
-
-			T::DbWeight::get().reads_writes(0, 1)
 		}
 	}
 
modifiedpallets/common/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/common/CHANGELOG.md
+++ b/pallets/common/CHANGELOG.md
@@ -3,7 +3,12 @@
 All notable changes to this project will be documented in this file.
 
 <!-- bureaucrate goes here -->
+## [0.1.14] - 2023-04-19
+
+- ### Fixed
 
+- Useless `on_runtime_upgrade()` has been removed
+
 ## [0.1.14] - 2023-03-28
 
 ### Added
@@ -82,7 +87,7 @@
 However, we don't use prefix removal limits, so upgrade is
 straightforward
 
-Upstream-Change: https://github.com/paritytech/substrate/pull/11490
+Upstream-Change: <https://github.com/paritytech/substrate/pull/11490>
 
 - build: Upgrade polkadot to v0.9.25 cdfb9bdc7b205ff1b5134f034ef9973d769e5e6b
 
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -420,10 +420,11 @@
 
 #[frame_support::pallet]
 pub mod pallet {
+	use core::marker::PhantomData;
+
 	use super::*;
 	use dispatch::CollectionDispatch;
 	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};
-	use frame_system::pallet_prelude::*;
 	use frame_support::traits::Currency;
 	use up_data_structs::{TokenId, mapping::TokenAddressMapping};
 	use scale_info::TypeInfo;
@@ -479,6 +480,23 @@
 		}
 	}
 
+	#[pallet::genesis_config]
+	pub struct GenesisConfig<T>(PhantomData<T>);
+
+	#[cfg(feature = "std")]
+	impl<T: Config> Default for GenesisConfig<T> {
+		fn default() -> Self {
+			Self(Default::default())
+		}
+	}
+
+	#[pallet::genesis_build]
+	impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
+		fn build(&self) {
+			StorageVersion::new(1).put::<Pallet<T>>();
+		}
+	}
+
 	impl<T: Config> Pallet<T> {
 		/// Helper function that handles deposit events
 		pub fn deposit_event(event: Event<T>) {
@@ -869,15 +887,6 @@
 		),
 		QueryKind = OptionQuery,
 	>;
-
-	#[pallet::hooks]
-	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
-		fn on_runtime_upgrade() -> Weight {
-			StorageVersion::new(1).put::<Pallet<T>>();
-
-			Weight::zero()
-		}
-	}
 }
 
 impl<T: Config> Pallet<T> {
modifiedpallets/nonfungible/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/nonfungible/CHANGELOG.md
+++ b/pallets/nonfungible/CHANGELOG.md
@@ -3,7 +3,12 @@
 All notable changes to this project will be documented in this file.
 
 <!-- bureaucrate goes here -->
+## [0.1.14] - 2023-04-19
+
+- ### Fixed
 
+- Useless `on_runtime_upgrade()` has been removed
+
 ## [0.1.14] - 2023-03-28
 
 ### Fixed
@@ -83,7 +88,7 @@
 However, we don't use prefix removal limits, so upgrade is
 straightforward
 
-Upstream-Change: https://github.com/paritytech/substrate/pull/11490
+Upstream-Change: <https://github.com/paritytech/substrate/pull/11490>
 
 - build: Upgrade polkadot to v0.9.25 cdfb9bdc7b205ff1b5134f034ef9973d769e5e6b
 
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
before · pallets/nonfungible/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # 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,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 mut actual_weight = <SelfWeightOf<T>>::transfer_raw();813		let token_data =814			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;815		ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);816817		if collection.permissions.access() == AccessMode::AllowList {818			collection.check_allowlist(from)?;819			collection.check_allowlist(to)?;820			actual_weight += <PalletCommonWeightOf<T>>::check_accesslist() * 2;821		}822		<PalletCommon<T>>::ensure_correct_receiver(to)?;823824		let balance_from = <AccountBalance<T>>::get((collection.id, from))825			.checked_sub(1)826			.ok_or(<CommonError<T>>::TokenValueTooLow)?;827		let balance_to = if from != to {828			let balance_to = <AccountBalance<T>>::get((collection.id, to))829				.checked_add(1)830				.ok_or(ArithmeticError::Overflow)?;831832			ensure!(833				balance_to < collection.limits.account_token_ownership_limit(),834				<CommonError<T>>::AccountTokenLimitExceeded,835			);836837			Some(balance_to)838		} else {839			None840		};841842		<PalletStructure<T>>::nest_if_sent_to_token(843			from.clone(),844			to,845			collection.id,846			token,847			nesting_budget,848		)?;849850		// =========851852		<PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);853854		<TokenData<T>>::insert(855			(collection.id, token),856			ItemData {857				owner: to.clone(),858				..token_data859			},860		);861862		if let Some(balance_to) = balance_to {863			// from != to864			if balance_from == 0 {865				<AccountBalance<T>>::remove((collection.id, from));866			} else {867				<AccountBalance<T>>::insert((collection.id, from), balance_from);868			}869			<AccountBalance<T>>::insert((collection.id, to), balance_to);870			<Owned<T>>::remove((collection.id, from, token));871			<Owned<T>>::insert((collection.id, to, token), true);872		}873		Self::set_allowance_unchecked(collection, from, token, None, true);874875		<PalletEvm<T>>::deposit_log(876			ERC721Events::Transfer {877				from: *from.as_eth(),878				to: *to.as_eth(),879				token_id: token.into(),880			}881			.to_log(collection_id_to_address(collection.id)),882		);883		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(884			collection.id,885			token,886			from.clone(),887			to.clone(),888			1,889		));890891		Ok(PostDispatchInfo {892			actual_weight: Some(actual_weight),893			pays_fee: Pays::Yes,894		})895	}896897	/// Batch operation to mint multiple NFT tokens.898	///899	/// The sender should be the owner/admin of the collection or collection should be configured900	/// to allow public minting.901	/// Throws if amount of tokens reached it's limit for the collection or if caller reached902	/// token ownership limit.903	///904	/// - `data`: Contains list of token properties and users who will become the owners of the905	///   corresponging tokens.906	/// - `nesting_budget`: Limit for token nesting depth907	pub fn create_multiple_items(908		collection: &NonfungibleHandle<T>,909		sender: &T::CrossAccountId,910		data: Vec<CreateItemData<T>>,911		nesting_budget: &dyn Budget,912	) -> DispatchResult {913		if !collection.is_owner_or_admin(sender) {914			ensure!(915				collection.permissions.mint_mode(),916				<CommonError<T>>::PublicMintingNotAllowed917			);918			collection.check_allowlist(sender)?;919920			for item in data.iter() {921				collection.check_allowlist(&item.owner)?;922			}923		}924925		for data in data.iter() {926			<PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;927		}928929		let first_token = <TokensMinted<T>>::get(collection.id);930		let tokens_minted = first_token931			.checked_add(data.len() as u32)932			.ok_or(ArithmeticError::Overflow)?;933		ensure!(934			tokens_minted <= collection.limits.token_limit(),935			<CommonError<T>>::CollectionTokenLimitExceeded936		);937938		let mut balances = BTreeMap::new();939		for data in &data {940			let balance = balances941				.entry(&data.owner)942				.or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));943			*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;944945			ensure!(946				*balance <= collection.limits.account_token_ownership_limit(),947				<CommonError<T>>::AccountTokenLimitExceeded,948			);949		}950951		for (i, data) in data.iter().enumerate() {952			let token = TokenId(first_token + i as u32 + 1);953954			<PalletStructure<T>>::check_nesting(955				sender.clone(),956				&data.owner,957				collection.id,958				token,959				nesting_budget,960			)?;961		}962963		// =========964965		with_transaction(|| {966			for (i, data) in data.iter().enumerate() {967				let token = first_token + i as u32 + 1;968969				<TokenData<T>>::insert(970					(collection.id, token),971					ItemData {972						// const_data: data.const_data.clone(),973						owner: data.owner.clone(),974					},975				);976977				<PalletStructure<T>>::nest_if_sent_to_token_unchecked(978					&data.owner,979					collection.id,980					TokenId(token),981				);982983				if let Err(e) = Self::set_token_properties(984					collection,985					sender,986					TokenId(token),987					data.properties.clone().into_iter(),988					true,989					nesting_budget,990				) {991					return TransactionOutcome::Rollback(Err(e));992				}993			}994			TransactionOutcome::Commit(Ok(()))995		})?;996997		<TokensMinted<T>>::insert(collection.id, tokens_minted);998		for (account, balance) in balances {999			<AccountBalance<T>>::insert((collection.id, account), balance);1000		}1001		for (i, data) in data.into_iter().enumerate() {1002			let token = first_token + i as u32 + 1;1003			<Owned<T>>::insert((collection.id, &data.owner, token), true);10041005			<PalletEvm<T>>::deposit_log(1006				ERC721Events::Transfer {1007					from: H160::default(),1008					to: *data.owner.as_eth(),1009					token_id: token.into(),1010				}1011				.to_log(collection_id_to_address(collection.id)),1012			);1013			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1014				collection.id,1015				TokenId(token),1016				data.owner.clone(),1017				1,1018			));1019		}1020		Ok(())1021	}10221023	pub fn set_allowance_unchecked(1024		collection: &NonfungibleHandle<T>,1025		sender: &T::CrossAccountId,1026		token: TokenId,1027		spender: Option<&T::CrossAccountId>,1028		assume_implicit_eth: bool,1029	) {1030		if let Some(spender) = spender {1031			let old_spender = <Allowance<T>>::get((collection.id, token));1032			<Allowance<T>>::insert((collection.id, token), spender);1033			// In ERC721 there is only one possible approved user of token, so we set1034			// approved user to spender1035			<PalletEvm<T>>::deposit_log(1036				ERC721Events::Approval {1037					owner: *sender.as_eth(),1038					approved: *spender.as_eth(),1039					token_id: token.into(),1040				}1041				.to_log(collection_id_to_address(collection.id)),1042			);1043			// In Unique chain, any token can have any amount of approved users, so we need to1044			// set allowance of old owner to 0, and allowance of new owner to 11045			if old_spender.as_ref() != Some(spender) {1046				if let Some(old_owner) = old_spender {1047					<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1048						collection.id,1049						token,1050						sender.clone(),1051						old_owner,1052						0,1053					));1054				}1055				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1056					collection.id,1057					token,1058					sender.clone(),1059					spender.clone(),1060					1,1061				));1062			}1063		} else {1064			let old_spender = <Allowance<T>>::take((collection.id, token));1065			if !assume_implicit_eth {1066				// In ERC721 there is only one possible approved user of token, so we set1067				// approved user to zero address1068				<PalletEvm<T>>::deposit_log(1069					ERC721Events::Approval {1070						owner: *sender.as_eth(),1071						approved: H160::default(),1072						token_id: token.into(),1073					}1074					.to_log(collection_id_to_address(collection.id)),1075				);1076			}1077			// In Unique chain, any token can have any amount of approved users, so we need to1078			// set allowance of old owner to 01079			if let Some(old_spender) = old_spender {1080				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1081					collection.id,1082					token,1083					sender.clone(),1084					old_spender,1085					0,1086				));1087			}1088		}1089	}10901091	pub fn get_allowance(1092		collection: &NonfungibleHandle<T>,1093		token_id: TokenId,1094	) -> Result<Option<T::CrossAccountId>, DispatchError> {1095		ensure!(1096			<TokenData<T>>::get((collection.id, token_id)).is_some(),1097			<CommonError<T>>::TokenNotFound1098		);1099		Ok(<Allowance<T>>::get((collection.id, token_id)))1100	}11011102	/// Set allowance for the spender to `transfer` or `burn` sender's token.1103	///1104	/// - `token`: Token the spender is allowed to `transfer` or `burn`.1105	pub fn set_allowance(1106		collection: &NonfungibleHandle<T>,1107		sender: &T::CrossAccountId,1108		token: TokenId,1109		spender: Option<&T::CrossAccountId>,1110	) -> DispatchResult {1111		if collection.permissions.access() == AccessMode::AllowList {1112			collection.check_allowlist(sender)?;1113			if let Some(spender) = spender {1114				collection.check_allowlist(spender)?;1115			}1116		}11171118		if let Some(spender) = spender {1119			<PalletCommon<T>>::ensure_correct_receiver(spender)?;1120		}11211122		let token_data =1123			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1124		if &token_data.owner != sender {1125			ensure!(1126				collection.ignores_owned_amount(sender),1127				<CommonError<T>>::CantApproveMoreThanOwned1128			);1129		}11301131		// =========11321133		Self::set_allowance_unchecked(collection, sender, token, spender, false);1134		Ok(())1135	}11361137	/// Set allowance for the spender to `transfer` or `burn` sender's token from eth mirror.1138	///1139	/// - `from`: Address of sender's eth mirror.1140	/// - `to`: Adress of spender.1141	/// - `token`: Token the spender is allowed to `transfer` or `burn`.1142	pub fn set_allowance_from(1143		collection: &NonfungibleHandle<T>,1144		sender: &T::CrossAccountId,1145		from: &T::CrossAccountId,1146		token: TokenId,1147		to: Option<&T::CrossAccountId>,1148	) -> DispatchResult {1149		if collection.permissions.access() == AccessMode::AllowList {1150			collection.check_allowlist(sender)?;1151			collection.check_allowlist(from)?;1152			if let Some(to) = to {1153				collection.check_allowlist(to)?;1154			}1155		}11561157		if let Some(to) = to {1158			<PalletCommon<T>>::ensure_correct_receiver(to)?;1159		}11601161		ensure!(1162			sender.conv_eq(from),1163			<CommonError<T>>::AddressIsNotEthMirror1164		);11651166		let token_data =1167			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1168		if token_data.owner != *from {1169			ensure!(1170				collection.limits.owner_can_transfer()1171					&& (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),1172				<CommonError<T>>::CantApproveMoreThanOwned1173			);1174		}11751176		// =========11771178		Self::set_allowance_unchecked(collection, from, token, to, false);1179		Ok(())1180	}11811182	/// Checks allowance for the spender to use the token.1183	fn check_allowed(1184		collection: &NonfungibleHandle<T>,1185		spender: &T::CrossAccountId,1186		from: &T::CrossAccountId,1187		token: TokenId,1188		nesting_budget: &dyn Budget,1189	) -> DispatchResult {1190		if spender.conv_eq(from) {1191			return Ok(());1192		}1193		if collection.permissions.access() == AccessMode::AllowList {1194			// `from`, `to` checked in [`transfer`]1195			collection.check_allowlist(spender)?;1196		}11971198		if collection.ignores_token_restrictions(spender) {1199			return Ok(());1200		}12011202		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1203			ensure!(1204				<PalletStructure<T>>::check_indirectly_owned(1205					spender.clone(),1206					source.0,1207					source.1,1208					None,1209					nesting_budget1210				)?,1211				<CommonError<T>>::ApprovedValueTooLow,1212			);1213			return Ok(());1214		}1215		if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {1216			return Ok(());1217		}1218		if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1219			return Ok(());1220		}12211222		Err(<CommonError<T>>::ApprovedValueTooLow.into())1223	}12241225	/// Transfer NFT token from one account to another.1226	///1227	/// Same as the [`transfer`] but spender doesn't needs to be the owner of the token.1228	/// The owner should set allowance for the spender to transfer token.1229	///1230	/// [`transfer`]: struct.Pallet.html#method.transfer1231	pub fn transfer_from(1232		collection: &NonfungibleHandle<T>,1233		spender: &T::CrossAccountId,1234		from: &T::CrossAccountId,1235		to: &T::CrossAccountId,1236		token: TokenId,1237		nesting_budget: &dyn Budget,1238	) -> DispatchResultWithPostInfo {1239		Self::check_allowed(collection, spender, from, token, nesting_budget)?;12401241		// =========12421243		// Allowance is reset in [`transfer`]1244		let mut result = Self::transfer(collection, from, to, token, nesting_budget);1245		add_weight_to_post_info(&mut result, <SelfWeightOf<T>>::check_allowed_raw());1246		result1247	}12481249	/// Burn NFT token for `from` account.1250	///1251	/// Same as the [`burn`] but spender doesn't need to be an owner of the token. The owner should1252	/// set allowance for the spender to burn token.1253	///1254	/// [`burn`]: struct.Pallet.html#method.burn1255	pub fn burn_from(1256		collection: &NonfungibleHandle<T>,1257		spender: &T::CrossAccountId,1258		from: &T::CrossAccountId,1259		token: TokenId,1260		nesting_budget: &dyn Budget,1261	) -> DispatchResult {1262		Self::check_allowed(collection, spender, from, token, nesting_budget)?;12631264		// =========12651266		Self::burn(collection, from, token)1267	}12681269	/// Check that `from` token could be nested in `under` token.1270	///1271	pub fn check_nesting(1272		handle: &NonfungibleHandle<T>,1273		sender: T::CrossAccountId,1274		from: (CollectionId, TokenId),1275		under: TokenId,1276		nesting_budget: &dyn Budget,1277	) -> DispatchResult {1278		let nesting = handle.permissions.nesting();12791280		#[cfg(not(feature = "runtime-benchmarks"))]1281		let permissive = false;1282		#[cfg(feature = "runtime-benchmarks")]1283		let permissive = nesting.permissive;12841285		if permissive {1286			ensure!(1287				<TokenData<T>>::contains_key((handle.id, under)),1288				<CommonError<T>>::TokenNotFound1289			);1290		} else if nesting.token_owner1291			&& <PalletStructure<T>>::check_indirectly_owned(1292				sender.clone(),1293				handle.id,1294				under,1295				Some(from),1296				nesting_budget,1297			)? {1298			// Pass, token existence and ouroboros checks are done in `check_indirectly_owned`1299		} else if nesting.collection_admin && handle.is_owner_or_admin(&sender) {1300			// token existence and ouroboros checks are done in `get_checked_topmost_owner`1301			let _ = <PalletStructure<T>>::get_checked_topmost_owner(1302				handle.id,1303				under,1304				Some(from),1305				nesting_budget,1306			)?1307			.ok_or(<CommonError<T>>::TokenNotFound)?;1308		} else {1309			fail!(<CommonError<T>>::UserIsNotAllowedToNest);1310		}13111312		if let Some(whitelist) = &nesting.restricted {1313			ensure!(1314				whitelist.contains(&from.0),1315				<CommonError<T>>::SourceCollectionIsNotAllowedToNest1316			);1317		}1318		Ok(())1319	}13201321	fn nest(under: (CollectionId, TokenId), to_nest: (CollectionId, TokenId)) {1322		<TokenChildren<T>>::insert((under.0, under.1, (to_nest.0, to_nest.1)), true);1323	}13241325	fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {1326		<TokenChildren<T>>::remove((under.0, under.1, to_unnest));1327	}13281329	fn collection_has_tokens(collection_id: CollectionId) -> bool {1330		<TokenData<T>>::iter_prefix((collection_id,))1331			.next()1332			.is_some()1333	}13341335	fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {1336		<TokenChildren<T>>::iter_prefix((collection_id, token_id))1337			.next()1338			.is_some()1339	}13401341	pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {1342		<TokenChildren<T>>::iter_prefix((collection_id, token_id))1343			.map(|((child_collection_id, child_id), _)| TokenChild {1344				collection: child_collection_id,1345				token: child_id,1346			})1347			.collect()1348	}13491350	/// Mint single NFT token.1351	///1352	/// Delegated to [`create_multiple_items`]1353	///1354	/// [`create_multiple_items`]: struct.Pallet.html#method.create_multiple_items1355	pub fn create_item(1356		collection: &NonfungibleHandle<T>,1357		sender: &T::CrossAccountId,1358		data: CreateItemData<T>,1359		nesting_budget: &dyn Budget,1360	) -> DispatchResult {1361		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1362	}13631364	/// Sets or unsets the approval of a given operator.1365	///1366	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1367	/// - `owner`: Token owner1368	/// - `operator`: Operator1369	/// - `approve`: Should operator status be granted or revoked?1370	pub fn set_allowance_for_all(1371		collection: &NonfungibleHandle<T>,1372		owner: &T::CrossAccountId,1373		operator: &T::CrossAccountId,1374		approve: bool,1375	) -> DispatchResult {1376		<PalletCommon<T>>::set_allowance_for_all(1377			collection,1378			owner,1379			operator,1380			approve,1381			|| <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve),1382			ERC721Events::ApprovalForAll {1383				owner: *owner.as_eth(),1384				operator: *operator.as_eth(),1385				approved: approve,1386			}1387			.to_log(collection_id_to_address(collection.id)),1388		)1389	}13901391	/// Tells whether the given `owner` approves the `operator`.1392	pub fn allowance_for_all(1393		collection: &NonfungibleHandle<T>,1394		owner: &T::CrossAccountId,1395		operator: &T::CrossAccountId,1396	) -> bool {1397		<CollectionAllowance<T>>::get((collection.id, owner, operator))1398	}13991400	pub fn repair_item(collection: &NonfungibleHandle<T>, token: TokenId) -> DispatchResult {1401		<TokenProperties<T>>::mutate((collection.id, token), |properties| {1402			properties.recompute_consumed_space();1403		});14041405		Ok(())1406	}1407}
after · pallets/nonfungible/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # 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,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	#[pallet::genesis_config]287	pub struct GenesisConfig<T>(PhantomData<T>);288289	#[cfg(feature = "std")]290	impl<T: Config> Default for GenesisConfig<T> {291		fn default() -> Self {292			Self(Default::default())293		}294	}295296	#[pallet::genesis_build]297	impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {298		fn build(&self) {299			StorageVersion::new(1).put::<Pallet<T>>();300		}301	}302}303304pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);305impl<T: Config> NonfungibleHandle<T> {306	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {307		Self(inner)308	}309	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {310		self.0311	}312	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {313		&mut self.0314	}315}316317impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {318	fn recorder(&self) -> &SubstrateRecorder<T> {319		self.0.recorder()320	}321	fn into_recorder(self) -> SubstrateRecorder<T> {322		self.0.into_recorder()323	}324}325impl<T: Config> Deref for NonfungibleHandle<T> {326	type Target = pallet_common::CollectionHandle<T>;327328	fn deref(&self) -> &Self::Target {329		&self.0330	}331}332333impl<T: Config> Pallet<T> {334	/// Get number of NFT tokens in collection.335	pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {336		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)337	}338339	/// Check that NFT token exists.340	///341	/// - `token`: Token ID.342	pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {343		<TokenData<T>>::contains_key((collection.id, token))344	}345346	/// Set the token property with the scope.347	///348	/// - `property`: Contains key-value pair.349	pub fn set_scoped_token_property(350		collection_id: CollectionId,351		token_id: TokenId,352		scope: PropertyScope,353		property: Property,354	) -> DispatchResult {355		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {356			properties.try_scoped_set(scope, property.key, property.value)357		})358		.map_err(<CommonError<T>>::from)?;359360		Ok(())361	}362363	/// Batch operation to set multiple properties with the same scope.364	pub fn set_scoped_token_properties(365		collection_id: CollectionId,366		token_id: TokenId,367		scope: PropertyScope,368		properties: impl Iterator<Item = Property>,369	) -> DispatchResult {370		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {371			stored_properties.try_scoped_set_from_iter(scope, properties)372		})373		.map_err(<CommonError<T>>::from)?;374375		Ok(())376	}377378	/// Add or edit auxiliary data for the property.379	///380	/// - `f`: function that adds or edits auxiliary data.381	pub fn try_mutate_token_aux_property<R, E>(382		collection_id: CollectionId,383		token_id: TokenId,384		scope: PropertyScope,385		key: PropertyKey,386		f: impl FnOnce(&mut Option<AuxPropertyValue>) -> Result<R, E>,387	) -> Result<R, E> {388		<TokenAuxProperties<T>>::try_mutate((collection_id, token_id, scope, key), f)389	}390391	/// Remove auxiliary data for the property.392	pub fn remove_token_aux_property(393		collection_id: CollectionId,394		token_id: TokenId,395		scope: PropertyScope,396		key: PropertyKey,397	) {398		<TokenAuxProperties<T>>::remove((collection_id, token_id, scope, key));399	}400401	/// Get all auxiliary data in a given scope.402	///403	/// Returns iterator over Property Key - Data pairs.404	pub fn iterate_token_aux_properties(405		collection_id: CollectionId,406		token_id: TokenId,407		scope: PropertyScope,408	) -> impl Iterator<Item = (PropertyKey, AuxPropertyValue)> {409		<TokenAuxProperties<T>>::iter_prefix((collection_id, token_id, scope))410	}411412	/// Get ID of the last minted token413	pub fn current_token_id(collection_id: CollectionId) -> TokenId {414		TokenId(<TokensMinted<T>>::get(collection_id))415	}416}417418// unchecked calls skips any permission checks419impl<T: Config> Pallet<T> {420	/// Create NFT collection421	///422	/// `init_collection` will take non-refundable deposit for collection creation.423	///424	/// - `data`: Contains settings for collection limits and permissions.425	pub fn init_collection(426		owner: T::CrossAccountId,427		payer: T::CrossAccountId,428		data: CreateCollectionData<T::AccountId>,429		flags: CollectionFlags,430	) -> Result<CollectionId, DispatchError> {431		<PalletCommon<T>>::init_collection(owner, payer, data, flags)432	}433434	/// Destroy NFT collection435	///436	/// `destroy_collection` will throw error if collection contains any tokens.437	/// Only owner can destroy collection.438	pub fn destroy_collection(439		collection: NonfungibleHandle<T>,440		sender: &T::CrossAccountId,441	) -> DispatchResult {442		let id = collection.id;443444		if Self::collection_has_tokens(id) {445			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());446		}447448		// =========449450		PalletCommon::destroy_collection(collection.0, sender)?;451452		let _ = <TokenData<T>>::clear_prefix((id,), u32::MAX, None);453		let _ = <TokenChildren<T>>::clear_prefix((id,), u32::MAX, None);454		let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);455		<TokensMinted<T>>::remove(id);456		<TokensBurnt<T>>::remove(id);457		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);458		let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);459		let _ = <CollectionAllowance<T>>::clear_prefix((id,), u32::MAX, None);460		Ok(())461	}462463	/// Burn NFT token464	///465	/// `burn` removes `token` from the `collection`, from it's owner and from the parent token466	/// if the token is nested.467	/// Only the owner can `burn` the token. The `token` shouldn't have any nested tokens.468	/// Also removes all corresponding properties and auxiliary properties.469	///470	/// - `token`: Token that should be burned471	/// - `collection`: Collection that contains the token472	pub fn burn(473		collection: &NonfungibleHandle<T>,474		sender: &T::CrossAccountId,475		token: TokenId,476	) -> DispatchResult {477		let token_data =478			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;479		ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);480481		if collection.permissions.access() == AccessMode::AllowList {482			collection.check_allowlist(sender)?;483		}484485		if Self::token_has_children(collection.id, token) {486			return Err(<Error<T>>::CantBurnNftWithChildren.into());487		}488489		let burnt = <TokensBurnt<T>>::get(collection.id)490			.checked_add(1)491			.ok_or(ArithmeticError::Overflow)?;492493		let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))494			.checked_sub(1)495			.ok_or(ArithmeticError::Overflow)?;496497		// =========498499		if balance == 0 {500			<AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));501		} else {502			<AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);503		}504505		<PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);506507		<Owned<T>>::remove((collection.id, &token_data.owner, token));508		<TokensBurnt<T>>::insert(collection.id, burnt);509		<TokenData<T>>::remove((collection.id, token));510		<TokenProperties<T>>::remove((collection.id, token));511		let _ = <TokenAuxProperties<T>>::clear_prefix((collection.id, token), u32::MAX, None);512		let old_spender = <Allowance<T>>::take((collection.id, token));513514		if let Some(old_spender) = old_spender {515			<PalletCommon<T>>::deposit_event(CommonEvent::Approved(516				collection.id,517				token,518				token_data.owner.clone(),519				old_spender,520				0,521			));522		}523524		<PalletEvm<T>>::deposit_log(525			ERC721Events::Transfer {526				from: *token_data.owner.as_eth(),527				to: H160::default(),528				token_id: token.into(),529			}530			.to_log(collection_id_to_address(collection.id)),531		);532		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(533			collection.id,534			token,535			token_data.owner,536			1,537		));538		Ok(())539	}540541	/// Same as [`burn`] but burns all the tokens that are nested in the token first542	///543	/// - `self_budget`: Limit for searching children in depth.544	/// - `breadth_budget`: Limit of breadth of searching children.545	///546	/// [`burn`]: struct.Pallet.html#method.burn547	#[transactional]548	pub fn burn_recursively(549		collection: &NonfungibleHandle<T>,550		sender: &T::CrossAccountId,551		token: TokenId,552		self_budget: &dyn Budget,553		breadth_budget: &dyn Budget,554	) -> DispatchResultWithPostInfo {555		ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);556557		let current_token_account =558			T::CrossTokenAddressMapping::token_to_address(collection.id, token);559560		let mut weight = Weight::zero();561562		// This method is transactional, if user in fact doesn't have permissions to remove token -563		// tokens removed here will be restored after rejected transaction564		for ((collection, token), _) in <TokenChildren<T>>::iter_prefix((collection.id, token)) {565			ensure!(breadth_budget.consume(), <StructureError<T>>::BreadthLimit,);566			let PostDispatchInfo { actual_weight, .. } =567				<PalletStructure<T>>::burn_item_recursively(568					current_token_account.clone(),569					collection,570					token,571					self_budget,572					breadth_budget,573				)?;574			if let Some(actual_weight) = actual_weight {575				weight = weight.saturating_add(actual_weight);576			}577		}578579		Self::burn(collection, sender, token)?;580		DispatchResultWithPostInfo::Ok(PostDispatchInfo {581			actual_weight: Some(weight + <SelfWeightOf<T>>::burn_item()),582			pays_fee: Pays::Yes,583		})584	}585586	/// A batch operation to add, edit or remove properties for a token.587	///588	/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.589	/// - `is_token_create`: Indicates that method is called during token initialization.590	///   Allows to bypass ownership check.591	///592	/// All affected properties should have `mutable` permission593	/// to be **deleted** or to be **set more than once**,594	/// and the sender should have permission to edit those properties.595	///596	/// This function fires an event for each property change.597	/// In case of an error, all the changes (including the events) will be reverted598	/// since the function is transactional.599	#[transactional]600	fn modify_token_properties(601		collection: &NonfungibleHandle<T>,602		sender: &T::CrossAccountId,603		token_id: TokenId,604		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,605		is_token_create: bool,606		nesting_budget: &dyn Budget,607	) -> DispatchResult {608		let is_token_owner = || {609			let is_owned = <PalletStructure<T>>::check_indirectly_owned(610				sender.clone(),611				collection.id,612				token_id,613				None,614				nesting_budget,615			)?;616617			Ok(is_owned)618		};619620		let stored_properties = <TokenProperties<T>>::get((collection.id, token_id));621622		<PalletCommon<T>>::modify_token_properties(623			collection,624			sender,625			token_id,626			properties_updates,627			is_token_create,628			stored_properties,629			is_token_owner,630			|properties| <TokenProperties<T>>::set((collection.id, token_id), properties),631			erc::ERC721TokenEvent::TokenChanged {632				token_id: token_id.into(),633			}634			.to_log(T::ContractAddress::get()),635		)636	}637638	/// Batch operation to add or edit properties for the token639	///640	/// Same as [`modify_token_properties`] but doesn't allow to remove properties641	///642	/// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties643	pub fn set_token_properties(644		collection: &NonfungibleHandle<T>,645		sender: &T::CrossAccountId,646		token_id: TokenId,647		properties: impl Iterator<Item = Property>,648		is_token_create: bool,649		nesting_budget: &dyn Budget,650	) -> DispatchResult {651		Self::modify_token_properties(652			collection,653			sender,654			token_id,655			properties.map(|p| (p.key, Some(p.value))),656			is_token_create,657			nesting_budget,658		)659	}660661	/// Add or edit single property for the token662	///663	/// Calls [`set_token_properties`] internally664	///665	/// [`set_token_properties`]: struct.Pallet.html#method.set_token_properties666	pub fn set_token_property(667		collection: &NonfungibleHandle<T>,668		sender: &T::CrossAccountId,669		token_id: TokenId,670		property: Property,671		nesting_budget: &dyn Budget,672	) -> DispatchResult {673		let is_token_create = false;674675		Self::set_token_properties(676			collection,677			sender,678			token_id,679			[property].into_iter(),680			is_token_create,681			nesting_budget,682		)683	}684685	/// Batch operation to remove properties from the token686	///687	/// Same as [`modify_token_properties`] but doesn't allow to add or edit properties688	///689	/// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties690	pub fn delete_token_properties(691		collection: &NonfungibleHandle<T>,692		sender: &T::CrossAccountId,693		token_id: TokenId,694		property_keys: impl Iterator<Item = PropertyKey>,695		nesting_budget: &dyn Budget,696	) -> DispatchResult {697		let is_token_create = false;698699		Self::modify_token_properties(700			collection,701			sender,702			token_id,703			property_keys.into_iter().map(|key| (key, None)),704			is_token_create,705			nesting_budget,706		)707	}708709	/// Remove single property from the token710	///711	/// Calls [`delete_token_properties`] internally712	///713	/// [`delete_token_properties`]: struct.Pallet.html#method.delete_token_properties714	pub fn delete_token_property(715		collection: &NonfungibleHandle<T>,716		sender: &T::CrossAccountId,717		token_id: TokenId,718		property_key: PropertyKey,719		nesting_budget: &dyn Budget,720	) -> DispatchResult {721		Self::delete_token_properties(722			collection,723			sender,724			token_id,725			[property_key].into_iter(),726			nesting_budget,727		)728	}729730	/// Add or edit properties for the collection731	pub fn set_collection_properties(732		collection: &NonfungibleHandle<T>,733		sender: &T::CrossAccountId,734		properties: Vec<Property>,735	) -> DispatchResult {736		<PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())737	}738739	/// Remove properties from the collection740	pub fn delete_collection_properties(741		collection: &CollectionHandle<T>,742		sender: &T::CrossAccountId,743		property_keys: Vec<PropertyKey>,744	) -> DispatchResult {745		<PalletCommon<T>>::delete_collection_properties(746			collection,747			sender,748			property_keys.into_iter(),749		)750	}751752	/// Set property permissions for the token.753	///754	/// Sender should be the owner or admin of token's collection.755	pub fn set_token_property_permissions(756		collection: &CollectionHandle<T>,757		sender: &T::CrossAccountId,758		property_permissions: Vec<PropertyKeyPermission>,759	) -> DispatchResult {760		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)761	}762763	/// Set property permissions for the token with scope.764	///765	/// Sender should be the owner or admin of token's collection.766	pub fn set_scoped_token_property_permissions(767		collection: &CollectionHandle<T>,768		sender: &T::CrossAccountId,769		scope: PropertyScope,770		property_permissions: Vec<PropertyKeyPermission>,771	) -> DispatchResult {772		<PalletCommon<T>>::set_scoped_token_property_permissions(773			collection,774			sender,775			scope,776			property_permissions,777		)778	}779780	pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {781		<PalletCommon<T>>::property_permissions(collection_id)782	}783784	pub fn check_token_immediate_ownership(785		collection: &NonfungibleHandle<T>,786		token: TokenId,787		possible_owner: &T::CrossAccountId,788	) -> DispatchResult {789		let token_data =790			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;791		ensure!(792			&token_data.owner == possible_owner,793			<CommonError<T>>::NoPermission794		);795		Ok(())796	}797798	/// Transfer NFT token from one account to another.799	///800	/// `from` account stops being the owner and `to` account becomes the owner of the token.801	/// If `to` is token than `to` becomes owner of the token and the token become nested.802	/// Unnests token from previous parent if it was nested before.803	/// Removes allowance for the token if there was any.804	/// Throws if transfers aren't allowed for collection or if receiver reached token ownership limit.805	///806	/// - `nesting_budget`: Limit for token nesting depth807	pub fn transfer(808		collection: &NonfungibleHandle<T>,809		from: &T::CrossAccountId,810		to: &T::CrossAccountId,811		token: TokenId,812		nesting_budget: &dyn Budget,813	) -> DispatchResultWithPostInfo {814		ensure!(815			collection.limits.transfers_enabled(),816			<CommonError<T>>::TransferNotAllowed817		);818819		let mut actual_weight = <SelfWeightOf<T>>::transfer_raw();820		let token_data =821			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;822		ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);823824		if collection.permissions.access() == AccessMode::AllowList {825			collection.check_allowlist(from)?;826			collection.check_allowlist(to)?;827			actual_weight += <PalletCommonWeightOf<T>>::check_accesslist() * 2;828		}829		<PalletCommon<T>>::ensure_correct_receiver(to)?;830831		let balance_from = <AccountBalance<T>>::get((collection.id, from))832			.checked_sub(1)833			.ok_or(<CommonError<T>>::TokenValueTooLow)?;834		let balance_to = if from != to {835			let balance_to = <AccountBalance<T>>::get((collection.id, to))836				.checked_add(1)837				.ok_or(ArithmeticError::Overflow)?;838839			ensure!(840				balance_to < collection.limits.account_token_ownership_limit(),841				<CommonError<T>>::AccountTokenLimitExceeded,842			);843844			Some(balance_to)845		} else {846			None847		};848849		<PalletStructure<T>>::nest_if_sent_to_token(850			from.clone(),851			to,852			collection.id,853			token,854			nesting_budget,855		)?;856857		// =========858859		<PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);860861		<TokenData<T>>::insert(862			(collection.id, token),863			ItemData {864				owner: to.clone(),865				..token_data866			},867		);868869		if let Some(balance_to) = balance_to {870			// from != to871			if balance_from == 0 {872				<AccountBalance<T>>::remove((collection.id, from));873			} else {874				<AccountBalance<T>>::insert((collection.id, from), balance_from);875			}876			<AccountBalance<T>>::insert((collection.id, to), balance_to);877			<Owned<T>>::remove((collection.id, from, token));878			<Owned<T>>::insert((collection.id, to, token), true);879		}880		Self::set_allowance_unchecked(collection, from, token, None, true);881882		<PalletEvm<T>>::deposit_log(883			ERC721Events::Transfer {884				from: *from.as_eth(),885				to: *to.as_eth(),886				token_id: token.into(),887			}888			.to_log(collection_id_to_address(collection.id)),889		);890		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(891			collection.id,892			token,893			from.clone(),894			to.clone(),895			1,896		));897898		Ok(PostDispatchInfo {899			actual_weight: Some(actual_weight),900			pays_fee: Pays::Yes,901		})902	}903904	/// Batch operation to mint multiple NFT tokens.905	///906	/// The sender should be the owner/admin of the collection or collection should be configured907	/// to allow public minting.908	/// Throws if amount of tokens reached it's limit for the collection or if caller reached909	/// token ownership limit.910	///911	/// - `data`: Contains list of token properties and users who will become the owners of the912	///   corresponging tokens.913	/// - `nesting_budget`: Limit for token nesting depth914	pub fn create_multiple_items(915		collection: &NonfungibleHandle<T>,916		sender: &T::CrossAccountId,917		data: Vec<CreateItemData<T>>,918		nesting_budget: &dyn Budget,919	) -> DispatchResult {920		if !collection.is_owner_or_admin(sender) {921			ensure!(922				collection.permissions.mint_mode(),923				<CommonError<T>>::PublicMintingNotAllowed924			);925			collection.check_allowlist(sender)?;926927			for item in data.iter() {928				collection.check_allowlist(&item.owner)?;929			}930		}931932		for data in data.iter() {933			<PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;934		}935936		let first_token = <TokensMinted<T>>::get(collection.id);937		let tokens_minted = first_token938			.checked_add(data.len() as u32)939			.ok_or(ArithmeticError::Overflow)?;940		ensure!(941			tokens_minted <= collection.limits.token_limit(),942			<CommonError<T>>::CollectionTokenLimitExceeded943		);944945		let mut balances = BTreeMap::new();946		for data in &data {947			let balance = balances948				.entry(&data.owner)949				.or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));950			*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;951952			ensure!(953				*balance <= collection.limits.account_token_ownership_limit(),954				<CommonError<T>>::AccountTokenLimitExceeded,955			);956		}957958		for (i, data) in data.iter().enumerate() {959			let token = TokenId(first_token + i as u32 + 1);960961			<PalletStructure<T>>::check_nesting(962				sender.clone(),963				&data.owner,964				collection.id,965				token,966				nesting_budget,967			)?;968		}969970		// =========971972		with_transaction(|| {973			for (i, data) in data.iter().enumerate() {974				let token = first_token + i as u32 + 1;975976				<TokenData<T>>::insert(977					(collection.id, token),978					ItemData {979						// const_data: data.const_data.clone(),980						owner: data.owner.clone(),981					},982				);983984				<PalletStructure<T>>::nest_if_sent_to_token_unchecked(985					&data.owner,986					collection.id,987					TokenId(token),988				);989990				if let Err(e) = Self::set_token_properties(991					collection,992					sender,993					TokenId(token),994					data.properties.clone().into_iter(),995					true,996					nesting_budget,997				) {998					return TransactionOutcome::Rollback(Err(e));999				}1000			}1001			TransactionOutcome::Commit(Ok(()))1002		})?;10031004		<TokensMinted<T>>::insert(collection.id, tokens_minted);1005		for (account, balance) in balances {1006			<AccountBalance<T>>::insert((collection.id, account), balance);1007		}1008		for (i, data) in data.into_iter().enumerate() {1009			let token = first_token + i as u32 + 1;1010			<Owned<T>>::insert((collection.id, &data.owner, token), true);10111012			<PalletEvm<T>>::deposit_log(1013				ERC721Events::Transfer {1014					from: H160::default(),1015					to: *data.owner.as_eth(),1016					token_id: token.into(),1017				}1018				.to_log(collection_id_to_address(collection.id)),1019			);1020			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1021				collection.id,1022				TokenId(token),1023				data.owner.clone(),1024				1,1025			));1026		}1027		Ok(())1028	}10291030	pub fn set_allowance_unchecked(1031		collection: &NonfungibleHandle<T>,1032		sender: &T::CrossAccountId,1033		token: TokenId,1034		spender: Option<&T::CrossAccountId>,1035		assume_implicit_eth: bool,1036	) {1037		if let Some(spender) = spender {1038			let old_spender = <Allowance<T>>::get((collection.id, token));1039			<Allowance<T>>::insert((collection.id, token), spender);1040			// In ERC721 there is only one possible approved user of token, so we set1041			// approved user to spender1042			<PalletEvm<T>>::deposit_log(1043				ERC721Events::Approval {1044					owner: *sender.as_eth(),1045					approved: *spender.as_eth(),1046					token_id: token.into(),1047				}1048				.to_log(collection_id_to_address(collection.id)),1049			);1050			// In Unique chain, any token can have any amount of approved users, so we need to1051			// set allowance of old owner to 0, and allowance of new owner to 11052			if old_spender.as_ref() != Some(spender) {1053				if let Some(old_owner) = old_spender {1054					<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1055						collection.id,1056						token,1057						sender.clone(),1058						old_owner,1059						0,1060					));1061				}1062				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1063					collection.id,1064					token,1065					sender.clone(),1066					spender.clone(),1067					1,1068				));1069			}1070		} else {1071			let old_spender = <Allowance<T>>::take((collection.id, token));1072			if !assume_implicit_eth {1073				// In ERC721 there is only one possible approved user of token, so we set1074				// approved user to zero address1075				<PalletEvm<T>>::deposit_log(1076					ERC721Events::Approval {1077						owner: *sender.as_eth(),1078						approved: H160::default(),1079						token_id: token.into(),1080					}1081					.to_log(collection_id_to_address(collection.id)),1082				);1083			}1084			// In Unique chain, any token can have any amount of approved users, so we need to1085			// set allowance of old owner to 01086			if let Some(old_spender) = old_spender {1087				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1088					collection.id,1089					token,1090					sender.clone(),1091					old_spender,1092					0,1093				));1094			}1095		}1096	}10971098	pub fn get_allowance(1099		collection: &NonfungibleHandle<T>,1100		token_id: TokenId,1101	) -> Result<Option<T::CrossAccountId>, DispatchError> {1102		ensure!(1103			<TokenData<T>>::get((collection.id, token_id)).is_some(),1104			<CommonError<T>>::TokenNotFound1105		);1106		Ok(<Allowance<T>>::get((collection.id, token_id)))1107	}11081109	/// Set allowance for the spender to `transfer` or `burn` sender's token.1110	///1111	/// - `token`: Token the spender is allowed to `transfer` or `burn`.1112	pub fn set_allowance(1113		collection: &NonfungibleHandle<T>,1114		sender: &T::CrossAccountId,1115		token: TokenId,1116		spender: Option<&T::CrossAccountId>,1117	) -> DispatchResult {1118		if collection.permissions.access() == AccessMode::AllowList {1119			collection.check_allowlist(sender)?;1120			if let Some(spender) = spender {1121				collection.check_allowlist(spender)?;1122			}1123		}11241125		if let Some(spender) = spender {1126			<PalletCommon<T>>::ensure_correct_receiver(spender)?;1127		}11281129		let token_data =1130			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1131		if &token_data.owner != sender {1132			ensure!(1133				collection.ignores_owned_amount(sender),1134				<CommonError<T>>::CantApproveMoreThanOwned1135			);1136		}11371138		// =========11391140		Self::set_allowance_unchecked(collection, sender, token, spender, false);1141		Ok(())1142	}11431144	/// Set allowance for the spender to `transfer` or `burn` sender's token from eth mirror.1145	///1146	/// - `from`: Address of sender's eth mirror.1147	/// - `to`: Adress of spender.1148	/// - `token`: Token the spender is allowed to `transfer` or `burn`.1149	pub fn set_allowance_from(1150		collection: &NonfungibleHandle<T>,1151		sender: &T::CrossAccountId,1152		from: &T::CrossAccountId,1153		token: TokenId,1154		to: Option<&T::CrossAccountId>,1155	) -> DispatchResult {1156		if collection.permissions.access() == AccessMode::AllowList {1157			collection.check_allowlist(sender)?;1158			collection.check_allowlist(from)?;1159			if let Some(to) = to {1160				collection.check_allowlist(to)?;1161			}1162		}11631164		if let Some(to) = to {1165			<PalletCommon<T>>::ensure_correct_receiver(to)?;1166		}11671168		ensure!(1169			sender.conv_eq(from),1170			<CommonError<T>>::AddressIsNotEthMirror1171		);11721173		let token_data =1174			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1175		if token_data.owner != *from {1176			ensure!(1177				collection.limits.owner_can_transfer()1178					&& (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),1179				<CommonError<T>>::CantApproveMoreThanOwned1180			);1181		}11821183		// =========11841185		Self::set_allowance_unchecked(collection, from, token, to, false);1186		Ok(())1187	}11881189	/// Checks allowance for the spender to use the token.1190	fn check_allowed(1191		collection: &NonfungibleHandle<T>,1192		spender: &T::CrossAccountId,1193		from: &T::CrossAccountId,1194		token: TokenId,1195		nesting_budget: &dyn Budget,1196	) -> DispatchResult {1197		if spender.conv_eq(from) {1198			return Ok(());1199		}1200		if collection.permissions.access() == AccessMode::AllowList {1201			// `from`, `to` checked in [`transfer`]1202			collection.check_allowlist(spender)?;1203		}12041205		if collection.ignores_token_restrictions(spender) {1206			return Ok(());1207		}12081209		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1210			ensure!(1211				<PalletStructure<T>>::check_indirectly_owned(1212					spender.clone(),1213					source.0,1214					source.1,1215					None,1216					nesting_budget1217				)?,1218				<CommonError<T>>::ApprovedValueTooLow,1219			);1220			return Ok(());1221		}1222		if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {1223			return Ok(());1224		}1225		if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1226			return Ok(());1227		}12281229		Err(<CommonError<T>>::ApprovedValueTooLow.into())1230	}12311232	/// Transfer NFT token from one account to another.1233	///1234	/// Same as the [`transfer`] but spender doesn't needs to be the owner of the token.1235	/// The owner should set allowance for the spender to transfer token.1236	///1237	/// [`transfer`]: struct.Pallet.html#method.transfer1238	pub fn transfer_from(1239		collection: &NonfungibleHandle<T>,1240		spender: &T::CrossAccountId,1241		from: &T::CrossAccountId,1242		to: &T::CrossAccountId,1243		token: TokenId,1244		nesting_budget: &dyn Budget,1245	) -> DispatchResultWithPostInfo {1246		Self::check_allowed(collection, spender, from, token, nesting_budget)?;12471248		// =========12491250		// Allowance is reset in [`transfer`]1251		let mut result = Self::transfer(collection, from, to, token, nesting_budget);1252		add_weight_to_post_info(&mut result, <SelfWeightOf<T>>::check_allowed_raw());1253		result1254	}12551256	/// Burn NFT token for `from` account.1257	///1258	/// Same as the [`burn`] but spender doesn't need to be an owner of the token. The owner should1259	/// set allowance for the spender to burn token.1260	///1261	/// [`burn`]: struct.Pallet.html#method.burn1262	pub fn burn_from(1263		collection: &NonfungibleHandle<T>,1264		spender: &T::CrossAccountId,1265		from: &T::CrossAccountId,1266		token: TokenId,1267		nesting_budget: &dyn Budget,1268	) -> DispatchResult {1269		Self::check_allowed(collection, spender, from, token, nesting_budget)?;12701271		// =========12721273		Self::burn(collection, from, token)1274	}12751276	/// Check that `from` token could be nested in `under` token.1277	///1278	pub fn check_nesting(1279		handle: &NonfungibleHandle<T>,1280		sender: T::CrossAccountId,1281		from: (CollectionId, TokenId),1282		under: TokenId,1283		nesting_budget: &dyn Budget,1284	) -> DispatchResult {1285		let nesting = handle.permissions.nesting();12861287		#[cfg(not(feature = "runtime-benchmarks"))]1288		let permissive = false;1289		#[cfg(feature = "runtime-benchmarks")]1290		let permissive = nesting.permissive;12911292		if permissive {1293			ensure!(1294				<TokenData<T>>::contains_key((handle.id, under)),1295				<CommonError<T>>::TokenNotFound1296			);1297		} else if nesting.token_owner1298			&& <PalletStructure<T>>::check_indirectly_owned(1299				sender.clone(),1300				handle.id,1301				under,1302				Some(from),1303				nesting_budget,1304			)? {1305			// Pass, token existence and ouroboros checks are done in `check_indirectly_owned`1306		} else if nesting.collection_admin && handle.is_owner_or_admin(&sender) {1307			// token existence and ouroboros checks are done in `get_checked_topmost_owner`1308			let _ = <PalletStructure<T>>::get_checked_topmost_owner(1309				handle.id,1310				under,1311				Some(from),1312				nesting_budget,1313			)?1314			.ok_or(<CommonError<T>>::TokenNotFound)?;1315		} else {1316			fail!(<CommonError<T>>::UserIsNotAllowedToNest);1317		}13181319		if let Some(whitelist) = &nesting.restricted {1320			ensure!(1321				whitelist.contains(&from.0),1322				<CommonError<T>>::SourceCollectionIsNotAllowedToNest1323			);1324		}1325		Ok(())1326	}13271328	fn nest(under: (CollectionId, TokenId), to_nest: (CollectionId, TokenId)) {1329		<TokenChildren<T>>::insert((under.0, under.1, (to_nest.0, to_nest.1)), true);1330	}13311332	fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {1333		<TokenChildren<T>>::remove((under.0, under.1, to_unnest));1334	}13351336	fn collection_has_tokens(collection_id: CollectionId) -> bool {1337		<TokenData<T>>::iter_prefix((collection_id,))1338			.next()1339			.is_some()1340	}13411342	fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {1343		<TokenChildren<T>>::iter_prefix((collection_id, token_id))1344			.next()1345			.is_some()1346	}13471348	pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {1349		<TokenChildren<T>>::iter_prefix((collection_id, token_id))1350			.map(|((child_collection_id, child_id), _)| TokenChild {1351				collection: child_collection_id,1352				token: child_id,1353			})1354			.collect()1355	}13561357	/// Mint single NFT token.1358	///1359	/// Delegated to [`create_multiple_items`]1360	///1361	/// [`create_multiple_items`]: struct.Pallet.html#method.create_multiple_items1362	pub fn create_item(1363		collection: &NonfungibleHandle<T>,1364		sender: &T::CrossAccountId,1365		data: CreateItemData<T>,1366		nesting_budget: &dyn Budget,1367	) -> DispatchResult {1368		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1369	}13701371	/// Sets or unsets the approval of a given operator.1372	///1373	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1374	/// - `owner`: Token owner1375	/// - `operator`: Operator1376	/// - `approve`: Should operator status be granted or revoked?1377	pub fn set_allowance_for_all(1378		collection: &NonfungibleHandle<T>,1379		owner: &T::CrossAccountId,1380		operator: &T::CrossAccountId,1381		approve: bool,1382	) -> DispatchResult {1383		<PalletCommon<T>>::set_allowance_for_all(1384			collection,1385			owner,1386			operator,1387			approve,1388			|| <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve),1389			ERC721Events::ApprovalForAll {1390				owner: *owner.as_eth(),1391				operator: *operator.as_eth(),1392				approved: approve,1393			}1394			.to_log(collection_id_to_address(collection.id)),1395		)1396	}13971398	/// Tells whether the given `owner` approves the `operator`.1399	pub fn allowance_for_all(1400		collection: &NonfungibleHandle<T>,1401		owner: &T::CrossAccountId,1402		operator: &T::CrossAccountId,1403	) -> bool {1404		<CollectionAllowance<T>>::get((collection.id, owner, operator))1405	}14061407	pub fn repair_item(collection: &NonfungibleHandle<T>, token: TokenId) -> DispatchResult {1408		<TokenProperties<T>>::mutate((collection.id, token), |properties| {1409			properties.recompute_consumed_space();1410		});14111412		Ok(())1413	}1414}