git.delta.rocks / unique-network / refs/commits / 44071b633884

difftreelog

refactor use type-safe propertywriter to set/delete properties

Daniel Shiposha2023-09-30parent: #d2c9363.patch.diff
in: master

12 files changed

modifiedpallets/balances-adapter/src/common.rsdiffbeforeafterboth
--- a/pallets/balances-adapter/src/common.rs
+++ b/pallets/balances-adapter/src/common.rs
@@ -172,6 +172,20 @@
 		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
 	}
 
+	fn get_token_properties_map(&self, _token_id: TokenId) -> up_data_structs::TokenProperties {
+		// No token properties are defined on fungibles
+		up_data_structs::TokenProperties::new()
+	}
+
+	fn set_token_properties_map(&self, _token_id: TokenId, _map: up_data_structs::TokenProperties) {
+		// No token properties are defined on fungibles
+	}
+
+	fn properties_exist(&self, _token: TokenId) -> bool {
+		// No token properties are defined on fungibles
+		false
+	}
+
 	fn set_token_property_permissions(
 		&self,
 		_sender: &<T>::CrossAccountId,
@@ -277,6 +291,15 @@
 		Err(up_data_structs::TokenOwnerError::MultipleOwners)
 	}
 
+	fn check_token_indirect_owner(
+		&self,
+		_token: TokenId,
+		_maybe_owner: &<T>::CrossAccountId,
+		_nesting_budget: &dyn up_data_structs::budget::Budget,
+	) -> Result<bool, frame_support::sp_runtime::DispatchError> {
+		Ok(false)
+	}
+
 	fn token_owners(&self, _token: TokenId) -> Vec<<T>::CrossAccountId> {
 		vec![]
 	}
modifiedpallets/common/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -22,8 +22,9 @@
 use frame_benchmarking::{benchmarks, account};
 use up_data_structs::{
 	CollectionMode, CreateCollectionData, CollectionId, Property, PropertyKey, PropertyValue,
-	CollectionPermissions, NestingPermissions, AccessMode, MAX_COLLECTION_NAME_LENGTH,
-	MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH, MAX_PROPERTIES_PER_ITEM,
+	CollectionPermissions, NestingPermissions, AccessMode, PropertiesPermissionMap,
+	MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
+	MAX_PROPERTIES_PER_ITEM,
 };
 use frame_support::{
 	traits::{Get, fungible::Balanced, Imbalance, tokens::Precision},
@@ -123,6 +124,16 @@
 	)
 }
 
+pub fn load_is_admin_and_property_permissions<T: Config>(
+	collection: &CollectionHandle<T>,
+	sender: &T::CrossAccountId,
+) -> (bool, PropertiesPermissionMap) {
+	(
+		collection.is_owner_or_admin(sender),
+		<Pallet<T>>::property_permissions(collection.id),
+	)
+}
+
 /// Helper macros, which handles all benchmarking preparation in semi-declarative way
 ///
 /// `name` is a substrate account
@@ -215,4 +226,12 @@
 		assert_eq!(collection_handle.permissions.access(), AccessMode::AllowList);
 
 	}: {collection_handle.check_allowlist(&sender)?;}
+
+	init_token_properties_common {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			sender: sub;
+			sender: cross_from_sub(sender);
+		};
+	}: {load_is_admin_and_property_permissions(&collection, &sender);}
 }
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -56,6 +56,7 @@
 use core::{
 	ops::{Deref, DerefMut},
 	slice::from_ref,
+	marker::PhantomData,
 };
 use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
 use sp_std::vec::Vec;
@@ -97,6 +98,9 @@
 pub mod helpers;
 #[allow(missing_docs)]
 pub mod weights;
+
+use weights::WeightInfo;
+
 /// Weight info.
 pub type SelfWeightOf<T> = <T as Config>::WeightInfo;
 
@@ -864,19 +868,7 @@
 		QueryKind = OptionQuery,
 	>;
 }
-
-/// 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>,
@@ -892,19 +884,33 @@
 		}
 	}
 
-	/// Get the value. If it call furst time the value will be initialized.
+	/// Get the value. If it is called the first 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.compute_value_if_not_already();
+		self.value.as_ref().unwrap()
+	}
 
-		self.value.as_ref().unwrap()
+	/// Get the value. If it is called the first time, the value will be initialized.
+	pub fn value_mut(&mut self) -> &mut T {
+		self.compute_value_if_not_already();
+		self.value.as_mut().unwrap()
 	}
 
-	/// Is value initialized.
+	fn into_inner(mut self) -> T {
+		self.compute_value_if_not_already();
+		self.value.unwrap()
+	}
+
+	/// Is value initialized?
 	pub fn has_value(&self) -> bool {
 		self.value.is_some()
 	}
+
+	fn compute_value_if_not_already(&mut self) {
+		if self.value.is_none() {
+			self.value = Some(self.f.take().unwrap()())
+		}
+	}
 }
 
 fn check_token_permissions<T, FCA, FTO, FTE>(
@@ -926,10 +932,19 @@
 		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);
+	let token_exist_due_to_owner_check_success =
+		is_token_owner.has_value() && (*is_token_owner.value())?;
+
+	// If the token owner check has occurred and succeeded,
+	// we know the token exists (otherwise, the owner check must fail).
+	if !token_exist_due_to_owner_check_success {
+		// If the token owner check didn't occur,
+		// we must check the token's existence ourselves.
+		if !is_token_exist.value() {
+			fail!(<Error<T>>::TokenNotFound);
+		}
 	}
+
 	Ok(())
 }
 
@@ -1312,92 +1327,6 @@
 		Ok(())
 	}
 
-	/// A batch operation to add, edit or remove properties for a token.
-	/// It sets or removes a token's properties according to
-	/// `properties_updates` contents:
-	/// * 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)`.
-	///
-	/// 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.
-	///
-	/// 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.
-	#[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>)>,
-		mut stored_properties: TokenProperties,
-		is_token_owner: &mut LazyValue<Result<bool, DispatchError>, FTO>,
-		set_token_properties: impl FnOnce(TokenProperties),
-		log: evm_coder::ethereum::Log,
-	) -> DispatchResult
-	where
-		FTO: FnOnce() -> Result<bool, DispatchError>,
-		FTE: FnOnce() -> bool,
-	{
-		let mut is_collection_admin = LazyValue::new(|| collection.is_owner_or_admin(sender));
-		let mut permissions = LazyValue::new(|| Self::property_permissions(collection.id));
-
-		let mut changed = false;
-		for (key, value) in properties_updates {
-			let permission = permissions
-				.value()
-				.get(&key)
-				.cloned()
-				.unwrap_or_else(PropertyPermission::none);
-
-			let property_exists = stored_properties.get(&key).is_some();
-
-			match permission {
-				PropertyPermission { mutable: false, .. } if property_exists => {
-					return Err(<Error<T>>::NoPermission.into());
-				}
-
-				PropertyPermission {
-					collection_admin,
-					token_owner,
-					..
-				} => check_token_permissions::<T, _, FTO, FTE>(
-					collection_admin,
-					token_owner,
-					&mut is_collection_admin,
-					is_token_owner,
-					is_token_exist,
-				)?,
-			}
-
-			match value {
-				Some(value) => {
-					stored_properties
-						.try_set(key.clone(), value)
-						.map_err(<Error<T>>::from)?;
-
-					Self::deposit_event(Event::TokenPropertySet(collection.id, token_id, key));
-				}
-				None => {
-					stored_properties.remove(&key).map_err(<Error<T>>::from)?;
-
-					Self::deposit_event(Event::TokenPropertyDeleted(collection.id, token_id, key));
-				}
-			}
-
-			changed = true;
-		}
-
-		if changed {
-			<PalletEvm<T>>::deposit_log(log);
-			set_token_properties(stored_properties);
-		}
-
-		Ok(())
-	}
-
 	/// Sets or unsets the approval of a given operator.
 	///
 	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.
@@ -2166,6 +2095,22 @@
 		budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo;
 
+	/// Get token properties raw map.
+	///
+	/// * `token_id` - The token which properties are needed.
+	fn get_token_properties_map(&self, token_id: TokenId) -> TokenProperties;
+
+	/// Set token properties raw map.
+	///
+	/// * `token_id` - The token for which the properties are being set.
+	/// * `map` - The raw map containing the token's properties.
+	fn set_token_properties_map(&self, token_id: TokenId, map: TokenProperties);
+
+	/// Whether the given token has properties.
+	///
+	/// * `token_id` - The token in question.
+	fn properties_exist(&self, token: TokenId) -> bool;
+
 	/// Set token property permissions.
 	///
 	/// * `sender` - Must be either the owner of the token or its admin.
@@ -2309,6 +2254,18 @@
 	/// * `token` - The token for which you need to find out the owner.
 	fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;
 
+	/// Checks if the `maybe_owner` is the indirect owner of the `token`.
+	///
+	/// * `token` - Id token to check.
+	/// * `maybe_owner` - The account to check.
+	/// * `nesting_budget` - A budget that can be spent on nesting tokens.
+	fn check_token_indirect_owner(
+		&self,
+		token: TokenId,
+		maybe_owner: &T::CrossAccountId,
+		nesting_budget: &dyn Budget,
+	) -> Result<bool, DispatchError>;
+
 	/// Returns 10 tokens owners in no particular order.
 	///
 	/// * `token` - The token for which you need to find out the owners.
@@ -2420,6 +2377,348 @@
 	}
 }
 
