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

difftreelog

fix set prop for not existed token (#933)

bugrazoid2023-06-14parent: #807186d.patch.diff
in: master
* fix: set prop for not existed token

* optimize token checking

* remove comments

* test(token properties): on token non-existence

* fix PR comments

* rename value

* refactor(modify token properties): readability + grammar

* revert: unused import used for try-runtime

* fix prop permission check

* Add self_mint flag

* Add LazyValue

* fix tests

* fix unit tests

* fix docker

* fix mintCross sponsoring

* Generalize next_token_id

* fix: set sponsored properties

---------

20 files changed

modified.docker/Dockerfile-chain-dev-unitdiffbeforeafterboth
--- a/.docker/Dockerfile-chain-dev-unit
+++ b/.docker/Dockerfile-chain-dev-unit
@@ -17,4 +17,4 @@
 
 WORKDIR /dev_chain
 
-CMD cargo test --features=limit-testing --workspace
+CMD cargo test --features=limit-testing,tests --workspace
modifiedpallets/common/Cargo.tomldiffbeforeafterboth
--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -36,4 +36,5 @@
 	"up-pov-estimate-rpc/std",
 ]
 stubgen = ["evm-coder/stubgen"]
+tests = []
 try-runtime = ["frame-support/try-runtime"]
modifiedpallets/common/src/eth.rsdiffbeforeafterboth
--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -131,6 +131,18 @@
 	value: evm_coder::types::Bytes,
 }
 
+impl Property {
+	/// Property key.
+	pub fn key(&self) -> &str {
+		self.key.as_str()
+	}
+
+	/// Property value.
+	pub fn value(&self) -> &[u8] {
+		self.value.0.as_slice()
+	}
+}
+
 impl TryFrom<up_data_structs::Property> for Property {
 	type Error = pallet_evm_coder_substrate::execution::Error;
 
@@ -227,11 +239,9 @@
 			Some(value) => match value {
 				0 => Ok(Some(false)),
 				1 => Ok(Some(true)),
-				_ => {
-					return Err(Self::Error::Revert(format!(
-						"can't convert value to boolean \"{value}\""
-					)))
-				}
+				_ => Err(Self::Error::Revert(format!(
+					"can't convert value to boolean \"{value}\""
+				))),
 			},
 			None => Ok(None),
 		};
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -216,7 +216,6 @@
 	///
 	/// # Arguments
 	///
-	/// * `sender`: Caller's account.
 	/// * `sponsor`: ID of the account of the sponsor-to-be.
 	pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {
 		self.check_is_internal()?;
@@ -867,6 +866,74 @@
 	>;
 }
 
