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
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -109,7 +109,7 @@
 use pallet_common::{
 	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,
 	eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,
-	weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info,
+	weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info, SetPropertyMode,
 };
 use pallet_structure::{Pallet as PalletStructure, Error as StructureError};
 use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
@@ -585,8 +585,6 @@
 	/// A batch operation to add, edit or remove properties for a token.
 	///
 	/// - `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**,
@@ -601,10 +599,17 @@
 		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 = || {
+		let mut is_token_owner = pallet_common::LazyValue::new(|| {
+			if let SetPropertyMode::NewToken {
+				mint_target_is_sender,
+			} = mode
+			{
+				return Ok(mint_target_is_sender);
+			}
+
 			let is_owned = <PalletStructure<T>>::check_indirectly_owned(
 				sender.clone(),
 				collection.id,
@@ -614,18 +619,21 @@
 			)?;
 
 			Ok(is_owned)
-		};
+		});
 
+		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));
 
 		<PalletCommon<T>>::modify_token_properties(
 			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(),
@@ -634,6 +642,19 @@
 		)
 	}
 
+	pub fn next_token_id(collection: &NonfungibleHandle<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))
+	}
+
 	/// Batch operation to add or edit properties for the token
 	///
 	/// Same as [`modify_token_properties`] but doesn't allow to remove properties
@@ -644,7 +665,7 @@
 		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(
@@ -652,7 +673,7 @@
 			sender,
 			token_id,
 			properties.map(|p| (p.key, Some(p.value))),
-			is_token_create,
+			mode,
 			nesting_budget,
 		)
 	}
@@ -669,14 +690,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,
 		)
 	}
@@ -693,14 +712,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,
 		)
 	}
@@ -985,7 +1002,9 @@
 					sender,
 					TokenId(token),
 					data.properties.clone().into_iter(),