+/// A marker structure that enables the writer implementation
+/// to provide the interface to write properties to **newly created** tokens.
+pub struct NewTokenPropertyWriter;
+
+/// A marker structure that enables the writer implementation
+/// to provide the interface to write properties to **already existing** tokens.
+pub struct ExistingTokenPropertyWriter;
+
+/// The type-safe interface for writing properties (setting or deleting) to tokens.
+/// It has two distinct implementations for newly created tokens and existing ones.
+///
+/// This type utilizes the lazy evaluation to avoid repeating the computation
+/// of several performance-heavy or PoV-heavy tasks,
+/// such as checking the indirect ownership or reading the token property permissions.
+pub struct PropertyWriter<
+	'a,
+	T,
+	Handle,
+	WriterVariant,
+	FIsAdmin,
+	FPropertyPermissions,
+	FCheckTokenExist,
+	FGetProperties,
+> where
+	T: Config,
+	FIsAdmin: FnOnce() -> bool,
+	FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,
+{
+	collection: &'a Handle,
+	is_collection_admin: LazyValue<bool, FIsAdmin>,
+	property_permissions: LazyValue<PropertiesPermissionMap, FPropertyPermissions>,
+	check_token_exist: FCheckTokenExist,
+	get_properties: FGetProperties,
+	_phantom: PhantomData<(T, WriterVariant)>,
+}
+
+impl<'a, T, Handle, FIsAdmin, FPropertyPermissions, FCheckTokenExist, FGetProperties>
+	PropertyWriter<
+		'a,
+		T,
+		Handle,
+		NewTokenPropertyWriter,
+		FIsAdmin,
+		FPropertyPermissions,
+		FCheckTokenExist,
+		FGetProperties,
+	> where
+	T: Config,
+	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,
+	FIsAdmin: FnOnce() -> bool,
+	FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,
+	FCheckTokenExist: Copy + FnOnce(TokenId) -> bool,
+	FGetProperties: Copy + FnOnce(TokenId) -> TokenProperties,
+{
+	/// A function to write properties to a **newly created** token.
+	pub fn write_token_properties(
+		&mut self,
+		mint_target_is_sender: bool,
+		token_id: TokenId,
+		properties_updates: impl Iterator<Item = Property>,
+		log: evm_coder::ethereum::Log,
+	) -> DispatchResult {
+		self.internal_write_token_properties(
+			token_id,
+			properties_updates.map(|p| (p.key, Some(p.value))),
+			|_| Ok(mint_target_is_sender),
+			log,
+		)
+	}
+}
+
+impl<'a, T, Handle, FIsAdmin, FPropertyPermissions, FCheckTokenExist, FGetProperties>
+	PropertyWriter<
+		'a,
+		T,
+		Handle,
+		ExistingTokenPropertyWriter,
+		FIsAdmin,
+		FPropertyPermissions,
+		FCheckTokenExist,
+		FGetProperties,
+	> where
+	T: Config,
+	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,
+	FIsAdmin: FnOnce() -> bool,
+	FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,
+	FCheckTokenExist: Copy + FnOnce(TokenId) -> bool,
+	FGetProperties: Copy + FnOnce(TokenId) -> TokenProperties,
+{
+	/// A function to write properties to an **already existing** token.
+	pub fn write_token_properties(
+		&mut self,
+		sender: &T::CrossAccountId,
+		token_id: TokenId,
+		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
+		nesting_budget: &dyn Budget,
+		log: evm_coder::ethereum::Log,
+	) -> DispatchResult {
+		self.internal_write_token_properties(
+			token_id,
+			properties_updates,
+			|collection| collection.check_token_indirect_owner(token_id, sender, nesting_budget),
+			log,
+		)
+	}
+}
+
+impl<
+		'a,
+		T,
+		Handle,
+		WriterVariant,
+		FIsAdmin,
+		FPropertyPermissions,
+		FCheckTokenExist,
+		FGetProperties,
+	>
+	PropertyWriter<
+		'a,
+		T,
+		Handle,
+		WriterVariant,
+		FIsAdmin,
+		FPropertyPermissions,
+		FCheckTokenExist,
+		FGetProperties,
+	> where
+	T: Config,
+	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,
+	FIsAdmin: FnOnce() -> bool,
+	FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,
+	FCheckTokenExist: Copy + FnOnce(TokenId) -> bool,
+	FGetProperties: Copy + FnOnce(TokenId) -> TokenProperties,
+{
+	fn internal_write_token_properties<FCheckTokenOwner>(
+		&mut self,
+		token_id: TokenId,
+		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
+		check_token_owner: FCheckTokenOwner,
+		log: evm_coder::ethereum::Log,
+	) -> DispatchResult
+	where
+		FCheckTokenOwner: FnOnce(&Handle) -> Result<bool, DispatchError>,
+	{
+		let get_properties = self.get_properties;
+		let mut stored_properties = LazyValue::new(move || get_properties(token_id));
+
+		let mut is_token_owner = LazyValue::new(|| check_token_owner(self.collection));
+
+		let check_token_exist = self.check_token_exist;
+		let mut is_token_exist = LazyValue::new(move || check_token_exist(token_id));
+
+		for (key, value) in properties_updates {
+			let permission = self
+				.property_permissions
+				.value()
+				.get(&key)
+				.cloned()
+				.unwrap_or_else(PropertyPermission::none);
+
+			match permission {
+				PropertyPermission { mutable: false, .. }
+					if stored_properties.value().get(&key).is_some() =>
+				{
+					return Err(<Error<T>>::NoPermission.into());
+				}
+
+				PropertyPermission {
+					collection_admin,
+					token_owner,
+					..
+				} => check_token_permissions::<T, _, _, _>(
+					collection_admin,
+					token_owner,
+					&mut self.is_collection_admin,
+					&mut is_token_owner,
+					&mut is_token_exist,
+				)?,
+			}
+
+			match value {
+				Some(value) => {
+					stored_properties
+						.value_mut()
+						.try_set(key.clone(), value)
+						.map_err(<Error<T>>::from)?;
+
+					<Pallet<T>>::deposit_event(Event::TokenPropertySet(
+						self.collection.id,
+						token_id,
+						key,
+					));
+				}
+				None => {
+					stored_properties
+						.value_mut()
+						.remove(&key)
+						.map_err(<Error<T>>::from)?;
+
+					<Pallet<T>>::deposit_event(Event::TokenPropertyDeleted(
+						self.collection.id,
+						token_id,
+						key,
+					));
+				}
+			}
+		}
+
+		let properties_changed = stored_properties.has_value();
+		if properties_changed {
+			<PalletEvm<T>>::deposit_log(log);
+
+			self.collection
+				.set_token_properties_map(token_id, stored_properties.into_inner());
+		}
+
+		Ok(())
+	}
+}
+
+/// Create a [`PropertyWriter`] for newly created tokens.
+pub fn property_writer_for_new_token<'a, T, Handle>(
+	collection: &'a Handle,
+	sender: &'a T::CrossAccountId,
+) -> PropertyWriter<
+	'a,
+	T,
+	Handle,
+	NewTokenPropertyWriter,
+	impl FnOnce() -> bool + 'a,
+	impl FnOnce() -> PropertiesPermissionMap + 'a,
+	impl Copy + FnOnce(TokenId) -> bool + 'a,
+	impl Copy + FnOnce(TokenId) -> TokenProperties + 'a,
+>
+where
+	T: Config,
+	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,
+{
+	PropertyWriter {
+		collection,
+		is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),
+		property_permissions: LazyValue::new(|| <Pallet<T>>::property_permissions(collection.id)),
+		check_token_exist: |token_id| {
+			debug_assert!(collection.token_exists(token_id));
+			true
+		},
+		get_properties: |token_id| {
+			debug_assert!(!collection.properties_exist(token_id));
+			TokenProperties::new()
+		},
+		_phantom: PhantomData,
+	}
+}
+
+#[cfg(feature = "runtime-benchmarks")]
+/// Create a `PropertyWriter` with preloaded `is_collection_admin` and `property_permissions.
+/// Also:
+/// * it will return `true` for the token ownership check.
+/// * it will return empty stored properties without reading them from the storage.
+pub fn collection_info_loaded_property_writer<T, Handle>(
+	collection: &Handle,
+	is_collection_admin: bool,
+	property_permissions: PropertiesPermissionMap,
+) -> PropertyWriter<
+	T,
+	Handle,
+	NewTokenPropertyWriter,
+	impl FnOnce() -> bool,
+	impl FnOnce() -> PropertiesPermissionMap,
+	impl Copy + FnOnce(TokenId) -> bool,
+	impl Copy + FnOnce(TokenId) -> TokenProperties,
+>
+where
+	T: Config,
+	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,
+{
+	PropertyWriter {
+		collection,
+		is_collection_admin: LazyValue::new(move || is_collection_admin),
+		property_permissions: LazyValue::new(move || property_permissions),
+		check_token_exist: |_token_id| true,
+		get_properties: |_token_id| TokenProperties::new(),
+		_phantom: PhantomData,
+	}
+}
+
+/// Create a [`PropertyWriter`] for already existing tokens.
+pub fn property_writer_for_existing_token<'a, T, Handle>(
+	collection: &'a Handle,
+	sender: &'a T::CrossAccountId,
+) -> PropertyWriter<
+	'a,
+	T,
+	Handle,
+	ExistingTokenPropertyWriter,
+	impl FnOnce() -> bool + 'a,
+	impl FnOnce() -> PropertiesPermissionMap + 'a,
+	impl Copy + FnOnce(TokenId) -> bool + 'a,
+	impl Copy + FnOnce(TokenId) -> TokenProperties + 'a,
+>
+where
+	T: Config,
+	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,
+{
+	PropertyWriter {
+		collection,
+		is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),
+		property_permissions: LazyValue::new(|| <Pallet<T>>::property_permissions(collection.id)),
+		check_token_exist: |token_id| collection.token_exists(token_id),
+		get_properties: |token_id| collection.get_token_properties_map(token_id),
+		_phantom: PhantomData,
+	}
+}
+
+/// Computes the weight delta for newly created tokens with properties.
+/// * `properties_nums` - The properties num of each created token.
+/// * `init_token_properties` - The function to obtain the weight from a token's properties num.
+pub fn init_token_properties_delta<T: Config, I: Fn(u32) -> Weight>(
+	properties_nums: impl Iterator<Item = u32>,
+	init_token_properties: I,
+) -> Weight {
+	let mut delta = properties_nums
+		.filter_map(|properties_num| {
+			if properties_num > 0 {
+				Some(init_token_properties(properties_num))
+			} else {
+				None
+			}
+		})
+		.fold(Weight::zero(), |a, b| a.saturating_add(b));
+
+	// If at least once the `init_token_properties` was called,
+	// it means at least one newly created token has properties.
+	// Becuase of that, some common collection data also was loaded and we need to add this weight.
+	// However, these common data was loaded only once which is guaranteed by the `PropertyWriter`.
+	if !delta.is_zero() {
+		delta = delta.saturating_add(<SelfWeightOf<T>>::init_token_properties_common())
+	}
+
+	delta
+}
+
 #[cfg(any(feature = "tests", test))]
 #[allow(missing_docs)]
 pub mod tests {
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -25,7 +25,7 @@
 	weights::WeightInfo as _, SelfWeightOf as PalletCommonWeightOf,
 };
 use pallet_structure::Error as StructureError;