+/// Represents the change mode for the token property.
+pub enum SetPropertyMode {
+	/// The token already exists.
+	ExistingToken,
+
+	/// New token.
+	NewToken {
+		/// The creator of the token is the recipient.
+		mint_target_is_sender: bool,
+	},
+}
+
+/// Value representation with delayed initialization time.
+pub struct LazyValue<T, F: FnOnce() -> T> {
+	value: Option<T>,
+	f: Option<F>,
+}
+
+impl<T, F: FnOnce() -> T> LazyValue<T, F> {
+	/// Create a new LazyValue.
+	pub fn new(f: F) -> Self {
+		Self {
+			value: None,
+			f: Some(f),
+		}
+	}
+
+	/// Get the value. If it call furst time the value will be initialized.
+	pub fn value(&mut self) -> &T {
+		if self.value.is_none() {
+			self.value = Some(self.f.take().unwrap()())
+		}
+
+		self.value.as_ref().unwrap()
+	}
+
+	/// Is value initialized.
+	pub fn has_value(&self) -> bool {
+		self.value.is_some()
+	}
+}
+
+fn check_token_permissions<T, FCA, FTO, FTE>(
+	collection_admin_permitted: bool,
+	token_owner_permitted: bool,
+	is_collection_admin: &mut LazyValue<bool, FCA>,
+	is_token_owner: &mut LazyValue<Result<bool, DispatchError>, FTO>,
+	is_token_exist: &mut LazyValue<bool, FTE>,
+) -> DispatchResult
+where
+	T: Config,
+	FCA: FnOnce() -> bool,
+	FTO: FnOnce() -> Result<bool, DispatchError>,
+	FTE: FnOnce() -> bool,
+{
+	if !(collection_admin_permitted && *is_collection_admin.value()
+		|| token_owner_permitted && (*is_token_owner.value())?)
+	{
+		fail!(<Error<T>>::NoPermission);
+	}
+
+	let token_certainly_exist = is_token_owner.has_value() && (*is_token_owner.value())?;
+	if !token_certainly_exist && !is_token_exist.value() {
+		fail!(<Error<T>>::TokenNotFound);
+	}
+	Ok(())
+}
+
 impl<T: Config> Pallet<T> {
 	/// Enshure that receiver address is correct.
 	///
@@ -1218,10 +1285,6 @@
 	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`
 	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.
 	///
-	/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.
-	/// - `is_token_create`: Indicates that method is called during token initialization.
-	///   Allows to bypass ownership check.
-	///
 	/// All affected properties should have `mutable` permission
 	/// to be **deleted** or to be **set more than once**,
 	/// and the sender should have permission to edit those properties.
@@ -1229,35 +1292,36 @@
 	/// This function fires an event for each property change.
 	/// In case of an error, all the changes (including the events) will be reverted
 	/// since the function is transactional.
-	pub fn modify_token_properties(
+	#[allow(clippy::too_many_arguments)]
+	pub fn modify_token_properties<FTO, FTE>(
 		collection: &CollectionHandle<T>,
 		sender: &T::CrossAccountId,
 		token_id: TokenId,
+		is_token_exist: &mut LazyValue<bool, FTE>,
 		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
-		is_token_create: bool,
 		mut stored_properties: TokenProperties,
-		is_token_owner: impl Fn() -> Result<bool, DispatchError>,
+		is_token_owner: &mut LazyValue<Result<bool, DispatchError>, FTO>,
 		set_token_properties: impl FnOnce(TokenProperties),
 		log: evm_coder::ethereum::Log,
-	) -> DispatchResult {
-		let is_collection_admin = collection.is_owner_or_admin(sender);
+	) -> DispatchResult
+	where
+		FTO: FnOnce() -> Result<bool, DispatchError>,
+		FTE: FnOnce() -> bool,
+	{
+		let mut is_collection_admin = LazyValue::new(|| collection.is_owner_or_admin(sender));
 		let permissions = Self::property_permissions(collection.id);
 
-		let mut token_owner_result = None;
-		let mut is_token_owner = || -> Result<bool, DispatchError> {
-			*token_owner_result.get_or_insert_with(&is_token_owner)
-		};
-
+		let mut changed = false;
 		for (key, value) in properties_updates {
 			let permission = permissions
 				.get(&key)
 				.cloned()
 				.unwrap_or_else(PropertyPermission::none);
 
-			let is_property_exists = stored_properties.get(&key).is_some();
+			let property_exists = stored_properties.get(&key).is_some();
 
 			match permission {
-				PropertyPermission { mutable: false, .. } if is_property_exists => {
+				PropertyPermission { mutable: false, .. } if property_exists => {
 					return Err(<Error<T>>::NoPermission.into());
 				}
 
@@ -1265,17 +1329,13 @@
 					collection_admin,
 					token_owner,
 					..
-				} => {
-					//TODO: investigate threats during public minting.
-					let is_token_create =
-						is_token_create && (collection_admin || token_owner) && value.is_some();
-					if !(is_token_create
-						|| (collection_admin && is_collection_admin)
-						|| (token_owner && is_token_owner()?))
-					{
-						fail!(<Error<T>>::NoPermission);
-					}
-				}
+				} => check_token_permissions::<T, _, FTO, FTE>(
+					collection_admin,
+					token_owner,
+					&mut is_collection_admin,
+					is_token_owner,
+					is_token_exist,
+				)?,
 			}
 
 			match value {
@@ -1293,9 +1353,13 @@
 				}
 			}
 
-			<PalletEvm<T>>::deposit_log(log.clone());
+			changed = true;
 		}
 
+		if changed {
+			<PalletEvm<T>>::deposit_log(log);
+		}
+
 		set_token_properties(stored_properties);
 
 		Ok(())
@@ -2322,3 +2386,86 @@
 		}
 	}
 }
+
+#[cfg(feature = "tests")]
+pub mod tests {
+	use crate::{DispatchResult, DispatchError, LazyValue, Config};
+
+	const fn to_bool(u: u8) -> bool {
+		u != 0
+	}
+
+	#[derive(Debug)]
+	pub struct TestCase {
+		pub collection_admin: bool,
+		pub is_collection_admin: bool,
+		pub token_owner: bool,
+		pub is_token_owner: bool,
+		pub no_permission: bool,
+	}
+
+	impl TestCase {
+		const fn new(
+			collection_admin: u8,
+			is_collection_admin: u8,
+			token_owner: u8,
+			is_token_owner: u8,
+			no_permission: u8,
+		) -> Self {
+			Self {
+				collection_admin: to_bool(collection_admin),
+				is_collection_admin: to_bool(is_collection_admin),
+				token_owner: to_bool(token_owner),
+				is_token_owner: to_bool(is_token_owner),
+				no_permission: to_bool(no_permission),
+			}
+		}
+	}
+
+	#[rustfmt::skip]
+	pub const table: [TestCase; 16] = [
+		//                    ┌╴collection_admin
+		//                    │  ┌╴is_collection_admin
+		//                    │  │   ┌╴token_owner
+		//                    │  │   │  ┌╴is_token_ownership
+		//                    │  │   │  │   ┌╴no_permission
+		/*  0*/ TestCase::new(0, 0,  0, 0,  1),
+		/*  1*/ TestCase::new(0, 0,  0, 1,  1),
+		/*  2*/ TestCase::new(0, 0,  1, 0,  1),
+		/*  3*/ TestCase::new(0, 0,  1, 1,  0),
+		/*  4*/ TestCase::new(0, 1,  0, 0,  1),
+		/*  5*/ TestCase::new(0, 1,  0, 1,  1),
+		/*  6*/ TestCase::new(0, 1,  1, 0,  1),
+		/*  7*/ TestCase::new(0, 1,  1, 1,  0),
+		/*  8*/ TestCase::new(1, 0,  0, 0,  1),
+		/*  9*/ TestCase::new(1, 0,  0, 1,  1),
+		/* 10*/ TestCase::new(1, 0,  1, 0,  1),
+		/* 11*/ TestCase::new(1, 0,  1, 1,  0),
+		/* 12*/ TestCase::new(1, 1,  0, 0,  0),
+		/* 13*/ TestCase::new(1, 1,  0, 1,  0),
+		/* 14*/ TestCase::new(1, 1,  1, 0,  0),
+		/* 15*/ TestCase::new(1, 1,  1, 1,  0),
+	];
+
+	pub fn check_token_permissions<T, FCA, FTO, FTE>(
+		collection_admin_permitted: bool,
+		token_owner_permitted: bool,
+		is_collection_admin: &mut LazyValue<bool, FCA>,
+		check_token_ownership: &mut LazyValue<Result<bool, DispatchError>, FTO>,
+		check_token_existence: &mut LazyValue<bool, FTE>,
+	) -> DispatchResult
+	where
+		T: Config,
+		FCA: FnOnce() -> bool,
+		FTO: FnOnce() -> Result<bool, DispatchError>,
+		FTE: FnOnce() -> bool,
+	{
+		crate::check_token_permissions::<T, FCA, FTO, FTE>(
+			collection_admin_permitted,
+			token_owner_permitted,
+			is_collection_admin,
+			check_token_ownership,
+			check_token_existence,
+		)
+	}
+}
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -245,7 +245,7 @@
 				&sender,
 				token_id,
 				properties.into_iter(),
-				false,
+				pallet_common::SetPropertyMode::ExistingToken,
 				nesting_budget,
 			),
 			weight,
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -194,7 +194,7 @@
 			&caller,
 			TokenId(token_id),
 			properties.into_iter(),
-			false,
+			pallet_common::SetPropertyMode::ExistingToken,
 			&nesting_budget,
 		)
 		.map_err(dispatch_to_evm::<T>)
@@ -939,9 +939,8 @@
 	/// @notice Returns next free NFT ID.
 	fn next_token_id(&self) -> Result<U256> {
 		self.consume_store_reads(1)?;
-		Ok(<TokensMinted<T>>::get(self.id)
-			.checked_add(1)
-			.ok_or("item id overflow")?
+		Ok(<Pallet<T>>::next_token_id(self)
+			.map_err(dispatch_to_evm::<T>)?
 			.into())
 	}
 
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 up_data_structs::{CollectionId, TokenId};155	use super::weights::WeightInfo;156157	#[pallet::error]158	pub enum Error<T> {159		/// Not Nonfungible item data used to mint in Nonfungible collection.160		NotNonfungibleDataUsedToMintFungibleCollectionToken,161		/// Used amount > 1 with NFT162		NonfungibleItemsHaveNoAmount,163		/// Unable to burn NFT with children164		CantBurnNftWithChildren,165	}166167	#[pallet::config]168	pub trait Config:169		frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config170	{171		type WeightInfo: WeightInfo;172	}173174	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);175176	#[pallet::pallet]177	#[pallet::storage_version(STORAGE_VERSION)]178	pub struct Pallet<T>(_);179180	/// Total amount of minted tokens in a collection.181	#[pallet::storage]182	pub type TokensMinted<T: Config> =183		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;184185	/// Amount of burnt tokens in a collection.186	#[pallet::storage]187	pub type TokensBurnt<T: Config> =188		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;189190	/// Token data, used to partially describe a token.191	#[pallet::storage]192	pub type TokenData<T: Config> = StorageNMap<193		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),194		Value = ItemData<T::CrossAccountId>,195		QueryKind = OptionQuery,196	>;197198	/// Map of key-value pairs, describing the metadata of a token.199	#[pallet::storage]200	#[pallet::getter(fn token_properties)]201	pub type TokenProperties<T: Config> = StorageNMap<202		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),203		Value = TokenPropertiesT,204		QueryKind = ValueQuery,205	>;206207	/// Custom data of a token that is serialized to bytes,208	/// primarily reserved for on-chain operations,209	/// normally obscured from the external users.210	///211	/// Auxiliary properties are slightly different from212	/// usual [`TokenProperties`] due to an unlimited number213	/// and separately stored and written-to key-value pairs.214	///215	/// Currently unused.216	#[pallet::storage]217	#[pallet::getter(fn token_aux_property)]218	pub type TokenAuxProperties<T: Config> = StorageNMap<219		Key = (220			Key<Twox64Concat, CollectionId>,221			Key<Twox64Concat, TokenId>,222			Key<Twox64Concat, PropertyScope>,223			Key<Twox64Concat, PropertyKey>,224		),225		Value = AuxPropertyValue,226		QueryKind = OptionQuery,227	>;228229	/// Used to enumerate tokens owned by account.230	#[pallet::storage]231	pub type Owned<T: Config> = StorageNMap<232		Key = (233			Key<Twox64Concat, CollectionId>,234			Key<Blake2_128Concat, T::CrossAccountId>,235			Key<Twox64Concat, TokenId>,236		),237		Value = bool,238		QueryKind = ValueQuery,239	>;240241	/// Used to enumerate token's children.242	#[pallet::storage]243	#[pallet::getter(fn token_children)]244	pub type TokenChildren<T: Config> = StorageNMap<245		Key = (246			Key<Twox64Concat, CollectionId>,247			Key<Twox64Concat, TokenId>,248			Key<Twox64Concat, (CollectionId, TokenId)>,249		),250		Value = bool,251		QueryKind = ValueQuery,252	>;253254	/// Amount of tokens owned by an account in a collection.255	#[pallet::storage]256	pub type AccountBalance<T: Config> = StorageNMap<257		Key = (258			Key<Twox64Concat, CollectionId>,259			Key<Blake2_128Concat, T::CrossAccountId>,260		),261		Value = u32,262		QueryKind = ValueQuery,263	>;264265	/// Allowance set by a token owner for another user to perform one of certain transactions on a token.266	#[pallet::storage]267	pub type Allowance<T: Config> = StorageNMap<268		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),269		Value = T::CrossAccountId,270		QueryKind = OptionQuery,271	>;272273	/// Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.274	#[pallet::storage]275	pub type CollectionAllowance<T: Config> = StorageNMap<276		Key = (277			Key<Twox64Concat, CollectionId>,278			Key<Blake2_128Concat, T::CrossAccountId>,279			Key<Blake2_128Concat, T::CrossAccountId>,280		),281		Value = bool,282		QueryKind = ValueQuery,283	>;284285	#[pallet::genesis_config]286	pub struct GenesisConfig<T>(PhantomData<T>);287288	#[cfg(feature = "std")]289	impl<T: Config> Default for GenesisConfig<T> {290		fn default() -> Self {291			Self(Default::default())292		}293	}294295	#[pallet::genesis_build]296	impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {297		fn build(&self) {298			StorageVersion::new(1).put::<Pallet<T>>();299		}300	}301}302303pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);304impl<T: Config> NonfungibleHandle<T> {305	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {306		Self(inner)307	}308	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {309		self.0310	}311	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {312		&mut self.0313	}314}315316impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {317	fn recorder(&self) -> &SubstrateRecorder<T> {318		self.0.recorder()319	}320	fn into_recorder(self) -> SubstrateRecorder<T> {321		self.0.into_recorder()322	}323}324impl<T: Config> Deref for NonfungibleHandle<T> {325	type Target = pallet_common::CollectionHandle<T>;326327	fn deref(&self) -> &Self::Target {328		&self.0329	}330}331332impl<T: Config> Pallet<T> {333	/// Get number of NFT tokens in collection.334	pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {335		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)336	}337338	/// Check that NFT token exists.339	///340	/// - `token`: Token ID.341	pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {342		<TokenData<T>>::contains_key((collection.id, token))343	}344345	/// Set the token property with the scope.346	///347	/// - `property`: Contains key-value pair.348	pub fn set_scoped_token_property(349		collection_id: CollectionId,350		token_id: TokenId,351		scope: PropertyScope,352		property: Property,353	) -> DispatchResult {354		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {355			properties.try_scoped_set(scope, property.key, property.value)356		})357		.map_err(<CommonError<T>>::from)?;358359		Ok(())360	}361362	/// Batch operation to set multiple properties with the same scope.363	pub fn set_scoped_token_properties(364		collection_id: CollectionId,365		token_id: TokenId,366		scope: PropertyScope,367		properties: impl Iterator<Item = Property>,368	) -> DispatchResult {369		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {370			stored_properties.try_scoped_set_from_iter(scope, properties)371		})372		.map_err(<CommonError<T>>::from)?;373374		Ok(())375	}376377	/// Add or edit auxiliary data for the property.378	///379	/// - `f`: function that adds or edits auxiliary data.380	pub fn try_mutate_token_aux_property<R, E>(381		collection_id: CollectionId,382		token_id: TokenId,383		scope: PropertyScope,384		key: PropertyKey,385		f: impl FnOnce(&mut Option<AuxPropertyValue>) -> Result<R, E>,386	) -> Result<R, E> {387		<TokenAuxProperties<T>>::try_mutate((collection_id, token_id, scope, key), f)388	}389390	/// Remove auxiliary data for the property.391	pub fn remove_token_aux_property(392		collection_id: CollectionId,393		token_id: TokenId,394		scope: PropertyScope,395		key: PropertyKey,396	) {397		<TokenAuxProperties<T>>::remove((collection_id, token_id, scope, key));398	}399400	/// Get all auxiliary data in a given scope.401	///402	/// Returns iterator over Property Key - Data pairs.403	pub fn iterate_token_aux_properties(404		collection_id: CollectionId,405		token_id: TokenId,406		scope: PropertyScope,407	) -> impl Iterator<Item = (PropertyKey, AuxPropertyValue)> {408		<TokenAuxProperties<T>>::iter_prefix((collection_id, token_id, scope))409	}410411	/// Get ID of the last minted token412	pub fn current_token_id(collection_id: CollectionId) -> TokenId {413		TokenId(<TokensMinted<T>>::get(collection_id))414	}415}416417// unchecked calls skips any permission checks418impl<T: Config> Pallet<T> {419	/// Create NFT collection420	///421	/// `init_collection` will take non-refundable deposit for collection creation.422	///423	/// - `data`: Contains settings for collection limits and permissions.424	pub fn init_collection(425		owner: T::CrossAccountId,426		payer: T::CrossAccountId,427		data: CreateCollectionData<T::AccountId>,428		flags: CollectionFlags,429	) -> Result<CollectionId, DispatchError> {430		<PalletCommon<T>>::init_collection(owner, payer, data, flags)431	}432433	/// Destroy NFT collection434	///435	/// `destroy_collection` will throw error if collection contains any tokens.436	/// Only owner can destroy collection.437	pub fn destroy_collection(438		collection: NonfungibleHandle<T>,439		sender: &T::CrossAccountId,440	) -> DispatchResult {441		let id = collection.id;442443		if Self::collection_has_tokens(id) {444			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());445		}446447		// =========448449		PalletCommon::destroy_collection(collection.0, sender)?;450451		let _ = <TokenData<T>>::clear_prefix((id,), u32::MAX, None);452		let _ = <TokenChildren<T>>::clear_prefix((id,), u32::MAX, None);453		let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);454		<TokensMinted<T>>::remove(id);455		<TokensBurnt<T>>::remove(id);456		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);457		let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);458		let _ = <CollectionAllowance<T>>::clear_prefix((id,), u32::MAX, None);459		Ok(())460	}461462	/// Burn NFT token463	///464	/// `burn` removes `token` from the `collection`, from it's owner and from the parent token465	/// if the token is nested.466	/// Only the owner can `burn` the token. The `token` shouldn't have any nested tokens.467	/// Also removes all corresponding properties and auxiliary properties.468	///469	/// - `token`: Token that should be burned470	/// - `collection`: Collection that contains the token471	pub fn burn(472		collection: &NonfungibleHandle<T>,473		sender: &T::CrossAccountId,474		token: TokenId,475	) -> DispatchResult {476		let token_data =477			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;478		ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);479480		if collection.permissions.access() == AccessMode::AllowList {481			collection.check_allowlist(sender)?;482		}483484		if Self::token_has_children(collection.id, token) {485			return Err(<Error<T>>::CantBurnNftWithChildren.into());486		}487488		let burnt = <TokensBurnt<T>>::get(collection.id)489			.checked_add(1)490			.ok_or(ArithmeticError::Overflow)?;491492		let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))493			.checked_sub(1)494			.ok_or(ArithmeticError::Overflow)?;495496		// =========497498		if balance == 0 {499			<AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));500		} else {501			<AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);502		}503504		<PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);505506		<Owned<T>>::remove((collection.id, &token_data.owner, token));507		<TokensBurnt<T>>::insert(collection.id, burnt);508		<TokenData<T>>::remove((collection.id, token));509		<TokenProperties<T>>::remove((collection.id, token));510		let _ = <TokenAuxProperties<T>>::clear_prefix((collection.id, token), u32::MAX, None);511		let old_spender = <Allowance<T>>::take((collection.id, token));512513		if let Some(old_spender) = old_spender {514			<PalletCommon<T>>::deposit_event(CommonEvent::Approved(515				collection.id,516				token,517				token_data.owner.clone(),518				old_spender,519				0,520			));521		}522523		<PalletEvm<T>>::deposit_log(524			ERC721Events::Transfer {525				from: *token_data.owner.as_eth(),526				to: H160::default(),527				token_id: token.into(),528			}529			.to_log(collection_id_to_address(collection.id)),530		);531		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(532			collection.id,533			token,534			token_data.owner,535			1,536		));537		Ok(())538	}539540	/// Same as [`burn`] but burns all the tokens that are nested in the token first541	///542	/// - `self_budget`: Limit for searching children in depth.543	/// - `breadth_budget`: Limit of breadth of searching children.544	///545	/// [`burn`]: struct.Pallet.html#method.burn546	#[transactional]547	pub fn burn_recursively(548		collection: &NonfungibleHandle<T>,549		sender: &T::CrossAccountId,550		token: TokenId,551		self_budget: &dyn Budget,552		breadth_budget: &dyn Budget,553	) -> DispatchResultWithPostInfo {554		ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);555556		let current_token_account =557			T::CrossTokenAddressMapping::token_to_address(collection.id, token);558559		let mut weight = Weight::zero();560561		// This method is transactional, if user in fact doesn't have permissions to remove token -562		// tokens removed here will be restored after rejected transaction563		for ((collection, token), _) in <TokenChildren<T>>::iter_prefix((collection.id, token)) {564			ensure!(breadth_budget.consume(), <StructureError<T>>::BreadthLimit,);565			let PostDispatchInfo { actual_weight, .. } =566				<PalletStructure<T>>::burn_item_recursively(567					current_token_account.clone(),568					collection,569					token,570					self_budget,571					breadth_budget,572				)?;573			if let Some(actual_weight) = actual_weight {574				weight = weight.saturating_add(actual_weight);575			}576		}577578		Self::burn(collection, sender, token)?;579		DispatchResultWithPostInfo::Ok(PostDispatchInfo {580			actual_weight: Some(weight + <SelfWeightOf<T>>::burn_item()),581			pays_fee: Pays::Yes,582		})583	}584585	/// A batch operation to add, edit or remove properties for a token.586	///587	/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.588	/// - `is_token_create`: Indicates that method is called during token initialization.589	///   Allows to bypass ownership check.590	///591	/// All affected properties should have `mutable` permission592	/// to be **deleted** or to be **set more than once**,593	/// and the sender should have permission to edit those properties.594	///595	/// This function fires an event for each property change.596	/// In case of an error, all the changes (including the events) will be reverted597	/// since the function is transactional.598	#[transactional]599	fn modify_token_properties(600		collection: &NonfungibleHandle<T>,601		sender: &T::CrossAccountId,602		token_id: TokenId,603		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,604		is_token_create: bool,605		nesting_budget: &dyn Budget,606	) -> DispatchResult {607		let is_token_owner = || {608			let is_owned = <PalletStructure<T>>::check_indirectly_owned(609				sender.clone(),610				collection.id,611				token_id,612				None,613				nesting_budget,614			)?;615616			Ok(is_owned)617		};618619		let stored_properties = <TokenProperties<T>>::get((collection.id, token_id));620621		<PalletCommon<T>>::modify_token_properties(622			collection,623			sender,624			token_id,625			properties_updates,626			is_token_create,627			stored_properties,628			is_token_owner,629			|properties| <TokenProperties<T>>::set((collection.id, token_id), properties),630			erc::ERC721TokenEvent::TokenChanged {631				token_id: token_id.into(),632			}633			.to_log(T::ContractAddress::get()),634		)635	}636637	/// Batch operation to add or edit properties for the token638	///639	/// Same as [`modify_token_properties`] but doesn't allow to remove properties640	///641	/// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties642	pub fn set_token_properties(643		collection: &NonfungibleHandle<T>,644		sender: &T::CrossAccountId,645		token_id: TokenId,646		properties: impl Iterator<Item = Property>,647		is_token_create: bool,648		nesting_budget: &dyn Budget,649	) -> DispatchResult {650		Self::modify_token_properties(651			collection,652			sender,653			token_id,654			properties.map(|p| (p.key, Some(p.value))),655			is_token_create,656			nesting_budget,657		)658	}659660	/// Add or edit single property for the token661	///662	/// Calls [`set_token_properties`] internally663	///664	/// [`set_token_properties`]: struct.Pallet.html#method.set_token_properties665	pub fn set_token_property(666		collection: &NonfungibleHandle<T>,667		sender: &T::CrossAccountId,668		token_id: TokenId,669		property: Property,670		nesting_budget: &dyn Budget,671	) -> DispatchResult {672		let is_token_create = false;673674		Self::set_token_properties(675			collection,676			sender,677			token_id,678			[property].into_iter(),679			is_token_create,680			nesting_budget,681		)682	}683684	/// Batch operation to remove properties from the token685	///686	/// Same as [`modify_token_properties`] but doesn't allow to add or edit properties687	///688	/// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties689	pub fn delete_token_properties(690		collection: &NonfungibleHandle<T>,691		sender: &T::CrossAccountId,692		token_id: TokenId,693		property_keys: impl Iterator<Item = PropertyKey>,694		nesting_budget: &dyn Budget,695	) -> DispatchResult {696		let is_token_create = false;697698		Self::modify_token_properties(699			collection,700			sender,701			token_id,702			property_keys.into_iter().map(|key| (key, None)),703			is_token_create,704			nesting_budget,705		)706	}707708	/// Remove single property from the token709	///710	/// Calls [`delete_token_properties`] internally711	///712	/// [`delete_token_properties`]: struct.Pallet.html#method.delete_token_properties713	pub fn delete_token_property(714		collection: &NonfungibleHandle<T>,715		sender: &T::CrossAccountId,716		token_id: TokenId,717		property_key: PropertyKey,718		nesting_budget: &dyn Budget,719	) -> DispatchResult {720		Self::delete_token_properties(721			collection,722			sender,723			token_id,724			[property_key].into_iter(),725			nesting_budget,726		)727	}728729	/// Add or edit properties for the collection730	pub fn set_collection_properties(731		collection: &NonfungibleHandle<T>,732		sender: &T::CrossAccountId,733		properties: Vec<Property>,734	) -> DispatchResult {735		<PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())736	}737738	/// Remove properties from the collection739	pub fn delete_collection_properties(740		collection: &CollectionHandle<T>,741		sender: &T::CrossAccountId,742		property_keys: Vec<PropertyKey>,743	) -> DispatchResult {744		<PalletCommon<T>>::delete_collection_properties(745			collection,746			sender,747			property_keys.into_iter(),748		)749	}750751	/// Set property permissions for the token.752	///753	/// Sender should be the owner or admin of token's collection.754	pub fn set_token_property_permissions(755		collection: &CollectionHandle<T>,756		sender: &T::CrossAccountId,757		property_permissions: Vec<PropertyKeyPermission>,758	) -> DispatchResult {759		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)760	}761762	/// Set property permissions for the token with scope.763	///764	/// Sender should be the owner or admin of token's collection.765	pub fn set_scoped_token_property_permissions(766		collection: &CollectionHandle<T>,767		sender: &T::CrossAccountId,768		scope: PropertyScope,769		property_permissions: Vec<PropertyKeyPermission>,770	) -> DispatchResult {771		<PalletCommon<T>>::set_scoped_token_property_permissions(772			collection,773			sender,774			scope,775			property_permissions,776		)777	}778779	pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {780		<PalletCommon<T>>::property_permissions(collection_id)781	}782783	pub fn check_token_immediate_ownership(784		collection: &NonfungibleHandle<T>,785		token: TokenId,786		possible_owner: &T::CrossAccountId,787	) -> DispatchResult {788		let token_data =789			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;790		ensure!(791			&token_data.owner == possible_owner,792			<CommonError<T>>::NoPermission793		);794		Ok(())795	}796797	/// Transfer NFT token from one account to another.798	///799	/// `from` account stops being the owner and `to` account becomes the owner of the token.800	/// If `to` is token than `to` becomes owner of the token and the token become nested.801	/// Unnests token from previous parent if it was nested before.802	/// Removes allowance for the token if there was any.803	/// Throws if transfers aren't allowed for collection or if receiver reached token ownership limit.804	///805	/// - `nesting_budget`: Limit for token nesting depth806	pub fn transfer(807		collection: &NonfungibleHandle<T>,808		from: &T::CrossAccountId,809		to: &T::CrossAccountId,810		token: TokenId,811		nesting_budget: &dyn Budget,812	) -> DispatchResultWithPostInfo {813		ensure!(814			collection.limits.transfers_enabled(),815			<CommonError<T>>::TransferNotAllowed816		);817818		let mut actual_weight = <SelfWeightOf<T>>::transfer_raw();819		let token_data =820			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;821		ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);822823		if collection.permissions.access() == AccessMode::AllowList {824			collection.check_allowlist(from)?;825			collection.check_allowlist(to)?;826			actual_weight += <PalletCommonWeightOf<T>>::check_accesslist() * 2;827		}828		<PalletCommon<T>>::ensure_correct_receiver(to)?;829830		let balance_from = <AccountBalance<T>>::get((collection.id, from))831			.checked_sub(1)832			.ok_or(<CommonError<T>>::TokenValueTooLow)?;833		let balance_to = if from != to {834			let balance_to = <AccountBalance<T>>::get((collection.id, to))835				.checked_add(1)836				.ok_or(ArithmeticError::Overflow)?;837838			ensure!(839				balance_to < collection.limits.account_token_ownership_limit(),840				<CommonError<T>>::AccountTokenLimitExceeded,841			);842843			Some(balance_to)844		} else {845			None846		};847848		<PalletStructure<T>>::nest_if_sent_to_token(849			from.clone(),850			to,851			collection.id,852			token,853			nesting_budget,854		)?;855856		// =========857858		<PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);859860		<TokenData<T>>::insert((collection.id, token), ItemData { owner: to.clone() });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		if to_nest.0 != pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {1323			<TokenChildren<T>>::insert((under.0, under.1, to_nest), true);1324		}1325	}13261327	fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {1328		if to_unnest.0 != pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {1329			<TokenChildren<T>>::remove((under.0, under.1, to_unnest));1330		}1331	}13321333	fn collection_has_tokens(collection_id: CollectionId) -> bool {1334		<TokenData<T>>::iter_prefix((collection_id,))1335			.next()1336			.is_some()1337	}13381339	fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {1340		<TokenChildren<T>>::iter_prefix((collection_id, token_id))1341			.next()1342			.is_some()1343	}13441345	pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {1346		<TokenChildren<T>>::iter_prefix((collection_id, token_id))1347			.map(|((child_collection_id, child_id), _)| TokenChild {1348				collection: child_collection_id,1349				token: child_id,1350			})1351			.collect()1352	}13531354	/// Mint single NFT token.1355	///1356	/// Delegated to [`create_multiple_items`]1357	///1358	/// [`create_multiple_items`]: struct.Pallet.html#method.create_multiple_items1359	pub fn create_item(1360		collection: &NonfungibleHandle<T>,1361		sender: &T::CrossAccountId,1362		data: CreateItemData<T>,1363		nesting_budget: &dyn Budget,1364	) -> DispatchResult {1365		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1366	}13671368	/// Sets or unsets the approval of a given operator.1369	///1370	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1371	/// - `owner`: Token owner1372	/// - `operator`: Operator1373	/// - `approve`: Should operator status be granted or revoked?1374	pub fn set_allowance_for_all(1375		collection: &NonfungibleHandle<T>,1376		owner: &T::CrossAccountId,1377		operator: &T::CrossAccountId,1378		approve: bool,1379	) -> DispatchResult {1380		<PalletCommon<T>>::set_allowance_for_all(1381			collection,1382			owner,1383			operator,1384			approve,1385			|| <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve),1386			ERC721Events::ApprovalForAll {1387				owner: *owner.as_eth(),1388				operator: *operator.as_eth(),1389				approved: approve,1390			}1391			.to_log(collection_id_to_address(collection.id)),1392		)1393	}13941395	/// Tells whether the given `owner` approves the `operator`.1396	pub fn allowance_for_all(1397		collection: &NonfungibleHandle<T>,1398		owner: &T::CrossAccountId,1399		operator: &T::CrossAccountId,1400	) -> bool {1401		<CollectionAllowance<T>>::get((collection.id, owner, operator))1402	}14031404	pub fn repair_item(collection: &NonfungibleHandle<T>, token: TokenId) -> DispatchResult {1405		<TokenProperties<T>>::mutate((collection.id, token), |properties| {1406			properties.recompute_consumed_space();1407		});14081409		Ok(())1410	}1411}
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -399,7 +399,7 @@
 				&sender,
 				token_id,
 				properties.into_iter(),
-				false,
+				pallet_common::SetPropertyMode::ExistingToken,
 				nesting_budget,
 			),
 			weight,
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -196,7 +196,7 @@
 			&caller,
 			TokenId(token_id),
 			properties.into_iter(),
-			false,
+			pallet_common::SetPropertyMode::ExistingToken,
 			&nesting_budget,
 		)
 		.map_err(dispatch_to_evm::<T>)
@@ -973,9 +973,8 @@
 	/// @notice Returns next free RFT ID.
 	fn next_token_id(&self) -> Result<U256> {
 		self.consume_store_reads(1)?;
-		Ok(<TokensMinted<T>>::get(self.id)
-			.checked_add(1)
-			.ok_or("item id overflow")?
+		Ok(<Pallet<T>>::next_token_id(self)
+			.map_err(dispatch_to_evm::<T>)?
 			.into())
 	}
 
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -97,7 +97,7 @@
 use pallet_evm_coder_substrate::WithRecorder;
 use pallet_common::{
 	CommonCollectionOperations, Error as CommonError, eth::collection_id_to_address,
-	Event as CommonEvent, Pallet as PalletCommon,
+	Event as CommonEvent, Pallet as PalletCommon, SetPropertyMode,
 };
 use pallet_structure::Pallet as PalletStructure;
 use sp_core::{Get, H160};
@@ -521,8 +521,6 @@
 	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.
 	///
 	/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.
-	/// - `is_token_create`: Indicates that method is called during token initialization.
-	///   Allows to bypass ownership check.
 	///
 	/// All affected properties should have `mutable` permission
 	/// to be **deleted** or to be **set more than once**,
@@ -537,27 +535,38 @@
 		sender: &T::CrossAccountId,
 		token_id: TokenId,
 		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
-		is_token_create: bool,
+		mode: SetPropertyMode,
 		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
-		let is_token_owner = || -> Result<bool, DispatchError> {
-			let balance = collection.balance(sender.clone(), token_id);
-			let total_pieces: u128 =
-				Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);
-			if balance != total_pieces {
-				return Ok(false);
-			}
+		let mut is_token_owner =
+			pallet_common::LazyValue::new(|| -> Result<bool, DispatchError> {
+				if let SetPropertyMode::NewToken {
+					mint_target_is_sender,
+				} = mode
+				{
+					return Ok(mint_target_is_sender);
+				}
 
-			let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(
-				sender.clone(),
-				collection.id,
-				token_id,
-				None,
-				nesting_budget,
-			)?;
+				let balance = collection.balance(sender.clone(), token_id);
+				let total_pieces: u128 =
+					Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);
+				if balance != total_pieces {
+					return Ok(false);
+				}
+
+				let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(
+					sender.clone(),
+					collection.id,
+					token_id,
+					None,
+					nesting_budget,
+				)?;
+
+				Ok(is_bundle_owner)
+			});
 
-			Ok(is_bundle_owner)
-		};
+		let mut is_token_exist =
+			pallet_common::LazyValue::new(|| Self::token_exists(collection, token_id));
 
 		let stored_properties = <TokenProperties<T>>::get((collection.id, token_id));
 
@@ -565,10 +574,10 @@
 			collection,
 			sender,
 			token_id,
+			&mut is_token_exist,
 			properties_updates,
-			is_token_create,
 			stored_properties,
-			is_token_owner,
+			&mut is_token_owner,
 			|properties| <TokenProperties<T>>::set((collection.id, token_id), properties),
 			erc::ERC721TokenEvent::TokenChanged {
 				token_id: token_id.into(),
@@ -577,12 +586,25 @@
 		)
 	}
 
+	pub fn next_token_id(collection: &RefungibleHandle<T>) -> Result<TokenId, DispatchError> {
+		let next_token_id = <TokensMinted<T>>::get(collection.id)
+			.checked_add(1)
+			.ok_or(<CommonError<T>>::CollectionTokenLimitExceeded)?;
+
+		ensure!(
+			collection.limits.token_limit() >= next_token_id,
+			<CommonError<T>>::CollectionTokenLimitExceeded
+		);
+
+		Ok(TokenId(next_token_id))
+	}
+
 	pub fn set_token_properties(
 		collection: &RefungibleHandle<T>,
 		sender: &T::CrossAccountId,
 		token_id: TokenId,
 		properties: impl Iterator<Item = Property>,
-		is_token_create: bool,
+		mode: SetPropertyMode,
 		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
 		Self::modify_token_properties(
@@ -590,7 +612,7 @@
 			sender,
 			token_id,
 			properties.map(|p| (p.key, Some(p.value))),
-			is_token_create,
+			mode,
 			nesting_budget,
 		)
 	}
@@ -602,14 +624,12 @@
 		property: Property,
 		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
-		let is_token_create = false;
-
 		Self::set_token_properties(
 			collection,
 			sender,
 			token_id,
 			[property].into_iter(),
-			is_token_create,
+			SetPropertyMode::ExistingToken,
 			nesting_budget,
 		)
 	}
@@ -621,14 +641,12 @@
 		property_keys: impl Iterator<Item = PropertyKey>,
 		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
-		let is_token_create = false;
-
 		Self::modify_token_properties(
 			collection,
 			sender,
 			token_id,
 			property_keys.into_iter().map(|key| (key, None)),
-			is_token_create,
+			SetPropertyMode::ExistingToken,
 			nesting_budget,
 		)
 	}
@@ -914,10 +932,14 @@
 				let token_id = first_token_id + i as u32 + 1;
 				<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);
 
+				let mut mint_target_is_sender = true;
 				for (user, amount) in data.users.iter() {
 					if *amount == 0 {
 						continue;
 					}
+
+					mint_target_is_sender = mint_target_is_sender && sender.conv_eq(user);
+
 					<Balance<T>>::insert((collection.id, token_id, &user), amount);
 					<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);
 					<PalletStructure<T>>::nest_if_sent_to_token_unchecked(
@@ -932,7 +954,9 @@
 					sender,
 					TokenId(token_id),
 					data.properties.clone().into_iter(),
-					true,
+					SetPropertyMode::NewToken {
+						mint_target_is_sender,
+					},
 					nesting_budget,
 				) {
 					return TransactionOutcome::Rollback(Err(e));
modifiedruntime/common/ethereum/sponsoring.rsdiffbeforeafterboth
--- a/runtime/common/ethereum/sponsoring.rs
+++ b/runtime/common/ethereum/sponsoring.rs
@@ -22,7 +22,7 @@
 use pallet_evm::account::CrossAccountId;
 use pallet_evm_transaction_payment::CallContext;
 use pallet_nonfungible::{
-	Config as NonfungibleConfig,
+	Config as NonfungibleConfig, Pallet as NonfungiblePallet, NonfungibleHandle,
 	erc::{
 		UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721UniqueMintableCall, ERC721Call,
 		TokenPropertiesCall,
@@ -56,6 +56,8 @@
 pub struct UniqueEthSponsorshipHandler<T: UniqueConfig>(PhantomData<*const T>);
 impl<T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig>
 	SponsorshipHandler<T::CrossAccountId, CallContext> for UniqueEthSponsorshipHandler<T>
+where
+	T::AccountId: From<[u8; 32]>,
 {
 	fn get_sponsor(
 		who: &T::CrossAccountId,
@@ -67,29 +69,71 @@
 			let (method_id, mut reader) = AbiReader::new_call(&call_context.input).ok()?;
 			Some(T::CrossAccountId::from_sub(match &collection.mode {
 				CollectionMode::NFT => {
+					let collection = NonfungibleHandle::cast(collection);
 					let call = <UniqueNFTCall<T>>::parse(method_id, &mut reader).ok()??;
 					match call {
-						UniqueNFTCall::TokenProperties(TokenPropertiesCall::SetProperty {
-							token_id,
-							key,
-							value,
-							..
-						}) => {
-							let token_id: TokenId = token_id.try_into().ok()?;
-							withdraw_set_token_property::<T>(
-								&collection,
-								who,
-								&token_id,
-								key.len() + value.len(),
-							)
-							.map(|()| sponsor)
-						}
-						UniqueNFTCall::ERC721UniqueExtensions(
-							ERC721UniqueExtensionsCall::Transfer { token_id, .. },
-						) => {
-							let token_id: TokenId = token_id.try_into().ok()?;
-							withdraw_transfer::<T>(&collection, who, &token_id).map(|()| sponsor)
-						}
+						UniqueNFTCall::TokenProperties(call) => match call {
+							TokenPropertiesCall::SetProperty {
+								token_id,
+								key,
+								value,
+								..
+							} => {
+								let token_id: TokenId = token_id.try_into().ok()?;
+								withdraw_set_existing_token_property::<T>(
+									&collection,
+									who,
+									&token_id,
+									key.len() + value.len(),
+								)
+								.map(|()| sponsor)
+							}
+							TokenPropertiesCall::SetProperties {
+								token_id,
+								properties,
+								..
+							} => {
+								let token_id: TokenId = token_id.try_into().ok()?;
+								let data_size = properties
+									.into_iter()
+									.map(|p| p.key().len() + p.value().len())
+									.sum();
+
+								withdraw_set_existing_token_property::<T>(
+									&collection,
+									who,
+									&token_id,
+									data_size,
+								)
+								.map(|()| sponsor)
+							}
+							_ => None,
+						},
+						UniqueNFTCall::ERC721UniqueExtensions(call) => match call {
+							ERC721UniqueExtensionsCall::Transfer { token_id, .. } => {
+								let token_id: TokenId = token_id.try_into().ok()?;
+								withdraw_transfer::<T>(&collection, who, &token_id)
+									.map(|()| sponsor)
+							}
+							ERC721UniqueExtensionsCall::MintCross { properties, .. } => {
+								withdraw_create_item::<T>(
+									&collection,
+									who,
+									&CreateItemData::NFT(CreateNftData::default()),
+								)?;
+
+								let token_id =
+									<NonfungiblePallet<T>>::next_token_id(&collection).ok()?;
+								let data_size: usize = properties
+									.into_iter()
+									.map(|p| p.key().len() + p.value().len())
+									.sum();
+
+								withdraw_set_token_property::<T>(&collection, &token_id, data_size)
+									.map(|()| sponsor)
+							}
+							_ => None,
+						},
 						UniqueNFTCall::ERC721UniqueMintable(
 							ERC721UniqueMintableCall::Mint { .. }
 							| ERC721UniqueMintableCall::MintCheckId { .. }
modifiedruntime/common/ethereum/sponsoring/refungible.rsdiffbeforeafterboth
--- a/runtime/common/ethereum/sponsoring/refungible.rs
+++ b/runtime/common/ethereum/sponsoring/refungible.rs
@@ -94,7 +94,12 @@
 			..
 		} => {
 			let token_id = TokenId::try_from(token_id).ok()?;
-			withdraw_set_token_property::<T>(&collection, who, &token_id, key.len() + value.len())
+			withdraw_set_existing_token_property::<T>(
+				&collection,
+				who,
+				&token_id,
+				key.len() + value.len(),
+			)
 		}
 	}
 }
modifiedruntime/common/sponsoring.rsdiffbeforeafterboth
--- a/runtime/common/sponsoring.rs
+++ b/runtime/common/sponsoring.rs
@@ -39,7 +39,7 @@
 impl<T> Config for T where T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig {}
 
 // TODO: permission check?
-pub fn withdraw_set_token_property<T: Config>(
+pub fn withdraw_set_existing_token_property<T: Config>(
 	collection: &CollectionHandle<T>,
 	who: &T::CrossAccountId,
 	item_id: &TokenId,
@@ -64,6 +64,17 @@
 		}
 	}
 
+	withdraw_set_token_property(collection, item_id, data_size)
+}
+
+pub fn withdraw_set_token_property<T: Config>(
+	collection: &CollectionHandle<T>,
+	item_id: &TokenId,
+	data_size: usize,
+) -> Option<()> {
+	if data_size == 0 {
+		return Some(());
+	}
 	if data_size > collection.limits.sponsored_data_size() as usize {
 		return None;
 	}
@@ -173,7 +184,6 @@
 			return None;
 		}
 	}
-
 	CreateItemBasket::<T>::insert((collection.id, who.as_sub()), block_number);
 
 	Some(())
@@ -237,7 +247,7 @@
 				..
 			} => {
 				let (sponsor, collection) = load::<T>(*collection_id)?;
-				withdraw_set_token_property(
+				withdraw_set_existing_token_property(
 					&collection,
 					&T::CrossAccountId::from_sub(who.clone()),
 					token_id,
modifiedruntime/tests/Cargo.tomldiffbeforeafterboth
--- a/runtime/tests/Cargo.toml
+++ b/runtime/tests/Cargo.toml
@@ -5,6 +5,7 @@
 
 [features]
 default = ['refungible']
+tests = ['pallet-common/tests']
 
 refungible = []
 
modifiedruntime/tests/src/tests.rsdiffbeforeafterboth
--- a/runtime/tests/src/tests.rs
+++ b/runtime/tests/src/tests.rs
@@ -1737,6 +1737,11 @@
 		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = RuntimeOrigin::signed(1);
+		assert_ok!(Unique::add_collection_admin(
+			origin1.clone(),
+			collection_id,
+			account(1)
+		));
 
 		let data = default_nft_data();
 		create_test_item(collection_id, &data.into());
@@ -2610,3 +2615,67 @@
 		));
 	});
 }
+
+mod check_token_permissions {
+	use super::*;
+	use frame_support::once_cell::sync::Lazy;
+	use pallet_common::LazyValue;
+	use sp_runtime::DispatchError;
+
+	fn test<FTE: FnOnce() -> bool>(
+		i: usize,
+		test_case: &pallet_common::tests::TestCase,
+		check_token_existence: &mut LazyValue<bool, FTE>,
+	) {
+		let collection_admin = test_case.collection_admin;
+		let mut is_collection_admin = LazyValue::new(|| test_case.is_collection_admin);
+		let token_owner = test_case.token_owner;
+		let mut is_token_owner = LazyValue::new(|| Ok(test_case.is_token_owner));
+		let is_no_permission = test_case.no_permission;
+
+		let result = pallet_common::tests::check_token_permissions::<Test, _, _, FTE>(
+			collection_admin,
+			token_owner,
+			&mut is_collection_admin,
+			&mut is_token_owner,
+			check_token_existence,
+		);
+
+		if is_no_permission {
+			assert!(
+				result.is_err(),
+				"{i}: {test_case:?}, token_exist: {}",
+				check_token_existence.value()
+			);
+			assert_err!(result, pallet_common::Error::<Test>::NoPermission,);
+		} else if check_token_existence.has_value() && !check_token_existence.value() {
+			assert!(
+				result.is_err(),
+				"{i}: {test_case:?}, token_exist: {}",
+				check_token_existence.value()
+			);
+			assert_err!(result, pallet_common::Error::<Test>::TokenNotFound,);
+		}
+	}
+
+	#[test]
+	fn no_permission_only() {
+		new_test_ext().execute_with(|| {
+			let mut check_token_existence = LazyValue::new(|| true);
+			for (i, row) in pallet_common::tests::table.iter().enumerate() {
+				test(i, row, &mut check_token_existence);
+			}
+		});
+	}
+
+	#[test]
+	fn no_permission_and_token_not_found() {
+		new_test_ext().execute_with(|| {
+			for (i, row) in pallet_common::tests::table.iter().enumerate() {
+				// This is inside the loop to keep track of whether the lambda was called
+				let mut check_token_existence = LazyValue::new(|| false);
+				test(i, row, &mut check_token_existence);
+			}
+		});
+	}
+}
modifiedtests/src/createMultipleItemsEx.test.tsdiffbeforeafterboth
--- a/tests/src/createMultipleItemsEx.test.ts
+++ b/tests/src/createMultipleItemsEx.test.ts
@@ -195,7 +195,7 @@
       description: 'descr',
       tokenPrefix: 'COL',
       tokenPropertyPermissions: [
-        {key: 'k', permission: {tokenOwner: true, mutable: false, collectionAdmin: false}},
+        {key: 'k', permission: {tokenOwner: false, mutable: false, collectionAdmin: true}},
       ],
     });
 
modifiedtests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth
--- a/tests/src/eth/collectionSponsoring.test.ts
+++ b/tests/src/eth/collectionSponsoring.test.ts
@@ -17,6 +17,7 @@
 import {IKeyringPair} from '@polkadot/types/types';
 import {Pallets, requirePalletsOrSkip, usingPlaygrounds} from '../util/index';
 import {itEth, expect} from './util';
+import {CollectionLimitField, TokenPermissionField} from './util/playgrounds/types';
 
 describe('evm nft collection sponsoring', () => {
   let donor: IKeyringPair;
@@ -138,8 +139,7 @@
       expect(sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsorEth, true));
 
       // Create user with no balance:
-      const user = helper.eth.createAccount();
-      const userCross = helper.ethCrossAccount.fromAddress(user);
+      const user = helper.ethCrossAccount.createAccount();
       const nextTokenId = await collectionEvm.methods.nextTokenId().call();
       expect(nextTokenId).to.be.equal('1');
 
@@ -149,20 +149,29 @@
       expect(oldPermissions.access).to.be.equal('Normal');
 
       await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});
-      await collectionEvm.methods.addToCollectionAllowListCross(userCross).send({from: owner});
+      await collectionEvm.methods.addToCollectionAllowListCross(user).send({from: owner});
       await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});
+      await collectionEvm.methods.setCollectionLimit({field: CollectionLimitField.SponsoredDataRateLimit, value: {status: true, value: 30}}).send();
 
       const newPermissions = (await collectionSub.getData())!.raw.permissions;
       expect(newPermissions.mintMode).to.be.true;
       expect(newPermissions.access).to.be.equal('AllowList');
 
+      // Set token permissions
+      await collectionEvm.methods.setTokenPropertyPermissions([
+        ['key', [
+          [TokenPermissionField.TokenOwner, true],
+        ],
+        ],
+      ]).send({from: owner});
+
       const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
       const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));
-      const userBalanceBefore =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
+      const userBalanceBefore =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user.eth));
 
       // User can mint token without balance:
       {
-        const result = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});
+        const result = await collectionEvm.methods.mintCross(user, [{key: 'key', value: Buffer.from('Value')}]).send({from: user.eth});
         const event = helper.eth.normalizeEvents(result.events)
           .find(event => event.event === 'Transfer');
 
@@ -171,22 +180,102 @@
           event: 'Transfer',
           args: {
             from: '0x0000000000000000000000000000000000000000',
-            to: user,
+            to: user.eth,
             tokenId: '1',
           },
         });
 
+        // await collectionEvm.methods.setProperties(1, [{key: 'key', value: Buffer.from('Value1')}]).send({from: user.eth});
+
         const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
         const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));
-        const userBalanceAfter =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
+        const userBalanceAfter =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user.eth));
 
-        expect(await collectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+        expect(await collectionEvm.methods.properties(nextTokenId, []).call())
+          .to.be.like([
+            [
+              'key',
+              '0x' + Buffer.from('Value').toString('hex'),
+            ],
+          ]);
         expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);
         expect(userBalanceAfter).to.be.eq(userBalanceBefore);
         expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;
       }
     }));
 
+  itEth('Can sponsor [set token properties] via access list', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const sponsorEth = await helper.eth.createAccountWithBalance(donor);
+    const sponsorCrossEth = helper.ethCrossAccount.fromAddress(sponsorEth);
+
+    const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Sponsor collection', '1', '1', '');
+    const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner, false);
+
+    // Set collection sponsor:
+    await collectionEvm.methods.setCollectionSponsorCross(sponsorCrossEth).send({from: owner});
+
+    // Sponsor can confirm sponsorship:
+    await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsorEth});
+
+    // Create user with no balance:
+    const user = helper.ethCrossAccount.createAccount();
+    const nextTokenId = await collectionEvm.methods.nextTokenId().call();
+    expect(nextTokenId).to.be.equal('1');
+
+    // Set collection permissions:
+    await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});
+    await collectionEvm.methods.addToCollectionAllowListCross(user).send({from: owner});
+    await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});
+    await collectionEvm.methods.setCollectionLimit({field: CollectionLimitField.SponsoredDataRateLimit, value: {status: true, value: 30}}).send();
+
+    // Set token permissions
+    await collectionEvm.methods.setTokenPropertyPermissions([
+      ['key', [
+        [TokenPermissionField.TokenOwner, true],
+      ],
+      ],
+    ]).send({from: owner});
+
+    const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+    const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));
+    const userBalanceBefore =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user.eth));
+
+    // User can mint token without balance:
+    {
+      const result = await collectionEvm.methods.mintCross(user, []).send({from: user.eth});
+      const event = helper.eth.normalizeEvents(result.events)
+        .find(event => event.event === 'Transfer');
+
+      expect(event).to.be.deep.equal({
+        address: collectionAddress,
+        event: 'Transfer',
+        args: {
+          from: '0x0000000000000000000000000000000000000000',
+          to: user.eth,
+          tokenId: '1',
+        },
+      });
+
+      await collectionEvm.methods.setProperties(1, [{key: 'key', value: Buffer.from('Value')}]).send({from: user.eth});
+
+      const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+      const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));
+      const userBalanceAfter =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user.eth));
+
+      expect(await collectionEvm.methods.properties(nextTokenId, []).call())
+        .to.be.like([
+          [
+            'key',
+            '0x' + Buffer.from('Value').toString('hex'),
+          ],
+        ]);
+      expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);
+      expect(userBalanceAfter).to.be.eq(userBalanceBefore);
+      expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;
+    }
+  });
+
   // TODO: Temprorary off. Need refactor
   // itWeb3('Sponsoring collection from substrate address via access list', async ({api, web3, privateKeyWrapper}) => {
   //   const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
@@ -456,6 +545,15 @@
       expect(newPermissions.mintMode).to.be.true;
       expect(newPermissions.access).to.be.equal('AllowList');
 
+      // Set token permissions
+      await collectionEvm.methods.setTokenPropertyPermissions([
+        ['URI', [
+          [TokenPermissionField.TokenOwner, true],
+          [TokenPermissionField.CollectionAdmin, true],
+        ],
+        ],
+      ]).send({from: owner});
+
       const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
       const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));
       const userBalanceBefore =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
@@ -623,6 +721,15 @@
     await collectionEvm.methods.addToCollectionAllowListCross(userCross).send({from: owner});
     await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});
 
+    // Set token permissions
+    await collectionEvm.methods.setTokenPropertyPermissions([
+      ['URI', [
+        [TokenPermissionField.TokenOwner, true],
+        [TokenPermissionField.CollectionAdmin, true],
+      ],
+      ],
+    ]).send({from: owner});
+
     const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
     const sponsorBalanceBefore = await helper.balance.getSubstrate(sponsor.address);
     const userBalanceBefore =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
modifiedtests/src/eth/tokenProperties.test.tsdiffbeforeafterboth
--- a/tests/src/eth/tokenProperties.test.ts
+++ b/tests/src/eth/tokenProperties.test.ts
@@ -553,6 +553,63 @@
         ]).call({from: owner})).to.be.rejectedWith('NoPermission');
       }
     }));
+
+  [
+    {mode: 'nft' as const, requiredPallets: []},
+    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+  ].map(testCase =>
+    itEth.ifWithPallets(`[${testCase.mode}] Can't be multiple set/read for non-existent token`, testCase.requiredPallets, async({helper}) => {
+      const caller = await helper.eth.createAccountWithBalance(donor);
+
+      const properties = Array(5).fill(0).map((_, i) => { return {key: `key_${i}`, value: Buffer.from(`value_${i}`)}; });
+      const permissions: ITokenPropertyPermission[] = properties.map(p => { return {key: p.key, permission: {tokenOwner: true,
+        collectionAdmin: true,
+        mutable: true}}; });
+
+      const collection = await helper[testCase.mode].mintCollection(alice, {
+        tokenPrefix: 'ethp',
+        tokenPropertyPermissions: permissions,
+      }) as UniqueNFTCollection | UniqueRFTCollection;
+
+      await collection.addAdmin(alice, {Ethereum: caller});
+
+      const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+      const contract = await helper.ethNativeContract.collection(address, testCase.mode, caller);
+
+      await expect(contract.methods.setProperties(1, properties).call({from: caller})).to.be.rejectedWith('TokenNotFound');
+    }));
+
+  [
+    {mode: 'nft' as const, requiredPallets: []},
+    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+  ].map(testCase =>
+    itEth.ifWithPallets(`[${testCase.mode}] Can't be deleted for non-existent token`, testCase.requiredPallets, async({helper}) => {
+      const caller = await helper.eth.createAccountWithBalance(donor);
+      const collection = await helper[testCase.mode].mintCollection(alice, {
+        tokenPropertyPermissions: [{
+          key: 'testKey',
+          permission: {
+            mutable: true,
+            collectionAdmin: true,
+          },
+        },
+        {
+          key: 'testKey_1',
+          permission: {
+            mutable: true,
+            collectionAdmin: true,
+          },
+        }],
+      });
+
+
+      await collection.addAdmin(alice, {Ethereum: caller});
+
+      const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+      const contract = await helper.ethNativeContract.collection(address, testCase.mode, caller);
+
+      await expect(contract.methods.deleteProperties(1, ['testKey', 'testKey_1']).call({from: caller})).to.be.rejectedWith('TokenNotFound');
+    }));
 });
 
 