-					true,
+					SetPropertyMode::NewToken {
+						mint_target_is_sender: sender.conv_eq(&data.owner),
+					},
 					nesting_budget,
 				) {
 					return TransactionOutcome::Rollback(Err(e));
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
before · runtime/common/sponsoring.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/>.1617use core::marker::PhantomData;18use up_sponsorship::SponsorshipHandler;19use frame_support::{20	traits::{IsSubType},21};22use up_data_structs::{23	CollectionId, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, NFT_SPONSOR_TRANSFER_TIMEOUT,24	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, TokenId, CollectionMode, CreateItemData,25};26use sp_runtime::traits::Saturating;27use pallet_common::{CollectionHandle};28use pallet_evm::account::CrossAccountId;29use pallet_unique::{30	Call as UniqueCall, Config as UniqueConfig, FungibleApproveBasket, RefungibleApproveBasket,31	NftApproveBasket, CreateItemBasket, ReFungibleTransferBasket, FungibleTransferBasket,32	NftTransferBasket, TokenPropertyBasket,33};34use pallet_fungible::Config as FungibleConfig;35use pallet_nonfungible::Config as NonfungibleConfig;36use pallet_refungible::Config as RefungibleConfig;3738pub trait Config: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig {}39impl<T> Config for T where T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig {}4041// TODO: permission check?42pub fn withdraw_set_token_property<T: Config>(43	collection: &CollectionHandle<T>,44	who: &T::CrossAccountId,45	item_id: &TokenId,46	data_size: usize,47) -> Option<()> {48	// preliminary sponsoring correctness check49	match collection.mode {50		CollectionMode::NFT => {51			let owner = pallet_nonfungible::TokenData::<T>::get((collection.id, item_id))?.owner;52			if !owner.conv_eq(who) {53				return None;54			}55		}56		CollectionMode::Fungible(_) => {57			// Fungible tokens have no properties58			return None;59		}60		CollectionMode::ReFungible => {61			if !<pallet_refungible::Owned<T>>::get((collection.id, who, item_id)) {62				return None;63			}64		}65	}6667	if data_size > collection.limits.sponsored_data_size() as usize {68		return None;69	}7071	let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;72	let limit = collection.limits.sponsored_data_rate_limit()?;7374	if let Some(last_tx_block) = TokenPropertyBasket::<T>::get(collection.id, item_id) {75		let timeout = last_tx_block + limit.into();76		if block_number < timeout {77			return None;78		}79	}8081	<TokenPropertyBasket<T>>::insert(collection.id, item_id, block_number);8283	Some(())84}8586pub fn withdraw_transfer<T: Config>(87	collection: &CollectionHandle<T>,88	who: &T::CrossAccountId,89	item_id: &TokenId,90) -> Option<()> {91	// preliminary sponsoring correctness check92	match collection.mode {93		CollectionMode::NFT => {94			let owner = pallet_nonfungible::TokenData::<T>::get((collection.id, item_id))?.owner;95			if !owner.conv_eq(who) {96				return None;97			}98		}99		CollectionMode::Fungible(_) => {100			if item_id != &TokenId::default() {101				return None;102			}103			if <pallet_fungible::Balance<T>>::get((collection.id, who)) == 0 {104				return None;105			}106		}107		CollectionMode::ReFungible => {108			if !<pallet_refungible::Owned<T>>::get((collection.id, who, item_id)) {109				return None;110			}111		}112	}113114	// sponsor timeout115	let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;116	let limit = collection117		.limits118		.sponsor_transfer_timeout(match collection.mode {119			CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,120			CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,121			CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,122		});123124	let last_tx_block = match collection.mode {125		CollectionMode::NFT => <NftTransferBasket<T>>::get(collection.id, item_id),126		CollectionMode::Fungible(_) => {127			<FungibleTransferBasket<T>>::get(collection.id, who.as_sub())128		}129		CollectionMode::ReFungible => {130			<ReFungibleTransferBasket<T>>::get((collection.id, item_id, who.as_sub()))131		}132	};133134	if let Some(last_tx_block) = last_tx_block {135		let timeout = last_tx_block + limit.into();136		if block_number < timeout {137			return None;138		}139	}140141	match collection.mode {142		CollectionMode::NFT => <NftTransferBasket<T>>::insert(collection.id, item_id, block_number),143		CollectionMode::Fungible(_) => {144			<FungibleTransferBasket<T>>::insert(collection.id, who.as_sub(), block_number)145		}146		CollectionMode::ReFungible => <ReFungibleTransferBasket<T>>::insert(147			(collection.id, item_id, who.as_sub()),148			block_number,149		),150	};151152	Some(())153}154155pub fn withdraw_create_item<T: Config>(156	collection: &CollectionHandle<T>,157	who: &T::CrossAccountId,158	properties: &CreateItemData,159) -> Option<()> {160	// sponsor timeout161	let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;162	let limit = collection163		.limits164		.sponsor_transfer_timeout(match properties {165			CreateItemData::NFT(_) => NFT_SPONSOR_TRANSFER_TIMEOUT,166			CreateItemData::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,167			CreateItemData::ReFungible(_) => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,168		});169170	if let Some(last_tx_block) = <CreateItemBasket<T>>::get((collection.id, who.as_sub())) {171		let timeout = last_tx_block + limit.into();172		if block_number < timeout {173			return None;174		}175	}176177	CreateItemBasket::<T>::insert((collection.id, who.as_sub()), block_number);178179	Some(())180}181182pub fn withdraw_approve<T: Config>(183	collection: &CollectionHandle<T>,184	who: &T::AccountId,185	item_id: &TokenId,186) -> Option<()> {187	// sponsor timeout188	let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;189	let limit = collection.limits.sponsor_approve_timeout();190191	let last_tx_block = match collection.mode {192		CollectionMode::NFT => <NftApproveBasket<T>>::get(collection.id, item_id),193		CollectionMode::Fungible(_) => <FungibleApproveBasket<T>>::get(collection.id, who),194		CollectionMode::ReFungible => {195			<RefungibleApproveBasket<T>>::get((collection.id, item_id, who))196		}197	};198199	if let Some(last_tx_block) = last_tx_block {200		let timeout = last_tx_block + limit.into();201		if block_number < timeout {202			return None;203		}204	}205206	match collection.mode {207		CollectionMode::NFT => <NftApproveBasket<T>>::insert(collection.id, item_id, block_number),208		CollectionMode::Fungible(_) => {209			<FungibleApproveBasket<T>>::insert(collection.id, who, block_number)210		}211		CollectionMode::ReFungible => {212			<RefungibleApproveBasket<T>>::insert((collection.id, item_id, who), block_number)213		}214	};215216	Some(())217}218219fn load<T: UniqueConfig>(id: CollectionId) -> Option<(T::AccountId, CollectionHandle<T>)> {220	let collection = CollectionHandle::new(id)?;221	let sponsor = collection.sponsorship.sponsor().cloned()?;222	Some((sponsor, collection))223}224225pub struct UniqueSponsorshipHandler<T>(PhantomData<T>);226impl<T, C> SponsorshipHandler<T::AccountId, C> for UniqueSponsorshipHandler<T>227where228	T: Config,229	C: IsSubType<UniqueCall<T>>,230{231	fn get_sponsor(who: &T::AccountId, call: &C) -> Option<T::AccountId> {232		match IsSubType::<UniqueCall<T>>::is_sub_type(call)? {233			UniqueCall::set_token_properties {234				collection_id,235				token_id,236				properties,237				..238			} => {239				let (sponsor, collection) = load::<T>(*collection_id)?;240				withdraw_set_token_property(241					&collection,242					&T::CrossAccountId::from_sub(who.clone()),243					token_id,244					// No overflow may happen, as data larger than usize can't reach here245					properties.iter().map(|p| p.key.len() + p.value.len()).sum(),246				)247				.map(|()| sponsor)248			}249			UniqueCall::create_item {250				collection_id,251				data,252				..253			} => {254				let (sponsor, collection) = load(*collection_id)?;255				withdraw_create_item::<T>(256					&collection,257					&T::CrossAccountId::from_sub(who.clone()),258					data,259				)260				.map(|()| sponsor)261			}262			UniqueCall::transfer {263				collection_id,264				item_id,265				..266			} => {267				let (sponsor, collection) = load(*collection_id)?;268				withdraw_transfer::<T>(269					&collection,270					&T::CrossAccountId::from_sub(who.clone()),271					item_id,272				)273				.map(|()| sponsor)274			}275			UniqueCall::transfer_from {276				collection_id,277				item_id,278				from,279				..280			} => {281				let (sponsor, collection) = load(*collection_id)?;282				withdraw_transfer::<T>(&collection, from, item_id).map(|()| sponsor)283			}284			UniqueCall::approve {285				collection_id,286				item_id,287				..288			} => {289				let (sponsor, collection) = load(*collection_id)?;290				withdraw_approve::<T>(&collection, who, item_id).map(|()| sponsor)291			}292			_ => None,293		}294	}295}296297pub trait SponsorshipPredict<T: Config> {298	fn predict(collection: CollectionId, account: T::CrossAccountId, token: TokenId) -> Option<u64>299	where300		u64: From<<T as frame_system::Config>::BlockNumber>;301}302303pub struct UniqueSponsorshipPredict<T>(PhantomData<T>);304305impl<T: Config> SponsorshipPredict<T> for UniqueSponsorshipPredict<T> {306	fn predict(collection_id: CollectionId, who: T::CrossAccountId, token: TokenId) -> Option<u64>307	where308		u64: From<<T as frame_system::Config>::BlockNumber>,309	{310		let collection = <CollectionHandle<T>>::try_get(collection_id).ok()?;311		let _ = collection.sponsorship.sponsor()?;312313		// sponsor timeout314		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;315		let limit = collection316			.limits317			.sponsor_transfer_timeout(match collection.mode {318				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,319				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,320				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,321			});322323		let last_tx_block = match collection.mode {324			CollectionMode::NFT => <NftTransferBasket<T>>::get(collection.id, token),325			CollectionMode::Fungible(_) => {326				<FungibleTransferBasket<T>>::get(collection.id, who.as_sub())327			}328			CollectionMode::ReFungible => {329				<ReFungibleTransferBasket<T>>::get((collection.id, token, who.as_sub()))330			}331		};332333		if let Some(last_tx_block) = last_tx_block {334			return Some(335				last_tx_block336					.saturating_add(limit.into())337					.saturating_sub(block_number)338					.into(),339			);340		}341342		let token_exists = match collection.mode {343			CollectionMode::NFT => {344				<pallet_nonfungible::TokenData<T>>::contains_key((collection.id, token))345			}346			CollectionMode::Fungible(_) => token == TokenId::default(),347			CollectionMode::ReFungible => {348				<pallet_refungible::TotalSupply<T>>::contains_key((collection.id, token))349			}350		};351352		if token_exists {353			Some(0)354		} else {355			None356		}357	}358}
after · runtime/common/sponsoring.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/>.1617use core::marker::PhantomData;18use up_sponsorship::SponsorshipHandler;19use frame_support::{20	traits::{IsSubType},21};22use up_data_structs::{23	CollectionId, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, NFT_SPONSOR_TRANSFER_TIMEOUT,24	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, TokenId, CollectionMode, CreateItemData,25};26use sp_runtime::traits::Saturating;27use pallet_common::{CollectionHandle};28use pallet_evm::account::CrossAccountId;29use pallet_unique::{30	Call as UniqueCall, Config as UniqueConfig, FungibleApproveBasket, RefungibleApproveBasket,31	NftApproveBasket, CreateItemBasket, ReFungibleTransferBasket, FungibleTransferBasket,32	NftTransferBasket, TokenPropertyBasket,33};34use pallet_fungible::Config as FungibleConfig;35use pallet_nonfungible::Config as NonfungibleConfig;36use pallet_refungible::Config as RefungibleConfig;3738pub trait Config: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig {}39impl<T> Config for T where T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig {}4041// TODO: permission check?42pub fn withdraw_set_existing_token_property<T: Config>(43	collection: &CollectionHandle<T>,44	who: &T::CrossAccountId,45	item_id: &TokenId,46	data_size: usize,47) -> Option<()> {48	// preliminary sponsoring correctness check49	match collection.mode {50		CollectionMode::NFT => {51			let owner = pallet_nonfungible::TokenData::<T>::get((collection.id, item_id))?.owner;52			if !owner.conv_eq(who) {53				return None;54			}55		}56		CollectionMode::Fungible(_) => {57			// Fungible tokens have no properties58			return None;59		}60		CollectionMode::ReFungible => {61			if !<pallet_refungible::Owned<T>>::get((collection.id, who, item_id)) {62				return None;63			}64		}65	}6667	withdraw_set_token_property(collection, item_id, data_size)68}6970pub fn withdraw_set_token_property<T: Config>(71	collection: &CollectionHandle<T>,72	item_id: &TokenId,73	data_size: usize,74) -> Option<()> {75	if data_size == 0 {76		return Some(());77	}78	if data_size > collection.limits.sponsored_data_size() as usize {79		return None;80	}8182	let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;83	let limit = collection.limits.sponsored_data_rate_limit()?;8485	if let Some(last_tx_block) = TokenPropertyBasket::<T>::get(collection.id, item_id) {86		let timeout = last_tx_block + limit.into();87		if block_number < timeout {88			return None;89		}90	}9192	<TokenPropertyBasket<T>>::insert(collection.id, item_id, block_number);9394	Some(())95}9697pub fn withdraw_transfer<T: Config>(98	collection: &CollectionHandle<T>,99	who: &T::CrossAccountId,100	item_id: &TokenId,101) -> Option<()> {102	// preliminary sponsoring correctness check103	match collection.mode {104		CollectionMode::NFT => {105			let owner = pallet_nonfungible::TokenData::<T>::get((collection.id, item_id))?.owner;106			if !owner.conv_eq(who) {107				return None;108			}109		}110		CollectionMode::Fungible(_) => {111			if item_id != &TokenId::default() {112				return None;113			}114			if <pallet_fungible::Balance<T>>::get((collection.id, who)) == 0 {115				return None;116			}117		}118		CollectionMode::ReFungible => {119			if !<pallet_refungible::Owned<T>>::get((collection.id, who, item_id)) {120				return None;121			}122		}123	}124125	// sponsor timeout126	let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;127	let limit = collection128		.limits129		.sponsor_transfer_timeout(match collection.mode {130			CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,131			CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,132			CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,133		});134135	let last_tx_block = match collection.mode {136		CollectionMode::NFT => <NftTransferBasket<T>>::get(collection.id, item_id),137		CollectionMode::Fungible(_) => {138			<FungibleTransferBasket<T>>::get(collection.id, who.as_sub())139		}140		CollectionMode::ReFungible => {141			<ReFungibleTransferBasket<T>>::get((collection.id, item_id, who.as_sub()))142		}143	};144145	if let Some(last_tx_block) = last_tx_block {146		let timeout = last_tx_block + limit.into();147		if block_number < timeout {148			return None;149		}150	}151152	match collection.mode {153		CollectionMode::NFT => <NftTransferBasket<T>>::insert(collection.id, item_id, block_number),154		CollectionMode::Fungible(_) => {155			<FungibleTransferBasket<T>>::insert(collection.id, who.as_sub(), block_number)156		}157		CollectionMode::ReFungible => <ReFungibleTransferBasket<T>>::insert(158			(collection.id, item_id, who.as_sub()),159			block_number,160		),161	};162163	Some(())164}165166pub fn withdraw_create_item<T: Config>(167	collection: &CollectionHandle<T>,168	who: &T::CrossAccountId,169	properties: &CreateItemData,170) -> Option<()> {171	// sponsor timeout172	let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;173	let limit = collection174		.limits175		.sponsor_transfer_timeout(match properties {176			CreateItemData::NFT(_) => NFT_SPONSOR_TRANSFER_TIMEOUT,177			CreateItemData::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,178			CreateItemData::ReFungible(_) => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,179		});180181	if let Some(last_tx_block) = <CreateItemBasket<T>>::get((collection.id, who.as_sub())) {182		let timeout = last_tx_block + limit.into();183		if block_number < timeout {184			return None;185		}186	}187	CreateItemBasket::<T>::insert((collection.id, who.as_sub()), block_number);188189	Some(())190}191192pub fn withdraw_approve<T: Config>(193	collection: &CollectionHandle<T>,194	who: &T::AccountId,195	item_id: &TokenId,196) -> Option<()> {197	// sponsor timeout198	let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;199	let limit = collection.limits.sponsor_approve_timeout();200201	let last_tx_block = match collection.mode {202		CollectionMode::NFT => <NftApproveBasket<T>>::get(collection.id, item_id),203		CollectionMode::Fungible(_) => <FungibleApproveBasket<T>>::get(collection.id, who),204		CollectionMode::ReFungible => {205			<RefungibleApproveBasket<T>>::get((collection.id, item_id, who))206		}207	};208209	if let Some(last_tx_block) = last_tx_block {210		let timeout = last_tx_block + limit.into();211		if block_number < timeout {212			return None;213		}214	}215216	match collection.mode {217		CollectionMode::NFT => <NftApproveBasket<T>>::insert(collection.id, item_id, block_number),218		CollectionMode::Fungible(_) => {219			<FungibleApproveBasket<T>>::insert(collection.id, who, block_number)220		}221		CollectionMode::ReFungible => {222			<RefungibleApproveBasket<T>>::insert((collection.id, item_id, who), block_number)223		}224	};225226	Some(())227}228229fn load<T: UniqueConfig>(id: CollectionId) -> Option<(T::AccountId, CollectionHandle<T>)> {230	let collection = CollectionHandle::new(id)?;231	let sponsor = collection.sponsorship.sponsor().cloned()?;232	Some((sponsor, collection))233}234235pub struct UniqueSponsorshipHandler<T>(PhantomData<T>);236impl<T, C> SponsorshipHandler<T::AccountId, C> for UniqueSponsorshipHandler<T>237where238	T: Config,239	C: IsSubType<UniqueCall<T>>,240{241	fn get_sponsor(who: &T::AccountId, call: &C) -> Option<T::AccountId> {242		match IsSubType::<UniqueCall<T>>::is_sub_type(call)? {243			UniqueCall::set_token_properties {244				collection_id,245				token_id,246				properties,247				..248			} => {249				let (sponsor, collection) = load::<T>(*collection_id)?;250				withdraw_set_existing_token_property(251					&collection,252					&T::CrossAccountId::from_sub(who.clone()),253					token_id,254					// No overflow may happen, as data larger than usize can't reach here255					properties.iter().map(|p| p.key.len() + p.value.len()).sum(),256				)257				.map(|()| sponsor)258			}259			UniqueCall::create_item {260				collection_id,261				data,262				..263			} => {264				let (sponsor, collection) = load(*collection_id)?;265				withdraw_create_item::<T>(266					&collection,267					&T::CrossAccountId::from_sub(who.clone()),268					data,269				)270				.map(|()| sponsor)271			}272			UniqueCall::transfer {273				collection_id,274				item_id,275				..276			} => {277				let (sponsor, collection) = load(*collection_id)?;278				withdraw_transfer::<T>(279					&collection,280					&T::CrossAccountId::from_sub(who.clone()),281					item_id,282				)283				.map(|()| sponsor)284			}285			UniqueCall::transfer_from {286				collection_id,287				item_id,288				from,289				..290			} => {291				let (sponsor, collection) = load(*collection_id)?;292				withdraw_transfer::<T>(&collection, from, item_id).map(|()| sponsor)293			}294			UniqueCall::approve {295				collection_id,296				item_id,297				..298			} => {299				let (sponsor, collection) = load(*collection_id)?;300				withdraw_approve::<T>(&collection, who, item_id).map(|()| sponsor)301			}302			_ => None,303		}304	}305}306307pub trait SponsorshipPredict<T: Config> {308	fn predict(collection: CollectionId, account: T::CrossAccountId, token: TokenId) -> Option<u64>309	where310		u64: From<<T as frame_system::Config>::BlockNumber>;311}312313pub struct UniqueSponsorshipPredict<T>(PhantomData<T>);314315impl<T: Config> SponsorshipPredict<T> for UniqueSponsorshipPredict<T> {316	fn predict(collection_id: CollectionId, who: T::CrossAccountId, token: TokenId) -> Option<u64>317	where318		u64: From<<T as frame_system::Config>::BlockNumber>,319	{320		let collection = <CollectionHandle<T>>::try_get(collection_id).ok()?;321		let _ = collection.sponsorship.sponsor()?;322323		// sponsor timeout324		let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;325		let limit = collection326			.limits327			.sponsor_transfer_timeout(match collection.mode {328				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,329				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,330				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,331			});332333		let last_tx_block = match collection.mode {334			CollectionMode::NFT => <NftTransferBasket<T>>::get(collection.id, token),335			CollectionMode::Fungible(_) => {336				<FungibleTransferBasket<T>>::get(collection.id, who.as_sub())337			}338			CollectionMode::ReFungible => {339				<ReFungibleTransferBasket<T>>::get((collection.id, token, who.as_sub()))340			}341		};342343		if let Some(last_tx_block) = last_tx_block {344			return Some(345				last_tx_block346					.saturating_add(limit.into())347					.saturating_sub(block_number)348					.into(),349			);350		}351352		let token_exists = match collection.mode {353			CollectionMode::NFT => {354				<pallet_nonfungible::TokenData<T>>::contains_key((collection.id, token))355			}356			CollectionMode::Fungible(_) => token == TokenId::default(),357			CollectionMode::ReFungible => {358				<pallet_refungible::TotalSupply<T>>::contains_key((collection.id, token))359			}360		};361362		if token_exists {363			Some(0)364		} else {365			None366		}367	}368}
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})),