-use sp_runtime::ArithmeticError;
+use sp_runtime::{ArithmeticError, DispatchError};
 use sp_std::{vec::Vec, vec};
 use up_data_structs::{Property, PropertyKey, PropertyValue, PropertyKeyPermission};
 
@@ -364,6 +364,20 @@
 		fail!(<Error<T>>::SettingPropertiesNotAllowed)
 	}
 
+	fn get_token_properties_map(&self, _token_id: TokenId) -> up_data_structs::TokenProperties {
+		// No token properties are defined on fungibles
+		up_data_structs::TokenProperties::new()
+	}
+
+	fn set_token_properties_map(&self, _token_id: TokenId, _map: up_data_structs::TokenProperties) {
+		// No token properties are defined on fungibles
+	}
+
+	fn properties_exist(&self, _token: TokenId) -> bool {
+		// No token properties are defined on fungibles
+		false
+	}
+
 	fn check_nesting(
 		&self,
 		_sender: <T>::CrossAccountId,
@@ -402,6 +416,15 @@
 		Err(TokenOwnerError::MultipleOwners)
 	}
 
+	fn check_token_indirect_owner(
+		&self,
+		_token: TokenId,
+		_maybe_owner: &T::CrossAccountId,
+		_nesting_budget: &dyn Budget,
+	) -> Result<bool, DispatchError> {
+		Ok(false)
+	}
+
 	/// Returns 10 tokens owners in no particular order.
 	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {
 		<Pallet<T>>::token_owners(self.id, token).unwrap_or_default()
modifiedpallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -20,7 +20,9 @@
 use frame_benchmarking::{benchmarks, account};
 use pallet_common::{
 	bench_init,
-	benchmarking::{create_collection_raw, property_key, property_value},
+	benchmarking::{
+		create_collection_raw, property_key, property_value, load_is_admin_and_property_permissions,
+	},
 	CommonCollectionOperations,
 };
 use sp_std::prelude::*;
@@ -198,14 +200,15 @@
 			value: property_value(),
 		}).collect::<Vec<_>>();
 		let item = create_max_item(&collection, &owner, owner.clone())?;
-	}: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), SetPropertyMode::ExistingToken, &Unlimited)?}
+	}: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), &Unlimited)?}
 
-	reset_token_properties {
+	init_token_properties {
 		let b in 0..MAX_PROPERTIES_PER_ITEM;
 		bench_init!{
 			owner: sub; collection: collection(owner);
 			owner: cross_from_sub;
 		};
+
 		let perms = (0..b).map(|k| PropertyKeyPermission {
 			key: property_key(k as usize),
 			permission: PropertyPermission {
@@ -220,8 +223,26 @@
 			value: property_value(),
 		}).collect::<Vec<_>>();
 		let item = create_max_item(&collection, &owner, owner.clone())?;
-	}: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), SetPropertyMode::NewToken { mint_target_is_sender: true }, &Unlimited)?}
 
+		let (is_collection_admin, property_permissions) = load_is_admin_and_property_permissions(&collection, &owner);
+	}: {
+		let mut property_writer = pallet_common::collection_info_loaded_property_writer(
+			&collection,
+			is_collection_admin,
+			property_permissions,
+		);
+
+		property_writer.write_token_properties(
+			true,
+			item,
+			props.into_iter(),
+			crate::erc::ERC721TokenEvent::TokenChanged {
+				token_id: item.into(),
+			}
+			.to_log(T::ContractAddress::get()),
+		)?
+	}
+
 	delete_token_properties {
 		let b in 0..MAX_PROPERTIES_PER_ITEM;
 		bench_init!{
@@ -242,7 +263,7 @@
 			value: property_value(),
 		}).collect::<Vec<_>>();
 		let item = create_max_item(&collection, &owner, owner.clone())?;
-		<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), SetPropertyMode::ExistingToken, &Unlimited)?;
+		<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), &Unlimited)?;
 		let to_delete = (0..b).map(|k| property_key(k as usize)).collect::<Vec<_>>();
 	}: {<Pallet<T>>::delete_token_properties(&collection, &owner, item, to_delete.into_iter(), &Unlimited)?}
 
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -23,49 +23,40 @@
 };
 use pallet_common::{
 	CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
-	weights::WeightInfo as _, SelfWeightOf as PalletCommonWeightOf,
+	weights::WeightInfo as _, SelfWeightOf as PalletCommonWeightOf, init_token_properties_delta,
 };
+use pallet_structure::Pallet as PalletStructure;
 use sp_runtime::DispatchError;
 use sp_std::{vec::Vec, vec};
 
 use crate::{
 	AccountBalance, Allowance, Config, CreateItemData, Error, NonfungibleHandle, Owned, Pallet,
-	SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted,
+	SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted, TokenProperties,
 };
 
 pub struct CommonWeights<T: Config>(PhantomData<T>);
 impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {
 	fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {
 		match data {
-			CreateItemExData::NFT(t) => {
-				<SelfWeightOf<T>>::create_multiple_items_ex(t.len() as u32)
-					+ t.iter()
-						.filter_map(|t| {
-							if t.properties.len() > 0 {
-								Some(<SelfWeightOf<T>>::reset_token_properties(
-									t.properties.len() as u32,
-								))
-							} else {
-								None
-							}
-						})
-						.fold(Weight::zero(), |a, b| a.saturating_add(b))
-			}
+			CreateItemExData::NFT(t) => <SelfWeightOf<T>>::create_multiple_items_ex(t.len() as u32)
+				.saturating_add(init_token_properties_delta::<T, _>(
+					t.iter().map(|t| t.properties.len() as u32),
+					<SelfWeightOf<T>>::init_token_properties,
+				)),
 			_ => Weight::zero(),
 		}
 	}
 
 	fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {
-		<SelfWeightOf<T>>::create_multiple_items(data.len() as u32)
-			+ data
-				.iter()
-				.filter_map(|t| match t {
-					up_data_structs::CreateItemData::NFT(n) if n.properties.len() > 0 => Some(
-						<SelfWeightOf<T>>::reset_token_properties(n.properties.len() as u32),
-					),
-					_ => None,
-				})
-				.fold(Weight::zero(), |a, b| a.saturating_add(b))
+		<SelfWeightOf<T>>::create_multiple_items(data.len() as u32).saturating_add(
+			init_token_properties_delta::<T, _>(
+				data.iter().map(|t| match t {
+					up_data_structs::CreateItemData::NFT(n) => n.properties.len() as u32,
+					_ => 0,
+				}),
+				<SelfWeightOf<T>>::init_token_properties,
+			),
+		)
 	}
 
 	fn burn_item() -> Weight {
@@ -247,7 +238,6 @@
 				&sender,
 				token_id,
 				properties.into_iter(),
-				pallet_common::SetPropertyMode::ExistingToken,
 				nesting_budget,
 			),
 			weight,
@@ -275,6 +265,14 @@
 		)
 	}
 
+	fn get_token_properties_map(&self, token_id: TokenId) -> up_data_structs::TokenProperties {
+		<TokenProperties<T>>::get((self.id, token_id))
+	}
+
+	fn set_token_properties_map(&self, token_id: TokenId, map: up_data_structs::TokenProperties) {
+		<TokenProperties<T>>::set((self.id, token_id), map)
+	}
+
 	fn set_token_property_permissions(
 		&self,
 		sender: &T::CrossAccountId,
@@ -289,6 +287,10 @@
 		)
 	}
 
+	fn properties_exist(&self, token: TokenId) -> bool {
+		<TokenProperties<T>>::contains_key((self.id, token))
+	}
+
 	fn burn_item(
 		&self,
 		sender: T::CrossAccountId,
@@ -459,6 +461,21 @@
 			.ok_or(TokenOwnerError::NotFound)
 	}
 