modifiedtests/src/getPropertiesRpc.test.tsdiffbeforeafterboth
--- a/tests/src/getPropertiesRpc.test.ts
+++ b/tests/src/getPropertiesRpc.test.ts
@@ -120,3 +120,31 @@
     expect(propPermissions).to.be.deep.equal(tokenPropPermissions);
   });
 });
+
+[
+  {mode: 'nft' as const},
+  {mode: 'rft' as const},
+].map(testCase =>
+  describe('negative properties', () => {
+    let alice: IKeyringPair;
+
+    before(async () => {
+      await usingPlaygrounds(async (_, privateKey) => {
+        alice = await privateKey({url: import.meta.url});
+      });
+    });
+
+    itSub(`[${testCase.mode}] set token property for non-existent token`, async ({helper}) => {
+      const collection = await helper[testCase.mode].mintCollection(alice);
+      await collection.setTokenPropertyPermissions(alice, [{key: 'key', permission: {mutable: true, tokenOwner: true, collectionAdmin: true}}]);
+      await expect(collection.setTokenProperties(alice, 1, [{key: 'key', value: 'value'}])).to.be.rejectedWith('common.TokenNotFound');
+      expect(await collection.getTokenProperties(1, ['key'])).to.be.empty;
+    });
+
+    itSub(`[${testCase.mode}] delete token property for non-existent token`, async ({helper}) => {
+      const collection = await helper[testCase.mode].mintCollection(alice);
+      await collection.setTokenPropertyPermissions(alice, [{key: 'key', permission: {mutable: true, tokenOwner: true, collectionAdmin: true}}]);
+      await expect(collection.deleteTokenProperties(alice, 1, ['key'])).to.be.rejectedWith('common.TokenNotFound');
+      expect(await collection.getTokenProperties(1, ['key'])).to.be.empty;
+    });
+  }));
\ No newline at end of file
modifiedtests/src/nesting/tokenProperties.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/tokenProperties.test.ts
+++ b/tests/src/nesting/tokenProperties.test.ts
@@ -448,6 +448,29 @@
       expectedConsumedSpaceDiff = sizeOfProperty(biggerProp) - sizeOfProperty(smallerProp);
       expect(consumedSpace).to.be.equal(sizeOfProperty(biggerProp) - expectedConsumedSpaceDiff);
     }));