+	fn check_token_indirect_owner(
+		&self,
+		token: TokenId,
+		maybe_owner: &T::CrossAccountId,
+		nesting_budget: &dyn Budget,
+	) -> Result<bool, DispatchError> {
+		<PalletStructure<T>>::check_indirectly_owned(
+			maybe_owner.clone(),
+			self.id,
+			token,
+			None,
+			nesting_budget,
+		)
+	}
+
 	/// Returns token owners.
 	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {
 		self.token_owner(token).map_or_else(|_| vec![], |t| vec![t])
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -203,7 +203,6 @@
 			&caller,
 			TokenId(token_id),
 			properties.into_iter(),
-			pallet_common::SetPropertyMode::ExistingToken,
 			&nesting_budget,
 		)
 		.map_err(dispatch_to_evm::<T>)
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, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,104	mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey, PropertyValue,105	PropertyKeyPermission, PropertyScope, TrySetProperty, TokenChild, AuxPropertyValue,106	PropertiesPermissionMap, TokenProperties as TokenPropertiesT,107};108use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};109use pallet_common::{110	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,111	eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,112	weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info, SetPropertyMode,113};114use pallet_structure::{Pallet as PalletStructure, Error as StructureError};115use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};116use sp_core::{Get, H160};117use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};118use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};119use core::ops::Deref;120use codec::{Encode, Decode, MaxEncodedLen};121use scale_info::TypeInfo;122123pub use pallet::*;124use weights::WeightInfo;125#[cfg(feature = "runtime-benchmarks")]126pub mod benchmarking;127pub mod common;128pub mod erc;129pub mod weights;130131pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::Config>::CrossAccountId>;132pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;133134/// Token data, stored independently from other data used to describe it135/// for the convenience of database access. Notably contains the owner account address.136#[struct_versioning::versioned(version = 2, upper)]137#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]138pub struct ItemData<CrossAccountId> {139	#[version(..2)]140	pub const_data: BoundedVec<u8, CustomDataLimit>,141142	#[version(..2)]143	pub variable_data: BoundedVec<u8, CustomDataLimit>,144145	pub owner: CrossAccountId,146}147148#[frame_support::pallet]149pub mod pallet {150	use super::*;151	use frame_support::{152		Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,153	};154	use up_data_structs::{CollectionId, TokenId};155	use super::weights::WeightInfo;156157	#[pallet::error]158	pub enum Error<T> {159		/// Not Nonfungible item data used to mint in Nonfungible collection.160		NotNonfungibleDataUsedToMintFungibleCollectionToken,161		/// Used amount > 1 with NFT162		NonfungibleItemsHaveNoAmount,163		/// Unable to burn NFT with children164		CantBurnNftWithChildren,165	}166167	#[pallet::config]168	pub trait Config:169		frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config170	{171		type WeightInfo: WeightInfo;172	}173174	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);175176	#[pallet::pallet]177	#[pallet::storage_version(STORAGE_VERSION)]178	pub struct Pallet<T>(_);179180	/// Total amount of minted tokens in a collection.181	#[pallet::storage]182	pub type TokensMinted<T: Config> =183		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;184185	/// Amount of burnt tokens in a collection.186	#[pallet::storage]187	pub type TokensBurnt<T: Config> =188		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;189190	/// Token data, used to partially describe a token.191	#[pallet::storage]192	pub type TokenData<T: Config> = StorageNMap<193		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),194		Value = ItemData<T::CrossAccountId>,195		QueryKind = OptionQuery,196	>;197198	/// Map of key-value pairs, describing the metadata of a token.199	#[pallet::storage]200	#[pallet::getter(fn token_properties)]201	pub type TokenProperties<T: Config> = StorageNMap<202		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),203		Value = TokenPropertiesT,204		QueryKind = ValueQuery,205	>;206207	/// Custom data of a token that is serialized to bytes,208	/// primarily reserved for on-chain operations,209	/// normally obscured from the external users.210	///211	/// Auxiliary properties are slightly different from212	/// usual [`TokenProperties`] due to an unlimited number213	/// and separately stored and written-to key-value pairs.214	///215	/// Currently unused.216	#[pallet::storage]217	#[pallet::getter(fn token_aux_property)]218	pub type TokenAuxProperties<T: Config> = StorageNMap<219		Key = (220			Key<Twox64Concat, CollectionId>,221			Key<Twox64Concat, TokenId>,222			Key<Twox64Concat, PropertyScope>,223			Key<Twox64Concat, PropertyKey>,224		),225		Value = AuxPropertyValue,226		QueryKind = OptionQuery,227	>;228229	/// Used to enumerate tokens owned by account.230	#[pallet::storage]231	pub type Owned<T: Config> = StorageNMap<232		Key = (233			Key<Twox64Concat, CollectionId>,234			Key<Blake2_128Concat, T::CrossAccountId>,235			Key<Twox64Concat, TokenId>,236		),237		Value = bool,238		QueryKind = ValueQuery,239	>;240241	/// Used to enumerate token's children.242	#[pallet::storage]243	#[pallet::getter(fn token_children)]244	pub type TokenChildren<T: Config> = StorageNMap<245		Key = (246			Key<Twox64Concat, CollectionId>,247			Key<Twox64Concat, TokenId>,248			Key<Twox64Concat, (CollectionId, TokenId)>,249		),250		Value = bool,251		QueryKind = ValueQuery,252	>;253254	/// Amount of tokens owned by an account in a collection.255	#[pallet::storage]256	pub type AccountBalance<T: Config> = StorageNMap<257		Key = (258			Key<Twox64Concat, CollectionId>,259			Key<Blake2_128Concat, T::CrossAccountId>,260		),261		Value = u32,262		QueryKind = ValueQuery,263	>;264265	/// Allowance set by a token owner for another user to perform one of certain transactions on a token.266	#[pallet::storage]267	pub type Allowance<T: Config> = StorageNMap<268		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),269		Value = T::CrossAccountId,270		QueryKind = OptionQuery,271	>;272273	/// Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.274	#[pallet::storage]275	pub type CollectionAllowance<T: Config> = StorageNMap<276		Key = (277			Key<Twox64Concat, CollectionId>,278			Key<Blake2_128Concat, T::CrossAccountId>,279			Key<Blake2_128Concat, T::CrossAccountId>,280		),281		Value = bool,282		QueryKind = ValueQuery,283	>;284285	#[pallet::genesis_config]286	pub struct GenesisConfig<T>(PhantomData<T>);287288	#[cfg(feature = "std")]289	impl<T: Config> Default for GenesisConfig<T> {290		fn default() -> Self {291			Self(Default::default())292		}293	}294295	#[pallet::genesis_build]296	impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {297		fn build(&self) {298			StorageVersion::new(1).put::<Pallet<T>>();299		}300	}301}302303pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);304impl<T: Config> NonfungibleHandle<T> {305	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {306		Self(inner)307	}308	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {309		self.0310	}311	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {312		&mut self.0313	}314}315316impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {317	fn recorder(&self) -> &SubstrateRecorder<T> {318		self.0.recorder()319	}320	fn into_recorder(self) -> SubstrateRecorder<T> {321		self.0.into_recorder()322	}323}324impl<T: Config> Deref for NonfungibleHandle<T> {325	type Target = pallet_common::CollectionHandle<T>;326327	fn deref(&self) -> &Self::Target {328		&self.0329	}330}331332impl<T: Config> Pallet<T> {333	/// Get number of NFT tokens in collection.334	pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {335		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)336	}337338	/// Check that NFT token exists.339	///340	/// - `token`: Token ID.341	pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {342		<TokenData<T>>::contains_key((collection.id, token))343	}344345	/// Set the token property with the scope.346	///347	/// - `property`: Contains key-value pair.348	pub fn set_scoped_token_property(349		collection_id: CollectionId,350		token_id: TokenId,351		scope: PropertyScope,352		property: Property,353	) -> DispatchResult {354		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {355			properties.try_scoped_set(scope, property.key, property.value)356		})357		.map_err(<CommonError<T>>::from)?;358359		Ok(())360	}361362	/// Batch operation to set multiple properties with the same scope.363	pub fn set_scoped_token_properties(364		collection_id: CollectionId,365		token_id: TokenId,366		scope: PropertyScope,367		properties: impl Iterator<Item = Property>,368	) -> DispatchResult {369		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {370			stored_properties.try_scoped_set_from_iter(scope, properties)371		})372		.map_err(<CommonError<T>>::from)?;373374		Ok(())375	}376377	/// Add or edit auxiliary data for the property.378	///379	/// - `f`: function that adds or edits auxiliary data.380	pub fn try_mutate_token_aux_property<R, E>(381		collection_id: CollectionId,382		token_id: TokenId,383		scope: PropertyScope,384		key: PropertyKey,385		f: impl FnOnce(&mut Option<AuxPropertyValue>) -> Result<R, E>,386	) -> Result<R, E> {387		<TokenAuxProperties<T>>::try_mutate((collection_id, token_id, scope, key), f)388	}389390	/// Remove auxiliary data for the property.391	pub fn remove_token_aux_property(392		collection_id: CollectionId,393		token_id: TokenId,394		scope: PropertyScope,395		key: PropertyKey,396	) {397		<TokenAuxProperties<T>>::remove((collection_id, token_id, scope, key));398	}399400	/// Get all auxiliary data in a given scope.401	///402	/// Returns iterator over Property Key - Data pairs.403	pub fn iterate_token_aux_properties(404		collection_id: CollectionId,405		token_id: TokenId,406		scope: PropertyScope,407	) -> impl Iterator<Item = (PropertyKey, AuxPropertyValue)> {408		<TokenAuxProperties<T>>::iter_prefix((collection_id, token_id, scope))409	}410411	/// Get ID of the last minted token412	pub fn current_token_id(collection_id: CollectionId) -> TokenId {413		TokenId(<TokensMinted<T>>::get(collection_id))414	}415}416417// unchecked calls skips any permission checks418impl<T: Config> Pallet<T> {419	/// Create NFT collection420	///421	/// `init_collection` will take non-refundable deposit for collection creation.422	///423	/// - `data`: Contains settings for collection limits and permissions.424	pub fn init_collection(425		owner: T::CrossAccountId,426		payer: T::CrossAccountId,427		data: CreateCollectionData<T::CrossAccountId>,428	) -> Result<CollectionId, DispatchError> {429		<PalletCommon<T>>::init_collection(owner, payer, data)430	}431432	/// Destroy NFT collection433	///434	/// `destroy_collection` will throw error if collection contains any tokens.435	/// Only owner can destroy collection.436	pub fn destroy_collection(437		collection: NonfungibleHandle<T>,438		sender: &T::CrossAccountId,439	) -> DispatchResult {440		let id = collection.id;441442		if Self::collection_has_tokens(id) {443			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());444		}445446		// =========447448		PalletCommon::destroy_collection(collection.0, sender)?;449450		let _ = <TokenData<T>>::clear_prefix((id,), u32::MAX, None);451		let _ = <TokenChildren<T>>::clear_prefix((id,), u32::MAX, None);452		let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);453		<TokensMinted<T>>::remove(id);454		<TokensBurnt<T>>::remove(id);455		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);456		let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);457		let _ = <CollectionAllowance<T>>::clear_prefix((id,), u32::MAX, None);458		Ok(())459	}460461	/// Burn NFT token462	///463	/// `burn` removes `token` from the `collection`, from it's owner and from the parent token464	/// if the token is nested.465	/// Only the owner can `burn` the token. The `token` shouldn't have any nested tokens.466	/// Also removes all corresponding properties and auxiliary properties.467	///468	/// - `token`: Token that should be burned469	/// - `collection`: Collection that contains the token470	pub fn burn(471		collection: &NonfungibleHandle<T>,472		sender: &T::CrossAccountId,473		token: TokenId,474	) -> DispatchResult {475		let token_data =476			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;477		ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);478479		if collection.permissions.access() == AccessMode::AllowList {480			collection.check_allowlist(sender)?;481		}482483		if Self::token_has_children(collection.id, token) {484			return Err(<Error<T>>::CantBurnNftWithChildren.into());485		}486487		let burnt = <TokensBurnt<T>>::get(collection.id)488			.checked_add(1)489			.ok_or(ArithmeticError::Overflow)?;490491		let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))492			.checked_sub(1)493			.ok_or(ArithmeticError::Overflow)?;494495		// =========496497		if balance == 0 {498			<AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));499		} else {500			<AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);501		}502503		<PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);504505		<Owned<T>>::remove((collection.id, &token_data.owner, token));506		<TokensBurnt<T>>::insert(collection.id, burnt);507		<TokenData<T>>::remove((collection.id, token));508		<TokenProperties<T>>::remove((collection.id, token));509		let _ = <TokenAuxProperties<T>>::clear_prefix((collection.id, token), u32::MAX, None);510		let old_spender = <Allowance<T>>::take((collection.id, token));511512		if let Some(old_spender) = old_spender {513			<PalletCommon<T>>::deposit_event(CommonEvent::Approved(514				collection.id,515				token,516				token_data.owner.clone(),517				old_spender,518				0,519			));520		}521522		<PalletEvm<T>>::deposit_log(523			ERC721Events::Transfer {524				from: *token_data.owner.as_eth(),525				to: H160::default(),526				token_id: token.into(),527			}528			.to_log(collection_id_to_address(collection.id)),529		);530		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(531			collection.id,532			token,533			token_data.owner,534			1,535		));536		Ok(())537	}538539	/// Same as [`burn`] but burns all the tokens that are nested in the token first540	///541	/// - `self_budget`: Limit for searching children in depth.542	/// - `breadth_budget`: Limit of breadth of searching children.543	///544	/// [`burn`]: struct.Pallet.html#method.burn545	#[transactional]546	pub fn burn_recursively(547		collection: &NonfungibleHandle<T>,548		sender: &T::CrossAccountId,549		token: TokenId,550		self_budget: &dyn Budget,551		breadth_budget: &dyn Budget,552	) -> DispatchResultWithPostInfo {553		ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);554555		let current_token_account =556			T::CrossTokenAddressMapping::token_to_address(collection.id, token);557558		let mut weight = Weight::zero();559560		// This method is transactional, if user in fact doesn't have permissions to remove token -561		// tokens removed here will be restored after rejected transaction562		for ((collection, token), _) in <TokenChildren<T>>::iter_prefix((collection.id, token)) {563			ensure!(breadth_budget.consume(), <StructureError<T>>::BreadthLimit,);564			let PostDispatchInfo { actual_weight, .. } =565				<PalletStructure<T>>::burn_item_recursively(566					current_token_account.clone(),567					collection,568					token,569					self_budget,570					breadth_budget,571				)?;572			if let Some(actual_weight) = actual_weight {573				weight = weight.saturating_add(actual_weight);574			}575		}576577		Self::burn(collection, sender, token)?;578		DispatchResultWithPostInfo::Ok(PostDispatchInfo {579			actual_weight: Some(weight + <SelfWeightOf<T>>::burn_item()),580			pays_fee: Pays::Yes,581		})582	}583584	/// A batch operation to add, edit or remove properties for a token.585	///586	/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.587	///588	/// All affected properties should have `mutable` permission589	/// to be **deleted** or to be **set more than once**,590	/// and the sender should have permission to edit those properties.591	///592	/// This function fires an event for each property change.593	/// In case of an error, all the changes (including the events) will be reverted594	/// since the function is transactional.595	#[transactional]596	fn modify_token_properties(597		collection: &NonfungibleHandle<T>,598		sender: &T::CrossAccountId,599		token_id: TokenId,600		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,601		mode: SetPropertyMode,602		nesting_budget: &dyn Budget,603	) -> DispatchResult {604		let mut is_token_owner = pallet_common::LazyValue::new(|| {605			if let SetPropertyMode::NewToken {606				mint_target_is_sender,607			} = mode608			{609				return Ok(mint_target_is_sender);610			}611612			let is_owned = <PalletStructure<T>>::check_indirectly_owned(613				sender.clone(),614				collection.id,615				token_id,616				None,617				nesting_budget,618			)?;619620			Ok(is_owned)621		});622623		let is_new_token = matches!(mode, SetPropertyMode::NewToken { .. });624625		let mut is_token_exist = pallet_common::LazyValue::new(|| {626			if is_new_token {627				debug_assert!(Self::token_exists(collection, token_id));628				true629			} else {630				Self::token_exists(collection, token_id)631			}632		});633634		let stored_properties = if is_new_token {635			debug_assert!(!<TokenProperties<T>>::contains_key((636				collection.id,637				token_id638			)));639			TokenPropertiesT::new()640		} else {641			<TokenProperties<T>>::get((collection.id, token_id))642		};643644		<PalletCommon<T>>::modify_token_properties(645			collection,646			sender,647			token_id,648			&mut is_token_exist,649			properties_updates,650			stored_properties,651			&mut is_token_owner,652			|properties| <TokenProperties<T>>::set((collection.id, token_id), properties),653			erc::ERC721TokenEvent::TokenChanged {654				token_id: token_id.into(),655			}656			.to_log(T::ContractAddress::get()),657		)658	}659660	pub fn next_token_id(collection: &NonfungibleHandle<T>) -> Result<TokenId, DispatchError> {661		let next_token_id = <TokensMinted<T>>::get(collection.id)662			.checked_add(1)663			.ok_or(<CommonError<T>>::CollectionTokenLimitExceeded)?;664665		ensure!(666			collection.limits.token_limit() >= next_token_id,667			<CommonError<T>>::CollectionTokenLimitExceeded668		);669670		Ok(TokenId(next_token_id))671	}672673	/// Batch operation to add or edit properties for the token674	///675	/// Same as [`modify_token_properties`] but doesn't allow to remove properties676	///677	/// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties678	pub fn set_token_properties(679		collection: &NonfungibleHandle<T>,680		sender: &T::CrossAccountId,681		token_id: TokenId,682		properties: impl Iterator<Item = Property>,683		mode: SetPropertyMode,684		nesting_budget: &dyn Budget,685	) -> DispatchResult {686		Self::modify_token_properties(687			collection,688			sender,689			token_id,690			properties.map(|p| (p.key, Some(p.value))),691			mode,692			nesting_budget,693		)694	}695696	/// Add or edit single property for the token697	///698	/// Calls [`set_token_properties`] internally699	///700	/// [`set_token_properties`]: struct.Pallet.html#method.set_token_properties701	pub fn set_token_property(702		collection: &NonfungibleHandle<T>,703		sender: &T::CrossAccountId,704		token_id: TokenId,705		property: Property,706		nesting_budget: &dyn Budget,707	) -> DispatchResult {708		Self::set_token_properties(709			collection,710			sender,711			token_id,712			[property].into_iter(),713			SetPropertyMode::ExistingToken,714			nesting_budget,715		)716	}717718	/// Batch operation to remove properties from the token719	///720	/// Same as [`modify_token_properties`] but doesn't allow to add or edit properties721	///722	/// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties723	pub fn delete_token_properties(724		collection: &NonfungibleHandle<T>,725		sender: &T::CrossAccountId,726		token_id: TokenId,727		property_keys: impl Iterator<Item = PropertyKey>,728		nesting_budget: &dyn Budget,729	) -> DispatchResult {730		Self::modify_token_properties(731			collection,732			sender,733			token_id,734			property_keys.into_iter().map(|key| (key, None)),735			SetPropertyMode::ExistingToken,736			nesting_budget,737		)738	}739740	/// Remove single property from the token741	///742	/// Calls [`delete_token_properties`] internally743	///744	/// [`delete_token_properties`]: struct.Pallet.html#method.delete_token_properties745	pub fn delete_token_property(746		collection: &NonfungibleHandle<T>,747		sender: &T::CrossAccountId,748		token_id: TokenId,749		property_key: PropertyKey,750		nesting_budget: &dyn Budget,751	) -> DispatchResult {752		Self::delete_token_properties(753			collection,754			sender,755			token_id,756			[property_key].into_iter(),757			nesting_budget,758		)759	}760761	/// Add or edit properties for the collection762	pub fn set_collection_properties(763		collection: &NonfungibleHandle<T>,764		sender: &T::CrossAccountId,765		properties: Vec<Property>,766	) -> DispatchResult {767		<PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())768	}769770	/// Remove properties from the collection771	pub fn delete_collection_properties(772		collection: &CollectionHandle<T>,773		sender: &T::CrossAccountId,774		property_keys: Vec<PropertyKey>,775	) -> DispatchResult {776		<PalletCommon<T>>::delete_collection_properties(777			collection,778			sender,779			property_keys.into_iter(),780		)781	}782783	/// Set property permissions for the token.784	///785	/// Sender should be the owner or admin of token's collection.786	pub fn set_token_property_permissions(787		collection: &CollectionHandle<T>,788		sender: &T::CrossAccountId,789		property_permissions: Vec<PropertyKeyPermission>,790	) -> DispatchResult {791		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)792	}793794	/// Set property permissions for the token with scope.795	///796	/// Sender should be the owner or admin of token's collection.797	pub fn set_scoped_token_property_permissions(798		collection: &CollectionHandle<T>,799		sender: &T::CrossAccountId,800		scope: PropertyScope,801		property_permissions: Vec<PropertyKeyPermission>,802	) -> DispatchResult {803		<PalletCommon<T>>::set_scoped_token_property_permissions(804			collection,805			sender,806			scope,807			property_permissions,808		)809	}810811	pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {812		<PalletCommon<T>>::property_permissions(collection_id)813	}814815	pub fn check_token_immediate_ownership(816		collection: &NonfungibleHandle<T>,817		token: TokenId,818		possible_owner: &T::CrossAccountId,819	) -> DispatchResult {820		let token_data =821			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;822		ensure!(823			&token_data.owner == possible_owner,824			<CommonError<T>>::NoPermission825		);826		Ok(())827	}828829	/// Transfer NFT token from one account to another.830	///831	/// `from` account stops being the owner and `to` account becomes the owner of the token.832	/// If `to` is token than `to` becomes owner of the token and the token become nested.833	/// Unnests token from previous parent if it was nested before.834	/// Removes allowance for the token if there was any.835	/// Throws if transfers aren't allowed for collection or if receiver reached token ownership limit.836	///837	/// - `nesting_budget`: Limit for token nesting depth838	pub fn transfer(839		collection: &NonfungibleHandle<T>,840		from: &T::CrossAccountId,841		to: &T::CrossAccountId,842		token: TokenId,843		nesting_budget: &dyn Budget,844	) -> DispatchResultWithPostInfo {845		ensure!(846			collection.limits.transfers_enabled(),847			<CommonError<T>>::TransferNotAllowed848		);849850		let mut actual_weight = <SelfWeightOf<T>>::transfer_raw();851		let token_data =852			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;853		ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);854855		if collection.permissions.access() == AccessMode::AllowList {856			collection.check_allowlist(from)?;857			collection.check_allowlist(to)?;858			actual_weight += <PalletCommonWeightOf<T>>::check_accesslist() * 2;859		}860		<PalletCommon<T>>::ensure_correct_receiver(to)?;861862		let balance_from = <AccountBalance<T>>::get((collection.id, from))863			.checked_sub(1)864			.ok_or(<CommonError<T>>::TokenValueTooLow)?;865		let balance_to = if from != to {866			let balance_to = <AccountBalance<T>>::get((collection.id, to))867				.checked_add(1)868				.ok_or(ArithmeticError::Overflow)?;869870			ensure!(871				balance_to < collection.limits.account_token_ownership_limit(),872				<CommonError<T>>::AccountTokenLimitExceeded,873			);874875			Some(balance_to)876		} else {877			None878		};879880		<PalletStructure<T>>::nest_if_sent_to_token(881			from.clone(),882			to,883			collection.id,884			token,885			nesting_budget,886		)?;887888		// =========889890		<PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);891892		<TokenData<T>>::insert((collection.id, token), ItemData { owner: to.clone() });893894		if let Some(balance_to) = balance_to {895			// from != to896			if balance_from == 0 {897				<AccountBalance<T>>::remove((collection.id, from));898			} else {899				<AccountBalance<T>>::insert((collection.id, from), balance_from);900			}901			<AccountBalance<T>>::insert((collection.id, to), balance_to);902			<Owned<T>>::remove((collection.id, from, token));903			<Owned<T>>::insert((collection.id, to, token), true);904		}905		Self::set_allowance_unchecked(collection, from, token, None, true);906907		<PalletEvm<T>>::deposit_log(908			ERC721Events::Transfer {909				from: *from.as_eth(),910				to: *to.as_eth(),911				token_id: token.into(),912			}913			.to_log(collection_id_to_address(collection.id)),914		);915		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(916			collection.id,917			token,918			from.clone(),919			to.clone(),920			1,921		));922923		Ok(PostDispatchInfo {924			actual_weight: Some(actual_weight),925			pays_fee: Pays::Yes,926		})927	}928929	/// Batch operation to mint multiple NFT tokens.930	///931	/// The sender should be the owner/admin of the collection or collection should be configured932	/// to allow public minting.933	/// Throws if amount of tokens reached it's limit for the collection or if caller reached934	/// token ownership limit.935	///936	/// - `data`: Contains list of token properties and users who will become the owners of the937	///   corresponging tokens.938	/// - `nesting_budget`: Limit for token nesting depth939	pub fn create_multiple_items(940		collection: &NonfungibleHandle<T>,941		sender: &T::CrossAccountId,942		data: Vec<CreateItemData<T>>,943		nesting_budget: &dyn Budget,944	) -> DispatchResult {945		if !collection.is_owner_or_admin(sender) {946			ensure!(947				collection.permissions.mint_mode(),948				<CommonError<T>>::PublicMintingNotAllowed949			);950			collection.check_allowlist(sender)?;951952			for item in data.iter() {953				collection.check_allowlist(&item.owner)?;954			}955		}956957		for data in data.iter() {958			<PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;959		}960961		let first_token = <TokensMinted<T>>::get(collection.id);962		let tokens_minted = first_token963			.checked_add(data.len() as u32)964			.ok_or(ArithmeticError::Overflow)?;965		ensure!(966			tokens_minted <= collection.limits.token_limit(),967			<CommonError<T>>::CollectionTokenLimitExceeded968		);969970		let mut balances = BTreeMap::new();971		for data in &data {972			let balance = balances973				.entry(&data.owner)974				.or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));975			*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;976977			ensure!(978				*balance <= collection.limits.account_token_ownership_limit(),979				<CommonError<T>>::AccountTokenLimitExceeded,980			);981		}982983		for (i, data) in data.iter().enumerate() {984			let token = TokenId(first_token + i as u32 + 1);985986			<PalletStructure<T>>::check_nesting(987				sender.clone(),988				&data.owner,989				collection.id,990				token,991				nesting_budget,992			)?;993		}994995		// =========996997		with_transaction(|| {998			for (i, data) in data.iter().enumerate() {999				let token = first_token + i as u32 + 1;10001001				<TokenData<T>>::insert(1002					(collection.id, token),1003					ItemData {1004						// const_data: data.const_data.clone(),1005						owner: data.owner.clone(),1006					},1007				);10081009				<PalletStructure<T>>::nest_if_sent_to_token_unchecked(1010					&data.owner,1011					collection.id,1012					TokenId(token),1013				);10141015				if let Err(e) = Self::set_token_properties(1016					collection,1017					sender,1018					TokenId(token),1019					data.properties.clone().into_iter(),1020					SetPropertyMode::NewToken {1021						mint_target_is_sender: sender.conv_eq(&data.owner),1022					},1023					nesting_budget,1024				) {1025					return TransactionOutcome::Rollback(Err(e));1026				}1027			}1028			TransactionOutcome::Commit(Ok(()))1029		})?;10301031		<TokensMinted<T>>::insert(collection.id, tokens_minted);1032		for (account, balance) in balances {1033			<AccountBalance<T>>::insert((collection.id, account), balance);1034		}1035		for (i, data) in data.into_iter().enumerate() {1036			let token = first_token + i as u32 + 1;1037			<Owned<T>>::insert((collection.id, &data.owner, token), true);10381039			<PalletEvm<T>>::deposit_log(1040				ERC721Events::Transfer {1041					from: H160::default(),1042					to: *data.owner.as_eth(),1043					token_id: token.into(),1044				}1045				.to_log(collection_id_to_address(collection.id)),1046			);1047			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1048				collection.id,1049				TokenId(token),1050				data.owner.clone(),1051				1,1052			));1053		}1054		Ok(())1055	}10561057	pub fn set_allowance_unchecked(1058		collection: &NonfungibleHandle<T>,1059		sender: &T::CrossAccountId,1060		token: TokenId,1061		spender: Option<&T::CrossAccountId>,1062		assume_implicit_eth: bool,1063	) {1064		if let Some(spender) = spender {1065			let old_spender = <Allowance<T>>::get((collection.id, token));1066			<Allowance<T>>::insert((collection.id, token), spender);1067			// In ERC721 there is only one possible approved user of token, so we set1068			// approved user to spender1069			<PalletEvm<T>>::deposit_log(1070				ERC721Events::Approval {1071					owner: *sender.as_eth(),1072					approved: *spender.as_eth(),1073					token_id: token.into(),1074				}1075				.to_log(collection_id_to_address(collection.id)),1076			);1077			// In Unique chain, any token can have any amount of approved users, so we need to1078			// set allowance of old owner to 0, and allowance of new owner to 11079			if old_spender.as_ref() != Some(spender) {1080				if let Some(old_owner) = old_spender {1081					<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1082						collection.id,1083						token,1084						sender.clone(),1085						old_owner,1086						0,1087					));1088				}1089				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1090					collection.id,1091					token,1092					sender.clone(),1093					spender.clone(),1094					1,1095				));1096			}1097		} else {1098			let old_spender = <Allowance<T>>::take((collection.id, token));1099			if !assume_implicit_eth {1100				// In ERC721 there is only one possible approved user of token, so we set1101				// approved user to zero address1102				<PalletEvm<T>>::deposit_log(1103					ERC721Events::Approval {1104						owner: *sender.as_eth(),1105						approved: H160::default(),1106						token_id: token.into(),1107					}1108					.to_log(collection_id_to_address(collection.id)),1109				);1110			}1111			// In Unique chain, any token can have any amount of approved users, so we need to1112			// set allowance of old owner to 01113			if let Some(old_spender) = old_spender {1114				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1115					collection.id,1116					token,1117					sender.clone(),1118					old_spender,1119					0,1120				));1121			}1122		}1123	}11241125	pub fn get_allowance(1126		collection: &NonfungibleHandle<T>,1127		token_id: TokenId,1128	) -> Result<Option<T::CrossAccountId>, DispatchError> {1129		ensure!(1130			<TokenData<T>>::get((collection.id, token_id)).is_some(),1131			<CommonError<T>>::TokenNotFound1132		);1133		Ok(<Allowance<T>>::get((collection.id, token_id)))1134	}11351136	/// Set allowance for the spender to `transfer` or `burn` sender's token.1137	///1138	/// - `token`: Token the spender is allowed to `transfer` or `burn`.1139	pub fn set_allowance(1140		collection: &NonfungibleHandle<T>,1141		sender: &T::CrossAccountId,1142		token: TokenId,1143		spender: Option<&T::CrossAccountId>,1144	) -> DispatchResult {1145		if collection.permissions.access() == AccessMode::AllowList {1146			collection.check_allowlist(sender)?;1147			if let Some(spender) = spender {1148				collection.check_allowlist(spender)?;1149			}1150		}11511152		if let Some(spender) = spender {1153			<PalletCommon<T>>::ensure_correct_receiver(spender)?;1154		}11551156		let token_data =1157			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1158		if &token_data.owner != sender {1159			ensure!(1160				collection.ignores_owned_amount(sender),1161				<CommonError<T>>::CantApproveMoreThanOwned1162			);1163		}11641165		// =========11661167		Self::set_allowance_unchecked(collection, sender, token, spender, false);1168		Ok(())1169	}11701171	/// Set allowance for the spender to `transfer` or `burn` sender's token from eth mirror.1172	///1173	/// - `from`: Address of sender's eth mirror.1174	/// - `to`: Adress of spender.1175	/// - `token`: Token the spender is allowed to `transfer` or `burn`.1176	pub fn set_allowance_from(1177		collection: &NonfungibleHandle<T>,1178		sender: &T::CrossAccountId,1179		from: &T::CrossAccountId,1180		token: TokenId,1181		to: Option<&T::CrossAccountId>,1182	) -> DispatchResult {1183		if collection.permissions.access() == AccessMode::AllowList {1184			collection.check_allowlist(sender)?;1185			collection.check_allowlist(from)?;1186			if let Some(to) = to {1187				collection.check_allowlist(to)?;1188			}1189		}11901191		if let Some(to) = to {1192			<PalletCommon<T>>::ensure_correct_receiver(to)?;1193		}11941195		ensure!(1196			sender.conv_eq(from),1197			<CommonError<T>>::AddressIsNotEthMirror1198		);11991200		let token_data =1201			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1202		if token_data.owner != *from {1203			ensure!(1204				collection.limits.owner_can_transfer()1205					&& (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),1206				<CommonError<T>>::CantApproveMoreThanOwned1207			);1208		}12091210		// =========12111212		Self::set_allowance_unchecked(collection, from, token, to, false);1213		Ok(())1214	}12151216	/// Checks allowance for the spender to use the token.1217	fn check_allowed(1218		collection: &NonfungibleHandle<T>,1219		spender: &T::CrossAccountId,1220		from: &T::CrossAccountId,1221		token: TokenId,1222		nesting_budget: &dyn Budget,1223	) -> DispatchResult {1224		if spender.conv_eq(from) {1225			return Ok(());1226		}1227		if collection.permissions.access() == AccessMode::AllowList {1228			// `from`, `to` checked in [`transfer`]1229			collection.check_allowlist(spender)?;1230		}12311232		if collection.ignores_token_restrictions(spender) {1233			return Ok(());1234		}12351236		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1237			ensure!(1238				<PalletStructure<T>>::check_indirectly_owned(1239					spender.clone(),1240					source.0,1241					source.1,1242					None,1243					nesting_budget1244				)?,1245				<CommonError<T>>::ApprovedValueTooLow,1246			);1247			return Ok(());1248		}1249		if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {1250			return Ok(());1251		}1252		if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1253			return Ok(());1254		}12551256		Err(<CommonError<T>>::ApprovedValueTooLow.into())1257	}12581259	/// Transfer NFT token from one account to another.1260	///1261	/// Same as the [`transfer`] but spender doesn't needs to be the owner of the token.1262	/// The owner should set allowance for the spender to transfer token.1263	///1264	/// [`transfer`]: struct.Pallet.html#method.transfer1265	pub fn transfer_from(1266		collection: &NonfungibleHandle<T>,1267		spender: &T::CrossAccountId,1268		from: &T::CrossAccountId,1269		to: &T::CrossAccountId,1270		token: TokenId,1271		nesting_budget: &dyn Budget,1272	) -> DispatchResultWithPostInfo {1273		Self::check_allowed(collection, spender, from, token, nesting_budget)?;12741275		// =========12761277		// Allowance is reset in [`transfer`]1278		let mut result = Self::transfer(collection, from, to, token, nesting_budget);1279		add_weight_to_post_info(&mut result, <SelfWeightOf<T>>::check_allowed_raw());1280		result1281	}12821283	/// Burn NFT token for `from` account.1284	///1285	/// Same as the [`burn`] but spender doesn't need to be an owner of the token. The owner should1286	/// set allowance for the spender to burn token.1287	///1288	/// [`burn`]: struct.Pallet.html#method.burn1289	pub fn burn_from(1290		collection: &NonfungibleHandle<T>,1291		spender: &T::CrossAccountId,1292		from: &T::CrossAccountId,1293		token: TokenId,1294		nesting_budget: &dyn Budget,1295	) -> DispatchResult {1296		Self::check_allowed(collection, spender, from, token, nesting_budget)?;12971298		// =========12991300		Self::burn(collection, from, token)1301	}13021303	/// Check that `from` token could be nested in `under` token.1304	///1305	pub fn check_nesting(1306		handle: &NonfungibleHandle<T>,1307		sender: T::CrossAccountId,1308		from: (CollectionId, TokenId),1309		under: TokenId,1310		nesting_budget: &dyn Budget,1311	) -> DispatchResult {1312		let nesting = handle.permissions.nesting();13131314		#[cfg(not(feature = "runtime-benchmarks"))]1315		let permissive = false;1316		#[cfg(feature = "runtime-benchmarks")]1317		let permissive = nesting.permissive;13181319		if permissive {1320			ensure!(1321				<TokenData<T>>::contains_key((handle.id, under)),1322				<CommonError<T>>::TokenNotFound1323			);1324		} else if nesting.token_owner1325			&& <PalletStructure<T>>::check_indirectly_owned(1326				sender.clone(),1327				handle.id,1328				under,1329				Some(from),1330				nesting_budget,1331			)? {1332			// Pass, token existence and ouroboros checks are done in `check_indirectly_owned`1333		} else if nesting.collection_admin && handle.is_owner_or_admin(&sender) {1334			// token existence and ouroboros checks are done in `get_checked_topmost_owner`1335			let _ = <PalletStructure<T>>::get_checked_topmost_owner(1336				handle.id,1337				under,1338				Some(from),1339				nesting_budget,1340			)?1341			.ok_or(<CommonError<T>>::TokenNotFound)?;1342		} else {1343			fail!(<CommonError<T>>::UserIsNotAllowedToNest);1344		}13451346		if let Some(whitelist) = &nesting.restricted {1347			ensure!(1348				whitelist.contains(&from.0),1349				<CommonError<T>>::SourceCollectionIsNotAllowedToNest1350			);1351		}1352		Ok(())1353	}13541355	fn nest(under: (CollectionId, TokenId), to_nest: (CollectionId, TokenId)) {1356		if to_nest.0 != pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {1357			<TokenChildren<T>>::insert((under.0, under.1, to_nest), true);1358		}1359	}13601361	fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {1362		if to_unnest.0 != pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {1363			<TokenChildren<T>>::remove((under.0, under.1, to_unnest));1364		}1365	}13661367	fn collection_has_tokens(collection_id: CollectionId) -> bool {1368		<TokenData<T>>::iter_prefix((collection_id,))1369			.next()1370			.is_some()1371	}13721373	fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {1374		<TokenChildren<T>>::iter_prefix((collection_id, token_id))1375			.next()1376			.is_some()1377	}13781379	pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {1380		<TokenChildren<T>>::iter_prefix((collection_id, token_id))1381			.map(|((child_collection_id, child_id), _)| TokenChild {1382				collection: child_collection_id,1383				token: child_id,1384			})1385			.collect()1386	}13871388	/// Mint single NFT token.1389	///1390	/// Delegated to [`create_multiple_items`]1391	///1392	/// [`create_multiple_items`]: struct.Pallet.html#method.create_multiple_items1393	pub fn create_item(1394		collection: &NonfungibleHandle<T>,1395		sender: &T::CrossAccountId,1396		data: CreateItemData<T>,1397		nesting_budget: &dyn Budget,1398	) -> DispatchResult {1399		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1400	}14011402	/// Sets or unsets the approval of a given operator.1403	///1404	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1405	/// - `owner`: Token owner1406	/// - `operator`: Operator1407	/// - `approve`: Should operator status be granted or revoked?1408	pub fn set_allowance_for_all(1409		collection: &NonfungibleHandle<T>,1410		owner: &T::CrossAccountId,1411		operator: &T::CrossAccountId,1412		approve: bool,1413	) -> DispatchResult {1414		<PalletCommon<T>>::set_allowance_for_all(1415			collection,1416			owner,1417			operator,1418			approve,1419			|| <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve),1420			ERC721Events::ApprovalForAll {1421				owner: *owner.as_eth(),1422				operator: *operator.as_eth(),1423				approved: approve,1424			}1425			.to_log(collection_id_to_address(collection.id)),1426		)1427	}14281429	/// Tells whether the given `owner` approves the `operator`.1430	pub fn allowance_for_all(1431		collection: &NonfungibleHandle<T>,1432		owner: &T::CrossAccountId,1433		operator: &T::CrossAccountId,1434	) -> bool {1435		<CollectionAllowance<T>>::get((collection.id, owner, operator))1436	}14371438	pub fn repair_item(collection: &NonfungibleHandle<T>, token: TokenId) -> DispatchResult {1439		<TokenProperties<T>>::mutate((collection.id, token), |properties| {1440			properties.recompute_consumed_space();1441		});14421443		Ok(())1444	}1445}
modifiedpallets/refungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -22,7 +22,9 @@
 use frame_benchmarking::{benchmarks, account};
 use pallet_common::{
 	bench_init,
-	benchmarking::{create_collection_raw, property_key, property_value},
+	benchmarking::{
+		create_collection_raw, property_key, property_value, load_is_admin_and_property_permissions,
+	},
 };
 use sp_std::prelude::*;
 use up_data_structs::{
@@ -255,14 +257,15 @@
 			value: property_value(),
 		}).collect::<Vec<_>>();
 		let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
-	}: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), SetPropertyMode::ExistingToken, &Unlimited)?}
+	}: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), &Unlimited)?}
 
-	reset_token_properties {
+	init_token_properties {
 		let b in 0..MAX_PROPERTIES_PER_ITEM;
 		bench_init!{
 			owner: sub; collection: collection(owner);
 			owner: cross_from_sub;
 		};
+
 		let perms = (0..b).map(|k| PropertyKeyPermission {
 			key: property_key(k as usize),
 			permission: PropertyPermission {
@@ -277,8 +280,26 @@
 			value: property_value(),
 		}).collect::<Vec<_>>();
 		let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
-	}: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), SetPropertyMode::NewToken { mint_target_is_sender: true }, &Unlimited)?}
 
+		let (is_collection_admin, property_permissions) = load_is_admin_and_property_permissions(&collection, &owner);
+	}: {
+		let mut property_writer = pallet_common::collection_info_loaded_property_writer(
+			&collection,
+			is_collection_admin,
+			property_permissions,
+		);
+
+		property_writer.write_token_properties(
+			true,
+			item,
+			props.into_iter(),
+			crate::erc::ERC721TokenEvent::TokenChanged {
+				token_id: item.into(),
+			}
+			.to_log(T::ContractAddress::get()),
+		)?
+	}
+
 	delete_token_properties {
 		let b in 0..MAX_PROPERTIES_PER_ITEM;
 		bench_init!{
@@ -299,7 +320,7 @@
 			value: property_value(),
 		}).collect::<Vec<_>>();
 		let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