+
+  itSub('Set sponsored properties', async({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {tokenPropertyPermissions: [{key: 'k', permission: {tokenOwner: true}}]});
+
+    await collection.setSponsor(alice, alice.address);
+    await collection.confirmSponsorship(alice);
+    await collection.setPermissions(alice, {access: 'AllowList', mintMode: true});
+    await collection.addToAllowList(alice, {Substrate: bob.address});
+    await collection.setLimits(alice, {sponsoredDataRateLimit: {blocks: 30}});
+
+    const token = await collection.mintToken(alice, {Substrate: bob.address});
+
+    const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);
+    const bobBalanceBefore = await helper.balance.getSubstrate(bob.address);
+
+    await token.setProperties(bob, [{key: 'k', value: 'val'}]);
+
+    const aliceBalanceAfter = await helper.balance.getSubstrate(alice.address);
+    const bobBalanceAfter = await helper.balance.getSubstrate(bob.address);
+
+    expect(bobBalanceAfter).to.be.equal(bobBalanceBefore);
+    expect(aliceBalanceBefore > aliceBalanceAfter).to.be.true;
+  });
 });
 
 describe('Negative Integration Test: Token Properties', () => {
@@ -475,6 +498,27 @@
     });
   });
 
+  [
+    {mode: 'nft' as const, requiredPallets: [Pallets.NFT]},
+    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+  ].map(testCase =>
+    itSub.ifWithPallets(`Forbids adding/deleting properties of a token if token doesn't exist (${testCase.mode.toLocaleUpperCase})`, testCase.requiredPallets, async({helper}) => {
+      const collection = await helper[testCase.mode].mintCollection(alice, {
+        tokenPropertyPermissions: constitution.slice(0, 1).map(({permission}) => ({key: '1', permission})),
+      });
+      const nonExistentToken = collection.getTokenObject(1);
+
+      await expect(
+        nonExistentToken.setProperties(alice, [{key: '1', value: 'Serotonin increase'}]),
+        'on expecting failure whilst adding a property by alice',
+      ).to.be.rejectedWith(/common\.TokenNotFound/);
+
+      await expect(
+        nonExistentToken.deleteProperties(alice, ['1']),
+        'on expecting failure whilst deleting a property by alice',
+      ).to.be.rejectedWith(/common\.TokenNotFound/);
+    }));
+
   async function mintCollectionWithAllPermissionsAndToken(helper: UniqueHelper, mode: 'NFT' | 'RFT'): Promise<[UniqueNFToken | UniqueRFToken, bigint]> {
     const collection = await (mode == 'NFT' ? helper.nft : helper.rft).mintCollection(alice, {
       tokenPropertyPermissions: constitution.map(({permission}, i) => ({key: `${i+1}`, permission})),