-		<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), SetPropertyMode::ExistingToken, &Unlimited)?;
+		<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), &Unlimited)?;
 		let to_delete = (0..b).map(|k| property_key(k as usize)).collect::<Vec<_>>();
 	}: {<Pallet<T>>::delete_token_properties(&collection, &owner, item, to_delete.into_iter(), &Unlimited)?}
 
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -20,20 +20,20 @@
 use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, traits::Get};
 use up_data_structs::{
 	CollectionId, TokenId, CreateItemExData, budget::Budget, Property, PropertyKey, PropertyValue,
-	PropertyKeyPermission, CollectionPropertiesVec, CreateRefungibleExMultipleOwners,
-	CreateRefungibleExSingleOwner, TokenOwnerError,
+	PropertyKeyPermission, CreateRefungibleExMultipleOwners, CreateRefungibleExSingleOwner,
+	TokenOwnerError,
 };
 use pallet_common::{
 	CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
-	weights::WeightInfo as _,
+	weights::WeightInfo as _, init_token_properties_delta,
 };
-use pallet_structure::Error as StructureError;
+use pallet_structure::{Pallet as PalletStructure, Error as StructureError};
 use sp_runtime::{DispatchError};
 use sp_std::{vec::Vec, vec};
 
 use crate::{
 	AccountBalance, Allowance, Balance, Config, Error, Owned, Pallet, RefungibleHandle,
-	SelfWeightOf, weights::WeightInfo, TokensMinted, TotalSupply, CreateItemData,
+	SelfWeightOf, weights::WeightInfo, TokensMinted, TotalSupply, CreateItemData, TokenProperties,
 };
 
 macro_rules! max_weight_of {
@@ -45,26 +45,19 @@
 	};
 }
 
-fn properties_weight<T: Config>(properties: &CollectionPropertiesVec) -> Weight {
-	if properties.len() > 0 {
-		<SelfWeightOf<T>>::reset_token_properties(properties.len() as u32)
-	} else {
-		Weight::zero()
-	}
-}
-
 pub struct CommonWeights<T: Config>(PhantomData<T>);
 impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {
 	fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {
 		<SelfWeightOf<T>>::create_multiple_items(data.len() as u32).saturating_add(
-			data.iter()
-				.map(|data| match data {
+			init_token_properties_delta::<T, _>(
+				data.iter().map(|data| match data {
 					up_data_structs::CreateItemData::ReFungible(rft_data) => {
-						properties_weight::<T>(&rft_data.properties)
+						rft_data.properties.len() as u32
 					}
-					_ => Weight::zero(),
-				})
-				.fold(Weight::zero(), |a, b| a.saturating_add(b)),
+					_ => 0,
+				}),
+				<SelfWeightOf<T>>::init_token_properties,
+			),
 		)
 	}
 
@@ -72,15 +65,17 @@
 		match call {
 			CreateItemExData::RefungibleMultipleOwners(i) => {
 				<SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(i.users.len() as u32)
-					.saturating_add(properties_weight::<T>(&i.properties))
+					.saturating_add(init_token_properties_delta::<T, _>(
+						[i.properties.len() as u32].into_iter(),
+						<SelfWeightOf<T>>::init_token_properties,
+					))
 			}
 			CreateItemExData::RefungibleMultipleItems(i) => {
 				<SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(i.len() as u32)
-					.saturating_add(
-						i.iter()
-							.map(|d| properties_weight::<T>(&d.properties))
-							.fold(Weight::zero(), |a, b| a.saturating_add(b)),
-					)
+					.saturating_add(init_token_properties_delta::<T, _>(
+						i.iter().map(|d| d.properties.len() as u32),
+						<SelfWeightOf<T>>::init_token_properties,
+					))
 			}
 			_ => Weight::zero(),
 		}
@@ -399,7 +394,6 @@
 				&sender,
 				token_id,
 				properties.into_iter(),
-				pallet_common::SetPropertyMode::ExistingToken,
 				nesting_budget,
 			),
 			weight,
@@ -441,6 +435,18 @@
 		)
 	}
 
+	fn get_token_properties_map(&self, token_id: TokenId) -> up_data_structs::TokenProperties {
+		<TokenProperties<T>>::get((self.id, token_id))
+	}
+
+	fn set_token_properties_map(&self, token_id: TokenId, map: up_data_structs::TokenProperties) {
+		<TokenProperties<T>>::set((self.id, token_id), map)
+	}
+
+	fn properties_exist(&self, token: TokenId) -> bool {
+		<TokenProperties<T>>::contains_key((self.id, token))
+	}
+
 	fn check_nesting(
 		&self,
 		_sender: <T>::CrossAccountId,
@@ -479,6 +485,29 @@
 		<Pallet<T>>::token_owner(self.id, token)
 	}
 
+	fn check_token_indirect_owner(
+		&self,
+		token: TokenId,
+		maybe_owner: &T::CrossAccountId,
+		nesting_budget: &dyn Budget,
+	) -> Result<bool, DispatchError> {
+		let balance = self.balance(maybe_owner.clone(), token);
+		let total_pieces: u128 = <Pallet<T>>::total_pieces(self.id, token).unwrap_or(u128::MAX);
+		if balance != total_pieces {
+			return Ok(false);
+		}
+
+		let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(
+			maybe_owner.clone(),
+			self.id,
+			token,
+			None,
+			nesting_budget,
+		)?;
+
+		Ok(is_bundle_owner)
+	}
+
 	/// Returns 10 token in no particular order.
 	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {
 		<Pallet<T>>::token_owners(self.id, token).unwrap_or_default()
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -214,7 +214,6 @@
 			&caller,
 			TokenId(token_id),
 			properties.into_iter(),
-			pallet_common::SetPropertyMode::ExistingToken,
 			&nesting_budget,
 		)
 		.map_err(dispatch_to_evm::<T>)
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -96,8 +96,8 @@
 use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
 use pallet_evm_coder_substrate::WithRecorder;
 use pallet_common::{
-	CommonCollectionOperations, Error as CommonError, eth::collection_id_to_address,
-	Event as CommonEvent, Pallet as PalletCommon, SetPropertyMode,
+	Error as CommonError, eth::collection_id_to_address, Event as CommonEvent,
+	Pallet as PalletCommon,
 };
 use pallet_structure::Pallet as PalletStructure;
 use sp_core::{Get, H160};
@@ -533,66 +533,16 @@
 		sender: &T::CrossAccountId,
 		token_id: TokenId,
 		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
-		mode: SetPropertyMode,
 		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
-		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 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)
-			});
-
-		let is_new_token = matches!(mode, SetPropertyMode::NewToken { .. });
-
-		let mut is_token_exist = pallet_common::LazyValue::new(|| {
-			if is_new_token {
-				debug_assert!(Self::token_exists(collection, token_id));
-				true
-			} else {
-				Self::token_exists(collection, token_id)
-			}
-		});
-
-		let stored_properties = if is_new_token {
-			debug_assert!(!<TokenProperties<T>>::contains_key((
-				collection.id,
-				token_id
-			)));
-			TokenPropertiesT::new()
-		} else {
-			<TokenProperties<T>>::get((collection.id, token_id))
-		};
+		let mut property_writer =
+			pallet_common::property_writer_for_existing_token(collection, sender);
 
-		<PalletCommon<T>>::modify_token_properties(
-			collection,
+		property_writer.write_token_properties(
 			sender,
 			token_id,
-			&mut is_token_exist,
 			properties_updates,
-			stored_properties,
-			&mut is_token_owner,
-			|properties| <TokenProperties<T>>::set((collection.id, token_id), properties),
+			nesting_budget,
 			erc::ERC721TokenEvent::TokenChanged {
 				token_id: token_id.into(),
 			}
@@ -618,7 +568,6 @@
 		sender: &T::CrossAccountId,
 		token_id: TokenId,
 		properties: impl Iterator<Item = Property>,
-		mode: SetPropertyMode,
 		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
 		Self::modify_token_properties(
@@ -626,7 +575,6 @@
 			sender,
 			token_id,
 			properties.map(|p| (p.key, Some(p.value))),
-			mode,
 			nesting_budget,
 		)
 	}
@@ -643,7 +591,6 @@
 			sender,
 			token_id,
 			[property].into_iter(),
-			SetPropertyMode::ExistingToken,
 			nesting_budget,
 		)
 	}
@@ -660,7 +607,6 @@
 			sender,
 			token_id,
 			property_keys.into_iter().map(|key| (key, None)),
-			SetPropertyMode::ExistingToken,
 			nesting_budget,
 		)
 	}
@@ -941,11 +887,15 @@
 
 		// =========
 
+		let mut property_writer = pallet_common::property_writer_for_new_token(collection, sender);
+
 		with_transaction(|| {
 			for (i, data) in data.iter().enumerate() {
 				let token_id = first_token_id + i as u32 + 1;
 				<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);
 
+				let token = TokenId(token_id);
+
 				let mut mint_target_is_sender = true;
 				for (user, amount) in data.users.iter() {
 					if *amount == 0 {
@@ -955,23 +905,22 @@
 					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);
+					<Owned<T>>::insert((collection.id, &user, token), true);
 					<PalletStructure<T>>::nest_if_sent_to_token_unchecked(
 						user,
 						collection.id,
-						TokenId(token_id),
+						token,
 					);
 				}
 
-				if let Err(e) = Self::set_token_properties(
-					collection,
-					sender,
-					TokenId(token_id),
+				if let Err(e) = property_writer.write_token_properties(
+					mint_target_is_sender,
+					token,
 					data.properties.clone().into_iter(),
-					SetPropertyMode::NewToken {
-						mint_target_is_sender,
-					},
-					nesting_budget,
+					erc::ERC721TokenEvent::TokenChanged {
+						token_id: token.into(),
+					}
+					.to_log(T::ContractAddress::get()),
 				) {
 					return TransactionOutcome::Rollback(Err(e));
 				}