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
--- a/runtime/common/sponsoring.rs
+++ b/runtime/common/sponsoring.rs
@@ -39,7 +39,7 @@
 impl<T> Config for T where T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig {}
 
 // TODO: permission check?
-pub fn withdraw_set_token_property<T: Config>(
+pub fn withdraw_set_existing_token_property<T: Config>(
 	collection: &CollectionHandle<T>,
 	who: &T::CrossAccountId,
 	item_id: &TokenId,
@@ -64,6 +64,17 @@
 		}
 	}
 
+	withdraw_set_token_property(collection, item_id, data_size)
+}
+
+pub fn withdraw_set_token_property<T: Config>(
+	collection: &CollectionHandle<T>,
+	item_id: &TokenId,
+	data_size: usize,
+) -> Option<()> {
+	if data_size == 0 {
+		return Some(());
+	}
 	if data_size > collection.limits.sponsored_data_size() as usize {
 		return None;
 	}
@@ -173,7 +184,6 @@
 			return None;
 		}
 	}
-
 	CreateItemBasket::<T>::insert((collection.id, who.as_sub()), block_number);
 
 	Some(())
@@ -237,7 +247,7 @@
 				..
 			} => {
 				let (sponsor, collection) = load::<T>(*collection_id)?;
-				withdraw_set_token_property(
+				withdraw_set_existing_token_property(
 					&collection,
 					&T::CrossAccountId::from_sub(who.clone()),
 					token_id,
modifiedruntime/tests/Cargo.tomldiffbeforeafterboth
--- a/runtime/tests/Cargo.toml
+++ b/runtime/tests/Cargo.toml
@@ -5,6 +5,7 @@
 
 [features]
 default = ['refungible']
+tests = ['pallet-common/tests']
 
 refungible = []
 
modifiedruntime/tests/src/tests.rsdiffbeforeafterboth
--- a/runtime/tests/src/tests.rs
+++ b/runtime/tests/src/tests.rs
@@ -1737,6 +1737,11 @@
 		let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
 
 		let origin1 = RuntimeOrigin::signed(1);
+		assert_ok!(Unique::add_collection_admin(
+			origin1.clone(),
+			collection_id,
+			account(1)
+		));
 
 		let data = default_nft_data();
 		create_test_item(collection_id, &data.into());
@@ -2610,3 +2615,67 @@
 		));
 	});
 }
+
+mod check_token_permissions {
+	use super::*;
+	use frame_support::once_cell::sync::Lazy;
+	use pallet_common::LazyValue;
+	use sp_runtime::DispatchError;
+
+	fn test<FTE: FnOnce() -> bool>(
+		i: usize,
+		test_case: &pallet_common::tests::TestCase,
+		check_token_existence: &mut LazyValue<bool, FTE>,
+	) {
+		let collection_admin = test_case.collection_admin;
+		let mut is_collection_admin = LazyValue::new(|| test_case.is_collection_admin);
+		let token_owner = test_case.token_owner;
+		let mut is_token_owner = LazyValue::new(|| Ok(test_case.is_token_owner));
+		let is_no_permission = test_case.no_permission;
+
+		let result = pallet_common::tests::check_token_permissions::<Test, _, _, FTE>(
+			collection_admin,
+			token_owner,
+			&mut is_collection_admin,
+			&mut is_token_owner,
+			check_token_existence,
+		);
+
+		if is_no_permission {
+			assert!(
+				result.is_err(),
+				"{i}: {test_case:?}, token_exist: {}",
+				check_token_existence.value()
+			);
+			assert_err!(result, pallet_common::Error::<Test>::NoPermission,);
+		} else if check_token_existence.has_value() && !check_token_existence.value() {
+			assert!(
+				result.is_err(),
+				"{i}: {test_case:?}, token_exist: {}",
+				check_token_existence.value()
+			);
+			assert_err!(result, pallet_common::Error::<Test>::TokenNotFound,);
+		}
+	}
+
+	#[test]
+	fn no_permission_only() {
+		new_test_ext().execute_with(|| {
+			let mut check_token_existence = LazyValue::new(|| true);
+			for (i, row) in pallet_common::tests::table.iter().enumerate() {
+				test(i, row, &mut check_token_existence);
+			}
+		});
+	}
+
+	#[test]
+	fn no_permission_and_token_not_found() {
+		new_test_ext().execute_with(|| {
+			for (i, row) in pallet_common::tests::table.iter().enumerate() {
+				// This is inside the loop to keep track of whether the lambda was called
+				let mut check_token_existence = LazyValue::new(|| false);
+				test(i, row, &mut check_token_existence);
+			}
+		});
+	}
+}
modifiedtests/src/createMultipleItemsEx.test.tsdiffbeforeafterboth
--- a/tests/src/createMultipleItemsEx.test.ts
+++ b/tests/src/createMultipleItemsEx.test.ts
@@ -195,7 +195,7 @@
       description: 'descr',
       tokenPrefix: 'COL',
       tokenPropertyPermissions: [
-        {key: 'k', permission: {tokenOwner: true, mutable: false, collectionAdmin: false}},
+        {key: 'k', permission: {tokenOwner: false, mutable: false, collectionAdmin: true}},
       ],
     });
 
modifiedtests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth
before · tests/src/eth/collectionSponsoring.test.ts
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/>.1617import {IKeyringPair} from '@polkadot/types/types';18import {Pallets, requirePalletsOrSkip, usingPlaygrounds} from '../util/index';19import {itEth, expect} from './util';2021describe('evm nft collection sponsoring', () => {22  let donor: IKeyringPair;23  let alice: IKeyringPair;24  let nominal: bigint;2526  before(async () => {27    await usingPlaygrounds(async (helper, privateKey) => {28      donor = await privateKey({url: import.meta.url});29      [alice] = await helper.arrange.createAccounts([100n], donor);30      nominal = helper.balance.getOneTokenNominal();31    });32  });3334  // TODO: move to substrate tests35  itEth('sponsors mint transactions', async ({helper}) => {36    const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'spnr', permissions: {mintMode: true}});37    await collection.setSponsor(alice, alice.address);38    await collection.confirmSponsorship(alice);3940    const minter = helper.eth.createAccount();41    expect(await helper.balance.getEthereum(minter)).to.equal(0n);4243    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);44    const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', minter);4546    await collection.addToAllowList(alice, {Ethereum: minter});4748    const result = await contract.methods.mint(minter).send();4950    const events = helper.eth.normalizeEvents(result.events);51    expect(events).to.be.deep.equal([52      {53        address: collectionAddress,54        event: 'Transfer',55        args: {56          from: '0x0000000000000000000000000000000000000000',57          to: minter,58          tokenId: '1',59        },60      },61    ]);62  });6364  // TODO: Temprorary off. Need refactor65  // itWeb3('Set substrate sponsor', async ({api, web3, privateKeyWrapper}) => {66  //   const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);67  //   const collectionHelpers = evmCollectionHelpers(web3, owner);68  //   let result = await collectionHelpers.methods.createNFTCollection('Sponsor collection', '1', '1').send();69  //   const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);70  //   const sponsor = privateKeyWrapper('//Alice');71  //   const collectionEvm = evmCollection(web3, owner, collectionIdAddress);7273  //   expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;74  //   result = await collectionEvm.methods.setCollectionSponsorSubstrate(sponsor.addressRaw).send({from: owner});75  //   expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;7677  //   const confirmTx = await api.tx.unique.confirmSponsorship(collectionId);78  //   await submitTransactionAsync(sponsor, confirmTx);79  //   expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;8081  //   const sponsorTuple = await collectionEvm.methods.collectionSponsor().call({from: owner});82  //   expect(bigIntToSub(api, BigInt(sponsorTuple[1]))).to.be.eq(sponsor.address);83  // });8485  [86    'setCollectionSponsorCross',87    'setCollectionSponsor', // Soft-deprecated88  ].map(testCase =>89    itEth(`[${testCase}] can remove collection sponsor`, async ({helper}) => {90      const owner = await helper.eth.createAccountWithBalance(donor);91      const collectionHelpers = await helper.ethNativeContract.collectionHelpers(owner);9293      let result = await collectionHelpers.methods.createNFTCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});94      const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);95      const sponsor = await helper.eth.createAccountWithBalance(donor);96      const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);97      const collectionEvm = await helper.ethNativeContract.collection(collectionIdAddress, 'nft', owner, testCase === 'setCollectionSponsor');9899      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;100      result = await collectionEvm.methods[testCase](testCase === 'setCollectionSponsor' ? sponsor : sponsorCross).send({from: owner});101      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;102103      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});104      let sponsorStruct = await collectionEvm.methods.collectionSponsor().call({from: owner});105      expect(helper.address.restoreCrossAccountFromBigInt(BigInt(sponsorStruct.sub))).to.be.eq(helper.address.ethToSubstrate(sponsor, true));106      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;107108      await collectionEvm.methods.removeCollectionSponsor().send({from: owner});109110      sponsorStruct = await collectionEvm.methods.collectionSponsor().call({from: owner});111      expect(sponsorStruct.eth).to.be.eq('0x0000000000000000000000000000000000000000');112    }));113114  [115    'setCollectionSponsorCross',116    'setCollectionSponsor', // Soft-deprecated117  ].map(testCase =>118    itEth(`[${testCase}] Can sponsor from evm address via access list`, async ({helper}) => {119      const owner = await helper.eth.createAccountWithBalance(donor);120      const sponsorEth = await helper.eth.createAccountWithBalance(donor);121      const sponsorCrossEth = helper.ethCrossAccount.fromAddress(sponsorEth);122123      const {collectionId, collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Sponsor collection', '1', '1', '');124125      const collectionSub = helper.nft.getCollectionObject(collectionId);126      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner, testCase === 'setCollectionSponsor');127128      // Set collection sponsor:129      await collectionEvm.methods[testCase](testCase === 'setCollectionSponsor' ? sponsorEth : sponsorCrossEth).send({from: owner});130      let sponsorship = (await collectionSub.getData())!.raw.sponsorship;131      expect(sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsorEth, true));132      // Account cannot confirm sponsorship if it is not set as a sponsor133      await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmSponsorshipFail');134135      // Sponsor can confirm sponsorship:136      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsorEth});137      sponsorship = (await collectionSub.getData())!.raw.sponsorship;138      expect(sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsorEth, true));139140      // Create user with no balance:141      const user = helper.eth.createAccount();142      const userCross = helper.ethCrossAccount.fromAddress(user);143      const nextTokenId = await collectionEvm.methods.nextTokenId().call();144      expect(nextTokenId).to.be.equal('1');145146      // Set collection permissions:147      const oldPermissions = (await collectionSub.getData())!.raw.permissions;148      expect(oldPermissions.mintMode).to.be.false;149      expect(oldPermissions.access).to.be.equal('Normal');150151      await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});152      await collectionEvm.methods.addToCollectionAllowListCross(userCross).send({from: owner});153      await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});154155      const newPermissions = (await collectionSub.getData())!.raw.permissions;156      expect(newPermissions.mintMode).to.be.true;157      expect(newPermissions.access).to.be.equal('AllowList');158159      const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));160      const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));161      const userBalanceBefore =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));162163      // User can mint token without balance:164      {165        const result = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});166        const event = helper.eth.normalizeEvents(result.events)167          .find(event => event.event === 'Transfer');168169        expect(event).to.be.deep.equal({170          address: collectionAddress,171          event: 'Transfer',172          args: {173            from: '0x0000000000000000000000000000000000000000',174            to: user,175            tokenId: '1',176          },177        });178179        const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));180        const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));181        const userBalanceAfter =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));182183        expect(await collectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');184        expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);185        expect(userBalanceAfter).to.be.eq(userBalanceBefore);186        expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;187      }188    }));189190  // TODO: Temprorary off. Need refactor191  // itWeb3('Sponsoring collection from substrate address via access list', async ({api, web3, privateKeyWrapper}) => {192  //   const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);193  //   const collectionHelpers = evmCollectionHelpers(web3, owner);194  //   const result = await collectionHelpers.methods.createERC721MetadataCompatibleNFTCollection('Sponsor collection', '1', '1', '').send();195  //   const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);196  //   const sponsor = privateKeyWrapper('//Alice');197  //   const collectionEvm = evmCollection(web3, owner, collectionIdAddress);198199  //   await collectionEvm.methods.setCollectionSponsorSubstrate(sponsor.addressRaw).send({from: owner});200201  //   const confirmTx = await api.tx.unique.confirmSponsorship(collectionId);202  //   await submitTransactionAsync(sponsor, confirmTx);203204  //   const user = createEthAccount(web3);205  //   const nextTokenId = await collectionEvm.methods.nextTokenId().call();206  //   expect(nextTokenId).to.be.equal('1');207208  //   await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});209  //   await collectionEvm.methods.addToCollectionAllowList(user).send({from: owner});210  //   await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});211212  //   const ownerBalanceBefore = await ethBalanceViaSub(api, owner);213  //   const sponsorBalanceBefore = (await getBalance(api, [sponsor.address]))[0];214215  //   {216  //     const nextTokenId = await collectionEvm.methods.nextTokenId().call();217  //     expect(nextTokenId).to.be.equal('1');218  //     const result = await collectionEvm.methods.mintWithTokenURI(219  //       user,220  //       nextTokenId,221  //       'Test URI',222  //     ).send({from: user});223  //     const events = normalizeEvents(result.events);224225  //     expect(events).to.be.deep.equal([226  //       {227  //         address: collectionIdAddress,228  //         event: 'Transfer',229  //         args: {230  //           from: '0x0000000000000000000000000000000000000000',231  //           to: user,232  //           tokenId: nextTokenId,233  //         },234  //       },235  //     ]);236237  //     const ownerBalanceAfter = await ethBalanceViaSub(api, owner);238  //     const sponsorBalanceAfter = (await getBalance(api, [sponsor.address]))[0];239240  //     expect(await collectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');241  //     expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);242  //     expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;243  //   }244  // });245246  [247    'setCollectionSponsorCross',248    'setCollectionSponsor', // Soft-deprecated249  ].map(testCase =>250    itEth(`[${testCase}] Check that transaction via EVM spend money from sponsor address`, async ({helper}) => {251      const owner = await helper.eth.createAccountWithBalance(donor);252      const sponsor = await helper.eth.createAccountWithBalance(donor);253      const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);254255      const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner,'Sponsor collection', '1', '1', '');256257      const collectionSub = helper.nft.getCollectionObject(collectionId);258      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner, testCase === 'setCollectionSponsor');259      // Set collection sponsor:260      await collectionEvm.methods[testCase](testCase === 'setCollectionSponsor' ? sponsor : sponsorCross).send();261      let collectionData = (await collectionSub.getData())!;262      expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));263      await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmSponsorshipFail');264265      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});266      collectionData = (await collectionSub.getData())!;267      expect(collectionData.raw.sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));268269      const user = helper.eth.createAccount();270      const userCross = helper.ethCrossAccount.fromAddress(user);271      await collectionEvm.methods.addCollectionAdminCross(userCross).send();272273      const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));274      const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));275276      const mintingResult = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});277      const tokenId = mintingResult.events.Transfer.returnValues.tokenId;278279      const event = helper.eth.normalizeEvents(mintingResult.events)280        .find(event => event.event === 'Transfer');281      const address = helper.ethAddress.fromCollectionId(collectionId);282283      expect(event).to.be.deep.equal({284        address,285        event: 'Transfer',286        args: {287          from: '0x0000000000000000000000000000000000000000',288          to: user,289          tokenId: '1',290        },291      });292      expect(await collectionEvm.methods.tokenURI(tokenId).call({from: user})).to.be.equal('Test URI');293294      const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));295      expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);296      const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));297      expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;298    }));299300  itEth('Can reassign collection sponsor', async ({helper}) => {301    const owner = await helper.eth.createAccountWithBalance(donor);302    const sponsorEth = await helper.eth.createAccountWithBalance(donor);303    const sponsorCrossEth = helper.ethCrossAccount.fromAddress(sponsorEth);304    const [sponsorSub] = await helper.arrange.createAccounts([100n], donor);305    const sponsorCrossSub = helper.ethCrossAccount.fromKeyringPair(sponsorSub);306307    const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner,'Sponsor collection', '1', '1', '');308    const collectionSub = helper.nft.getCollectionObject(collectionId);309    const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);310311    // Set and confirm sponsor:312    await collectionEvm.methods.setCollectionSponsorCross(sponsorCrossEth).send({from: owner});313    await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsorEth});314315    // Can reassign sponsor:316    await collectionEvm.methods.setCollectionSponsorCross(sponsorCrossSub).send({from: owner});317    const collectionSponsor = (await collectionSub.getData())?.raw.sponsorship;318    expect(collectionSponsor).to.deep.eq({Unconfirmed: sponsorSub.address});319  });320});321322describe('evm RFT collection sponsoring', () => {323  let donor: IKeyringPair;324  let alice: IKeyringPair;325  let nominal: bigint;326327  before(async function() {328    await usingPlaygrounds(async (helper, privateKey) => {329      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);330      donor = await privateKey({url: import.meta.url});331      [alice] = await helper.arrange.createAccounts([100n], donor);332      nominal = helper.balance.getOneTokenNominal();333    });334  });335336  [337    'mintCross',338    'mintWithTokenURI',339  ].map(testCase =>340    itEth(`[${testCase}] sponsors mint transactions`, async ({helper}) => {341      const collection = await helper.rft.mintCollection(alice, {tokenPrefix: 'spnr', permissions: {mintMode: true}, tokenPropertyPermissions: [342        {key: 'URI', permission: {tokenOwner: true, mutable: true, collectionAdmin: true}},343      ]});344345      const owner = await helper.eth.createAccountWithBalance(donor);346      await collection.setSponsor(alice, alice.address);347      await collection.confirmSponsorship(alice);348349      const minter = helper.eth.createAccount();350      const minterCross = helper.ethCrossAccount.fromAddress(minter);351      expect(await helper.balance.getEthereum(minter)).to.equal(0n);352353      const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);354      const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', minter, true);355356      await collection.addToAllowList(alice, {Ethereum: minter});357      await collection.addAdmin(alice, {Ethereum: owner});358      const collectionHelpers = await helper.ethNativeContract.collectionHelpers(owner);359      await collectionHelpers.methods.makeCollectionERC721MetadataCompatible(collectionAddress, 'base/')360        .send();361362      let mintingResult;363      let tokenId;364      switch (testCase) {365        case 'mintCross':366          mintingResult = await contract.methods.mintCross(minterCross, []).send();367          break;368        case 'mintWithTokenURI':369          mintingResult = await contract.methods.mintWithTokenURI(minter, 'Test URI').send();370          tokenId = mintingResult.events.Transfer.returnValues.tokenId;371          expect(await contract.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');372          break;373      }374375      const events = helper.eth.normalizeEvents(mintingResult.events);376      expect(events).to.deep.include({377        address: collectionAddress,378        event: 'Transfer',379        args: {380          from: '0x0000000000000000000000000000000000000000',381          to: minter,382          tokenId: '1',383        },384      });385    }));386387  [388    'setCollectionSponsorCross',389    'setCollectionSponsor', // Soft-deprecated390  ].map(testCase =>391    itEth(`[${testCase}] can remove collection sponsor`, async ({helper}) => {392      const owner = await helper.eth.createAccountWithBalance(donor);393      const collectionHelpers = await helper.ethNativeContract.collectionHelpers(owner);394395      let result = await collectionHelpers.methods.createRFTCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});396      const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);397      const sponsor = await helper.eth.createAccountWithBalance(donor);398      const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);399      const collectionEvm = await helper.ethNativeContract.collection(collectionIdAddress, 'rft', owner, testCase === 'setCollectionSponsor');400401      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;402      result = await collectionEvm.methods[testCase](testCase === 'setCollectionSponsor' ? sponsor : sponsorCross).send({from: owner});403      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;404405      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});406      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;407408      await collectionEvm.methods.removeCollectionSponsor().send({from: owner});409410      const sponsorStruct = await collectionEvm.methods.collectionSponsor().call({from: owner});411      expect(sponsorStruct.eth).to.be.eq('0x0000000000000000000000000000000000000000');412    }));413414  [415    'setCollectionSponsorCross',416    'setCollectionSponsor', // Soft-deprecated417  ].map(testCase =>418    itEth(`[${testCase}] Can sponsor from evm address via access list`, async ({helper}) => {419      const owner = await helper.eth.createAccountWithBalance(donor);420      const sponsorEth = await helper.eth.createAccountWithBalance(donor);421      const sponsorCrossEth = helper.ethCrossAccount.fromAddress(sponsorEth);422423      const {collectionId, collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'Sponsor collection', '1', '1', '');424425      const collectionSub = helper.rft.getCollectionObject(collectionId);426      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner, testCase === 'setCollectionSponsor');427428      // Set collection sponsor:429      await collectionEvm.methods[testCase](testCase === 'setCollectionSponsor' ? sponsorEth : sponsorCrossEth).send({from: owner});430      let sponsorship = (await collectionSub.getData())!.raw.sponsorship;431      expect(sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsorEth, true));432      // Account cannot confirm sponsorship if it is not set as a sponsor433      await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmSponsorshipFail');434435      // Sponsor can confirm sponsorship:436      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsorEth});437      sponsorship = (await collectionSub.getData())!.raw.sponsorship;438      expect(sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsorEth, true));439440      // Create user with no balance:441      const user = helper.eth.createAccount();442      const userCross = helper.ethCrossAccount.fromAddress(user);443      const nextTokenId = await collectionEvm.methods.nextTokenId().call();444      expect(nextTokenId).to.be.equal('1');445446      // Set collection permissions:447      const oldPermissions = (await collectionSub.getData())!.raw.permissions;448      expect(oldPermissions.mintMode).to.be.false;449      expect(oldPermissions.access).to.be.equal('Normal');450451      await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});452      await collectionEvm.methods.addToCollectionAllowListCross(userCross).send({from: owner});453      await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});454455      const newPermissions = (await collectionSub.getData())!.raw.permissions;456      expect(newPermissions.mintMode).to.be.true;457      expect(newPermissions.access).to.be.equal('AllowList');458459      const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));460      const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));461      const userBalanceBefore =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));462463      // User can mint token without balance:464      {465        const result = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});466        const events = helper.eth.normalizeEvents(result.events);467468        expect(events).to.deep.include({469          address: collectionAddress,470          event: 'Transfer',471          args: {472            from: '0x0000000000000000000000000000000000000000',473            to: user,474            tokenId: '1',475          },476        });477478        const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));479        const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));480        const userBalanceAfter =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));481482        expect(await collectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');483        expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);484        expect(userBalanceAfter).to.be.eq(userBalanceBefore);485        expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;486      }487    }));488489  [490    'setCollectionSponsorCross',491    'setCollectionSponsor', // Soft-deprecated492  ].map(testCase =>493    itEth(`[${testCase}] Check that collection admin EVM transaction spend money from sponsor eth address`, async ({helper}) => {494      const owner = await helper.eth.createAccountWithBalance(donor);495      const sponsor = await helper.eth.createAccountWithBalance(donor);496      const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);497498      const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner,'Sponsor collection', '1', '1', '');499500      const collectionSub = helper.rft.getCollectionObject(collectionId);501      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner, testCase === 'setCollectionSponsor');502      // Set collection sponsor:503      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call()).to.be.false;504      await collectionEvm.methods[testCase](testCase === 'setCollectionSponsor' ? sponsor : sponsorCross).send();505      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call()).to.be.true;506      let collectionData = (await collectionSub.getData())!;507      expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));508      await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmSponsorshipFail');509      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call()).to.be.true;510511      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});512      collectionData = (await collectionSub.getData())!;513      expect(collectionData.raw.sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));514      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call()).to.be.false;515      const sponsorStruct = await collectionEvm.methods.collectionSponsor().call({from: owner});516      const sponsorSubAddress = helper.address.normalizeSubstrateToChainFormat(helper.address.ethToSubstrate(sponsor));517      const actualSubAddress = helper.address.normalizeSubstrateToChainFormat(helper.address.restoreCrossAccountFromBigInt(BigInt(sponsorStruct.sub)));518      expect(actualSubAddress).to.be.equal(sponsorSubAddress);519520      const user = helper.eth.createAccount();521      const userCross = helper.ethCrossAccount.fromAddress(user);522      await collectionEvm.methods.addCollectionAdminCross(userCross).send();523524      const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));525      const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));526527      const mintingResult = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});528      const tokenId = mintingResult.events.Transfer.returnValues.tokenId;529530      const events = helper.eth.normalizeEvents(mintingResult.events);531      const address = helper.ethAddress.fromCollectionId(collectionId);532533      expect(events).to.deep.include({534        address,535        event: 'Transfer',536        args: {537          from: '0x0000000000000000000000000000000000000000',538          to: user,539          tokenId: '1',540        },541      });542      expect(await collectionEvm.methods.tokenURI(tokenId).call({from: user})).to.be.equal('Test URI');543544      const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));545      expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);546      const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));547      expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;548    }));549550  itEth('Check that collection admin EVM transaction spend money from sponsor sub address', async ({helper}) => {551    const owner = await helper.eth.createAccountWithBalance(donor);552    const sponsor = alice;553    const sponsorCross = helper.ethCrossAccount.fromKeyringPair(sponsor);554555    const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner,'Sponsor collection', '1', '1', '');556557    const collectionSub = helper.rft.getCollectionObject(collectionId);558    const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'rft', owner, false);559    // Set collection sponsor:560    expect(await collectionEvm.methods.hasCollectionPendingSponsor().call()).to.be.false;561    await collectionEvm.methods.setCollectionSponsorCross(sponsorCross).send();562    expect(await collectionEvm.methods.hasCollectionPendingSponsor().call()).to.be.true;563    let collectionData = (await collectionSub.getData())!;564    expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(sponsor.address);565    await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmSponsorshipFail');566567    await collectionSub.confirmSponsorship(sponsor);568    collectionData = (await collectionSub.getData())!;569    expect(collectionData.raw.sponsorship.Confirmed).to.be.eq(sponsor.address);570    expect(await collectionEvm.methods.hasCollectionPendingSponsor().call()).to.be.false;571    const sponsorStruct = await collectionEvm.methods.collectionSponsor().call({from: owner});572    expect(BigInt(sponsorStruct.sub)).to.be.equal(BigInt('0x' + Buffer.from(sponsor.addressRaw).toString('hex')));573574    const user = helper.eth.createAccount();575    const userCross = helper.ethCrossAccount.fromAddress(user);576    await collectionEvm.methods.addCollectionAdminCross(userCross).send();577578    const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));579    const sponsorBalanceBefore = await helper.balance.getSubstrate(sponsor.address);580581    const mintingResult = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});582    const tokenId = mintingResult.events.Transfer.returnValues.tokenId;583584    const events = helper.eth.normalizeEvents(mintingResult.events);585586    expect(events).to.deep.include({587      address: collectionAddress,588      event: 'Transfer',589      args: {590        from: '0x0000000000000000000000000000000000000000',591        to: user,592        tokenId: '1',593      },594    });595    expect(await collectionEvm.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');596597    const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));598    expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);599    const sponsorBalanceAfter = await helper.balance.getSubstrate(sponsor.address);600    expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;601  });602603  itEth('Sponsoring collection from substrate address via access list', async ({helper}) => {604    const owner = await helper.eth.createAccountWithBalance(donor);605    const user = helper.eth.createAccount();606    const userCross =  helper.ethCrossAccount.fromAddress(user);607    const sponsor = alice;608    const sponsorCross = helper.ethCrossAccount.fromKeyringPair(sponsor);609610    const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner,'Sponsor collection', '1', '1', '');611    const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner, false);612613    await collectionEvm.methods.setCollectionSponsorCross(sponsorCross).send({from: owner});614615    const collectionSub = helper.rft.getCollectionObject(collectionId);616    await collectionSub.confirmSponsorship(sponsor);617618    const nextTokenId = await collectionEvm.methods.nextTokenId().call();619    expect(nextTokenId).to.be.equal('1');620621    await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});622623    await collectionEvm.methods.addToCollectionAllowListCross(userCross).send({from: owner});624    await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});625626    const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));627    const sponsorBalanceBefore = await helper.balance.getSubstrate(sponsor.address);628    const userBalanceBefore =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));629630    {631      const nextTokenId = await collectionEvm.methods.nextTokenId().call();632      expect(nextTokenId).to.be.equal('1');633      const mintingResult = await collectionEvm.methods.mintWithTokenURI(634        user,635        'Test URI',636      ).send({from: user});637638      const events = helper.eth.normalizeEvents(mintingResult.events);639640641      expect(events).to.deep.include({642        address: collectionAddress,643        event: 'Transfer',644        args: {645          from: '0x0000000000000000000000000000000000000000',646          to: user,647          tokenId: nextTokenId,648        },649      });650651      const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));652      const sponsorBalanceAfter = await helper.balance.getSubstrate(sponsor.address);653      const userBalanceAfter =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));654655      expect(await collectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');656      expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);657      expect(userBalanceAfter).to.be.eq(userBalanceBefore);658      expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;659    }660  });661662  itEth('Can reassign collection sponsor', async ({helper}) => {663    const owner = await helper.eth.createAccountWithBalance(donor);664    const sponsorEth = await helper.eth.createAccountWithBalance(donor);665    const sponsorCrossEth = helper.ethCrossAccount.fromAddress(sponsorEth);666    const [sponsorSub] = await helper.arrange.createAccounts([100n], donor);667    const sponsorCrossSub = helper.ethCrossAccount.fromKeyringPair(sponsorSub);668669    const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner,'Sponsor collection', '1', '1', '');670    const collectionSub = helper.rft.getCollectionObject(collectionId);671    const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);672673    // Set and confirm sponsor:674    await collectionEvm.methods.setCollectionSponsorCross(sponsorCrossEth).send({from: owner});675    await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsorEth});676677    // Can reassign sponsor:678    await collectionEvm.methods.setCollectionSponsorCross(sponsorCrossSub).send({from: owner});679    const collectionSponsor = (await collectionSub.getData())?.raw.sponsorship;680    expect(collectionSponsor).to.deep.eq({Unconfirmed: sponsorSub.address});681  });682683  [684    'transfer',685    'transferCross',686    'transferFrom',687    'transferFromCross',688  ].map(testCase =>689    itEth(`[${testCase}] Check that transfer via EVM spend money from sponsor address`, async ({helper}) => {690      const owner = await helper.eth.createAccountWithBalance(donor);691692      const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner,'Sponsor collection', '1', '1', '');693      const sponsor = await helper.eth.createAccountWithBalance(donor);694      const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);695      const receiver = await helper.eth.createAccountWithBalance(donor);696      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);697698      await collectionEvm.methods.setCollectionSponsorCross(sponsorCross).send();699      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});700701      const user = await helper.eth.createAccountWithBalance(donor);702      const userCross = helper.ethCrossAccount.fromAddress(user);703      await collectionEvm.methods.addCollectionAdminCross(userCross).send();704705      const result = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});706      const tokenId = result.events.Transfer.returnValues.tokenId;707708      const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));709      const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));710      const userBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));711712      switch (testCase) {713        case 'transfer':714          await collectionEvm.methods.transfer(receiver, tokenId).send({from: user});715          break;716        case 'transferCross':717          await collectionEvm.methods.transferCross(helper.ethCrossAccount.fromAddress(receiver), tokenId).send({from: user});718          break;719        case 'transferFrom':720          await collectionEvm.methods.transferFrom(user, receiver, tokenId).send({from: user});721          break;722        case 'transferFromCross':723          await collectionEvm.methods.transferFromCross(helper.ethCrossAccount.fromAddress(user), helper.ethCrossAccount.fromAddress(receiver), tokenId).send({from: user});724          break;725      }726727      const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));728      expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);729      const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));730      expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;731      const userBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));732      expect(userBalanceAfter).to.be.eq(userBalanceBefore);733    }));734});735736describe('evm RFT token sponsoring', () => {737  let donor: IKeyringPair;738739  before(async function() {740    await usingPlaygrounds(async (helper, privateKey) => {741      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);742      donor = await privateKey({url: import.meta.url});743    });744  });745746  [747    'transfer',748    'transferCross',749    'transferFrom',750    'transferFromCross',751  ].map(testCase =>752    itEth(`[${testCase}] Check that token piece transfer via EVM spend money from sponsor address`, async ({helper}) => {753      const owner = await helper.eth.createAccountWithBalance(donor);754755      const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner,'Sponsor collection', '1', '1', '');756      const sponsor = await helper.eth.createAccountWithBalance(donor);757      const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);758      const receiver = await helper.eth.createAccountWithBalance(donor);759      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);760761      await collectionEvm.methods.setCollectionSponsorCross(sponsorCross).send();762      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});763764      const user = await helper.eth.createAccountWithBalance(donor);765      const userCross = helper.ethCrossAccount.fromAddress(user);766      await collectionEvm.methods.addCollectionAdminCross(userCross).send();767768      const result = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});769      const tokenId = result.events.Transfer.returnValues.tokenId;770771      const tokenContract = await helper.ethNativeContract.rftTokenById(collectionId, tokenId, user);772      await tokenContract.methods.repartition(2).send();773774      const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));775      const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));776      const userBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));777778      switch (testCase) {779        case 'transfer':780          await tokenContract.methods.transfer(receiver, 1).send();781          break;782        case 'transferCross':783          await tokenContract.methods.transferCross(helper.ethCrossAccount.fromAddress(receiver), 1).send();784          break;785        case 'transferFrom':786          await tokenContract.methods.transferFrom(user, receiver, 1).send();787          break;788        case 'transferFromCross':789          await tokenContract.methods.transferFromCross(helper.ethCrossAccount.fromAddress(user), helper.ethCrossAccount.fromAddress(receiver), 1).send();790          break;791      }792793      const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));794      expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);795      const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));796      expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;797      const userBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));798      expect(userBalanceAfter).to.be.eq(userBalanceBefore);799    }));800801  [802    'approve',803    'approveCross',804  ].map(testCase =>805    itEth(`[${testCase}] Check that approve via EVM spend money from sponsor address`, async ({helper}) => {806      const owner = await helper.eth.createAccountWithBalance(donor);807808      const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner,'Sponsor collection', '1', '1', '');809      const sponsor = await helper.eth.createAccountWithBalance(donor);810      const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);811      const receiver = await helper.eth.createAccountWithBalance(donor);812      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);813814      await collectionEvm.methods.setCollectionSponsorCross(sponsorCross).send();815      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});816817      const user = await helper.eth.createAccountWithBalance(donor);818      const userCross = helper.ethCrossAccount.fromAddress(user);819      await collectionEvm.methods.addCollectionAdminCross(userCross).send();820821      const result = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});822      const tokenId = result.events.Transfer.returnValues.tokenId;823824      const tokenContract = await helper.ethNativeContract.rftTokenById(collectionId, tokenId, user);825      await tokenContract.methods.repartition(2).send();826827      const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));828      const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));829      const userBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));830831      switch (testCase) {832        case 'approve':833          await tokenContract.methods.approve(receiver, 1).send();834          break;835        case 'approveCross':836          await tokenContract.methods.approveCross(helper.ethCrossAccount.fromAddress(receiver), 1).send();837          break;838      }839840      const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));841      expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);842      const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));843      expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;844      const userBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));845      expect(userBalanceAfter).to.be.eq(userBalanceBefore);846    }));847});848
after · tests/src/eth/collectionSponsoring.test.ts
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/>.1617import {IKeyringPair} from '@polkadot/types/types';18import {Pallets, requirePalletsOrSkip, usingPlaygrounds} from '../util/index';19import {itEth, expect} from './util';20import {CollectionLimitField, TokenPermissionField} from './util/playgrounds/types';2122describe('evm nft collection sponsoring', () => {23  let donor: IKeyringPair;24  let alice: IKeyringPair;25  let nominal: bigint;2627  before(async () => {28    await usingPlaygrounds(async (helper, privateKey) => {29      donor = await privateKey({url: import.meta.url});30      [alice] = await helper.arrange.createAccounts([100n], donor);31      nominal = helper.balance.getOneTokenNominal();32    });33  });3435  // TODO: move to substrate tests36  itEth('sponsors mint transactions', async ({helper}) => {37    const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'spnr', permissions: {mintMode: true}});38    await collection.setSponsor(alice, alice.address);39    await collection.confirmSponsorship(alice);4041    const minter = helper.eth.createAccount();42    expect(await helper.balance.getEthereum(minter)).to.equal(0n);4344    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);45    const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', minter);4647    await collection.addToAllowList(alice, {Ethereum: minter});4849    const result = await contract.methods.mint(minter).send();5051    const events = helper.eth.normalizeEvents(result.events);52    expect(events).to.be.deep.equal([53      {54        address: collectionAddress,55        event: 'Transfer',56        args: {57          from: '0x0000000000000000000000000000000000000000',58          to: minter,59          tokenId: '1',60        },61      },62    ]);63  });6465  // TODO: Temprorary off. Need refactor66  // itWeb3('Set substrate sponsor', async ({api, web3, privateKeyWrapper}) => {67  //   const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);68  //   const collectionHelpers = evmCollectionHelpers(web3, owner);69  //   let result = await collectionHelpers.methods.createNFTCollection('Sponsor collection', '1', '1').send();70  //   const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);71  //   const sponsor = privateKeyWrapper('//Alice');72  //   const collectionEvm = evmCollection(web3, owner, collectionIdAddress);7374  //   expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;75  //   result = await collectionEvm.methods.setCollectionSponsorSubstrate(sponsor.addressRaw).send({from: owner});76  //   expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;7778  //   const confirmTx = await api.tx.unique.confirmSponsorship(collectionId);79  //   await submitTransactionAsync(sponsor, confirmTx);80  //   expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;8182  //   const sponsorTuple = await collectionEvm.methods.collectionSponsor().call({from: owner});83  //   expect(bigIntToSub(api, BigInt(sponsorTuple[1]))).to.be.eq(sponsor.address);84  // });8586  [87    'setCollectionSponsorCross',88    'setCollectionSponsor', // Soft-deprecated89  ].map(testCase =>90    itEth(`[${testCase}] can remove collection sponsor`, async ({helper}) => {91      const owner = await helper.eth.createAccountWithBalance(donor);92      const collectionHelpers = await helper.ethNativeContract.collectionHelpers(owner);9394      let result = await collectionHelpers.methods.createNFTCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});95      const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);96      const sponsor = await helper.eth.createAccountWithBalance(donor);97      const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);98      const collectionEvm = await helper.ethNativeContract.collection(collectionIdAddress, 'nft', owner, testCase === 'setCollectionSponsor');99100      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;101      result = await collectionEvm.methods[testCase](testCase === 'setCollectionSponsor' ? sponsor : sponsorCross).send({from: owner});102      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;103104      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});105      let sponsorStruct = await collectionEvm.methods.collectionSponsor().call({from: owner});106      expect(helper.address.restoreCrossAccountFromBigInt(BigInt(sponsorStruct.sub))).to.be.eq(helper.address.ethToSubstrate(sponsor, true));107      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;108109      await collectionEvm.methods.removeCollectionSponsor().send({from: owner});110111      sponsorStruct = await collectionEvm.methods.collectionSponsor().call({from: owner});112      expect(sponsorStruct.eth).to.be.eq('0x0000000000000000000000000000000000000000');113    }));114115  [116    'setCollectionSponsorCross',117    'setCollectionSponsor', // Soft-deprecated118  ].map(testCase =>119    itEth(`[${testCase}] Can sponsor from evm address via access list`, async ({helper}) => {120      const owner = await helper.eth.createAccountWithBalance(donor);121      const sponsorEth = await helper.eth.createAccountWithBalance(donor);122      const sponsorCrossEth = helper.ethCrossAccount.fromAddress(sponsorEth);123124      const {collectionId, collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Sponsor collection', '1', '1', '');125126      const collectionSub = helper.nft.getCollectionObject(collectionId);127      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner, testCase === 'setCollectionSponsor');128129      // Set collection sponsor:130      await collectionEvm.methods[testCase](testCase === 'setCollectionSponsor' ? sponsorEth : sponsorCrossEth).send({from: owner});131      let sponsorship = (await collectionSub.getData())!.raw.sponsorship;132      expect(sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsorEth, true));133      // Account cannot confirm sponsorship if it is not set as a sponsor134      await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmSponsorshipFail');135136      // Sponsor can confirm sponsorship:137      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsorEth});138      sponsorship = (await collectionSub.getData())!.raw.sponsorship;139      expect(sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsorEth, true));140141      // Create user with no balance:142      const user = helper.ethCrossAccount.createAccount();143      const nextTokenId = await collectionEvm.methods.nextTokenId().call();144      expect(nextTokenId).to.be.equal('1');145146      // Set collection permissions:147      const oldPermissions = (await collectionSub.getData())!.raw.permissions;148      expect(oldPermissions.mintMode).to.be.false;149      expect(oldPermissions.access).to.be.equal('Normal');150151      await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});152      await collectionEvm.methods.addToCollectionAllowListCross(user).send({from: owner});153      await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});154      await collectionEvm.methods.setCollectionLimit({field: CollectionLimitField.SponsoredDataRateLimit, value: {status: true, value: 30}}).send();155156      const newPermissions = (await collectionSub.getData())!.raw.permissions;157      expect(newPermissions.mintMode).to.be.true;158      expect(newPermissions.access).to.be.equal('AllowList');159160      // Set token permissions161      await collectionEvm.methods.setTokenPropertyPermissions([162        ['key', [163          [TokenPermissionField.TokenOwner, true],164        ],165        ],166      ]).send({from: owner});167168      const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));169      const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));170      const userBalanceBefore =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user.eth));171172      // User can mint token without balance:173      {174        const result = await collectionEvm.methods.mintCross(user, [{key: 'key', value: Buffer.from('Value')}]).send({from: user.eth});175        const event = helper.eth.normalizeEvents(result.events)176          .find(event => event.event === 'Transfer');177178        expect(event).to.be.deep.equal({179          address: collectionAddress,180          event: 'Transfer',181          args: {182            from: '0x0000000000000000000000000000000000000000',183            to: user.eth,184            tokenId: '1',185          },186        });187188        // await collectionEvm.methods.setProperties(1, [{key: 'key', value: Buffer.from('Value1')}]).send({from: user.eth});189190        const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));191        const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));192        const userBalanceAfter =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user.eth));193194        expect(await collectionEvm.methods.properties(nextTokenId, []).call())195          .to.be.like([196            [197              'key',198              '0x' + Buffer.from('Value').toString('hex'),199            ],200          ]);201        expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);202        expect(userBalanceAfter).to.be.eq(userBalanceBefore);203        expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;204      }205    }));206207  itEth('Can sponsor [set token properties] via access list', async ({helper}) => {208    const owner = await helper.eth.createAccountWithBalance(donor);209    const sponsorEth = await helper.eth.createAccountWithBalance(donor);210    const sponsorCrossEth = helper.ethCrossAccount.fromAddress(sponsorEth);211212    const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Sponsor collection', '1', '1', '');213    const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner, false);214215    // Set collection sponsor:216    await collectionEvm.methods.setCollectionSponsorCross(sponsorCrossEth).send({from: owner});217218    // Sponsor can confirm sponsorship:219    await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsorEth});220221    // Create user with no balance:222    const user = helper.ethCrossAccount.createAccount();223    const nextTokenId = await collectionEvm.methods.nextTokenId().call();224    expect(nextTokenId).to.be.equal('1');225226    // Set collection permissions:227    await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});228    await collectionEvm.methods.addToCollectionAllowListCross(user).send({from: owner});229    await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});230    await collectionEvm.methods.setCollectionLimit({field: CollectionLimitField.SponsoredDataRateLimit, value: {status: true, value: 30}}).send();231232    // Set token permissions233    await collectionEvm.methods.setTokenPropertyPermissions([234      ['key', [235        [TokenPermissionField.TokenOwner, true],236      ],237      ],238    ]).send({from: owner});239240    const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));241    const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));242    const userBalanceBefore =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user.eth));243244    // User can mint token without balance:245    {246      const result = await collectionEvm.methods.mintCross(user, []).send({from: user.eth});247      const event = helper.eth.normalizeEvents(result.events)248        .find(event => event.event === 'Transfer');249250      expect(event).to.be.deep.equal({251        address: collectionAddress,252        event: 'Transfer',253        args: {254          from: '0x0000000000000000000000000000000000000000',255          to: user.eth,256          tokenId: '1',257        },258      });259260      await collectionEvm.methods.setProperties(1, [{key: 'key', value: Buffer.from('Value')}]).send({from: user.eth});261262      const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));263      const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));264      const userBalanceAfter =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user.eth));265266      expect(await collectionEvm.methods.properties(nextTokenId, []).call())267        .to.be.like([268          [269            'key',270            '0x' + Buffer.from('Value').toString('hex'),271          ],272        ]);273      expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);274      expect(userBalanceAfter).to.be.eq(userBalanceBefore);275      expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;276    }277  });278279  // TODO: Temprorary off. Need refactor280  // itWeb3('Sponsoring collection from substrate address via access list', async ({api, web3, privateKeyWrapper}) => {281  //   const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);282  //   const collectionHelpers = evmCollectionHelpers(web3, owner);283  //   const result = await collectionHelpers.methods.createERC721MetadataCompatibleNFTCollection('Sponsor collection', '1', '1', '').send();284  //   const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);285  //   const sponsor = privateKeyWrapper('//Alice');286  //   const collectionEvm = evmCollection(web3, owner, collectionIdAddress);287288  //   await collectionEvm.methods.setCollectionSponsorSubstrate(sponsor.addressRaw).send({from: owner});289290  //   const confirmTx = await api.tx.unique.confirmSponsorship(collectionId);291  //   await submitTransactionAsync(sponsor, confirmTx);292293  //   const user = createEthAccount(web3);294  //   const nextTokenId = await collectionEvm.methods.nextTokenId().call();295  //   expect(nextTokenId).to.be.equal('1');296297  //   await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});298  //   await collectionEvm.methods.addToCollectionAllowList(user).send({from: owner});299  //   await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});300301  //   const ownerBalanceBefore = await ethBalanceViaSub(api, owner);302  //   const sponsorBalanceBefore = (await getBalance(api, [sponsor.address]))[0];303304  //   {305  //     const nextTokenId = await collectionEvm.methods.nextTokenId().call();306  //     expect(nextTokenId).to.be.equal('1');307  //     const result = await collectionEvm.methods.mintWithTokenURI(308  //       user,309  //       nextTokenId,310  //       'Test URI',311  //     ).send({from: user});312  //     const events = normalizeEvents(result.events);313314  //     expect(events).to.be.deep.equal([315  //       {316  //         address: collectionIdAddress,317  //         event: 'Transfer',318  //         args: {319  //           from: '0x0000000000000000000000000000000000000000',320  //           to: user,321  //           tokenId: nextTokenId,322  //         },323  //       },324  //     ]);325326  //     const ownerBalanceAfter = await ethBalanceViaSub(api, owner);327  //     const sponsorBalanceAfter = (await getBalance(api, [sponsor.address]))[0];328329  //     expect(await collectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');330  //     expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);331  //     expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;332  //   }333  // });334335  [336    'setCollectionSponsorCross',337    'setCollectionSponsor', // Soft-deprecated338  ].map(testCase =>339    itEth(`[${testCase}] Check that transaction via EVM spend money from sponsor address`, async ({helper}) => {340      const owner = await helper.eth.createAccountWithBalance(donor);341      const sponsor = await helper.eth.createAccountWithBalance(donor);342      const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);343344      const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner,'Sponsor collection', '1', '1', '');345346      const collectionSub = helper.nft.getCollectionObject(collectionId);347      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner, testCase === 'setCollectionSponsor');348      // Set collection sponsor:349      await collectionEvm.methods[testCase](testCase === 'setCollectionSponsor' ? sponsor : sponsorCross).send();350      let collectionData = (await collectionSub.getData())!;351      expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));352      await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmSponsorshipFail');353354      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});355      collectionData = (await collectionSub.getData())!;356      expect(collectionData.raw.sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));357358      const user = helper.eth.createAccount();359      const userCross = helper.ethCrossAccount.fromAddress(user);360      await collectionEvm.methods.addCollectionAdminCross(userCross).send();361362      const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));363      const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));364365      const mintingResult = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});366      const tokenId = mintingResult.events.Transfer.returnValues.tokenId;367368      const event = helper.eth.normalizeEvents(mintingResult.events)369        .find(event => event.event === 'Transfer');370      const address = helper.ethAddress.fromCollectionId(collectionId);371372      expect(event).to.be.deep.equal({373        address,374        event: 'Transfer',375        args: {376          from: '0x0000000000000000000000000000000000000000',377          to: user,378          tokenId: '1',379        },380      });381      expect(await collectionEvm.methods.tokenURI(tokenId).call({from: user})).to.be.equal('Test URI');382383      const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));384      expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);385      const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));386      expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;387    }));388389  itEth('Can reassign collection sponsor', async ({helper}) => {390    const owner = await helper.eth.createAccountWithBalance(donor);391    const sponsorEth = await helper.eth.createAccountWithBalance(donor);392    const sponsorCrossEth = helper.ethCrossAccount.fromAddress(sponsorEth);393    const [sponsorSub] = await helper.arrange.createAccounts([100n], donor);394    const sponsorCrossSub = helper.ethCrossAccount.fromKeyringPair(sponsorSub);395396    const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner,'Sponsor collection', '1', '1', '');397    const collectionSub = helper.nft.getCollectionObject(collectionId);398    const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);399400    // Set and confirm sponsor:401    await collectionEvm.methods.setCollectionSponsorCross(sponsorCrossEth).send({from: owner});402    await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsorEth});403404    // Can reassign sponsor:405    await collectionEvm.methods.setCollectionSponsorCross(sponsorCrossSub).send({from: owner});406    const collectionSponsor = (await collectionSub.getData())?.raw.sponsorship;407    expect(collectionSponsor).to.deep.eq({Unconfirmed: sponsorSub.address});408  });409});410411describe('evm RFT collection sponsoring', () => {412  let donor: IKeyringPair;413  let alice: IKeyringPair;414  let nominal: bigint;415416  before(async function() {417    await usingPlaygrounds(async (helper, privateKey) => {418      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);419      donor = await privateKey({url: import.meta.url});420      [alice] = await helper.arrange.createAccounts([100n], donor);421      nominal = helper.balance.getOneTokenNominal();422    });423  });424425  [426    'mintCross',427    'mintWithTokenURI',428  ].map(testCase =>429    itEth(`[${testCase}] sponsors mint transactions`, async ({helper}) => {430      const collection = await helper.rft.mintCollection(alice, {tokenPrefix: 'spnr', permissions: {mintMode: true}, tokenPropertyPermissions: [431        {key: 'URI', permission: {tokenOwner: true, mutable: true, collectionAdmin: true}},432      ]});433434      const owner = await helper.eth.createAccountWithBalance(donor);435      await collection.setSponsor(alice, alice.address);436      await collection.confirmSponsorship(alice);437438      const minter = helper.eth.createAccount();439      const minterCross = helper.ethCrossAccount.fromAddress(minter);440      expect(await helper.balance.getEthereum(minter)).to.equal(0n);441442      const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);443      const contract = await helper.ethNativeContract.collection(collectionAddress, 'rft', minter, true);444445      await collection.addToAllowList(alice, {Ethereum: minter});446      await collection.addAdmin(alice, {Ethereum: owner});447      const collectionHelpers = await helper.ethNativeContract.collectionHelpers(owner);448      await collectionHelpers.methods.makeCollectionERC721MetadataCompatible(collectionAddress, 'base/')449        .send();450451      let mintingResult;452      let tokenId;453      switch (testCase) {454        case 'mintCross':455          mintingResult = await contract.methods.mintCross(minterCross, []).send();456          break;457        case 'mintWithTokenURI':458          mintingResult = await contract.methods.mintWithTokenURI(minter, 'Test URI').send();459          tokenId = mintingResult.events.Transfer.returnValues.tokenId;460          expect(await contract.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');461          break;462      }463464      const events = helper.eth.normalizeEvents(mintingResult.events);465      expect(events).to.deep.include({466        address: collectionAddress,467        event: 'Transfer',468        args: {469          from: '0x0000000000000000000000000000000000000000',470          to: minter,471          tokenId: '1',472        },473      });474    }));475476  [477    'setCollectionSponsorCross',478    'setCollectionSponsor', // Soft-deprecated479  ].map(testCase =>480    itEth(`[${testCase}] can remove collection sponsor`, async ({helper}) => {481      const owner = await helper.eth.createAccountWithBalance(donor);482      const collectionHelpers = await helper.ethNativeContract.collectionHelpers(owner);483484      let result = await collectionHelpers.methods.createRFTCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});485      const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);486      const sponsor = await helper.eth.createAccountWithBalance(donor);487      const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);488      const collectionEvm = await helper.ethNativeContract.collection(collectionIdAddress, 'rft', owner, testCase === 'setCollectionSponsor');489490      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;491      result = await collectionEvm.methods[testCase](testCase === 'setCollectionSponsor' ? sponsor : sponsorCross).send({from: owner});492      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;493494      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});495      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;496497      await collectionEvm.methods.removeCollectionSponsor().send({from: owner});498499      const sponsorStruct = await collectionEvm.methods.collectionSponsor().call({from: owner});500      expect(sponsorStruct.eth).to.be.eq('0x0000000000000000000000000000000000000000');501    }));502503  [504    'setCollectionSponsorCross',505    'setCollectionSponsor', // Soft-deprecated506  ].map(testCase =>507    itEth(`[${testCase}] Can sponsor from evm address via access list`, async ({helper}) => {508      const owner = await helper.eth.createAccountWithBalance(donor);509      const sponsorEth = await helper.eth.createAccountWithBalance(donor);510      const sponsorCrossEth = helper.ethCrossAccount.fromAddress(sponsorEth);511512      const {collectionId, collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'Sponsor collection', '1', '1', '');513514      const collectionSub = helper.rft.getCollectionObject(collectionId);515      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner, testCase === 'setCollectionSponsor');516517      // Set collection sponsor:518      await collectionEvm.methods[testCase](testCase === 'setCollectionSponsor' ? sponsorEth : sponsorCrossEth).send({from: owner});519      let sponsorship = (await collectionSub.getData())!.raw.sponsorship;520      expect(sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsorEth, true));521      // Account cannot confirm sponsorship if it is not set as a sponsor522      await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmSponsorshipFail');523524      // Sponsor can confirm sponsorship:525      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsorEth});526      sponsorship = (await collectionSub.getData())!.raw.sponsorship;527      expect(sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsorEth, true));528529      // Create user with no balance:530      const user = helper.eth.createAccount();531      const userCross = helper.ethCrossAccount.fromAddress(user);532      const nextTokenId = await collectionEvm.methods.nextTokenId().call();533      expect(nextTokenId).to.be.equal('1');534535      // Set collection permissions:536      const oldPermissions = (await collectionSub.getData())!.raw.permissions;537      expect(oldPermissions.mintMode).to.be.false;538      expect(oldPermissions.access).to.be.equal('Normal');539540      await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});541      await collectionEvm.methods.addToCollectionAllowListCross(userCross).send({from: owner});542      await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});543544      const newPermissions = (await collectionSub.getData())!.raw.permissions;545      expect(newPermissions.mintMode).to.be.true;546      expect(newPermissions.access).to.be.equal('AllowList');547548      // Set token permissions549      await collectionEvm.methods.setTokenPropertyPermissions([550        ['URI', [551          [TokenPermissionField.TokenOwner, true],552          [TokenPermissionField.CollectionAdmin, true],553        ],554        ],555      ]).send({from: owner});556557      const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));558      const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));559      const userBalanceBefore =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));560561      // User can mint token without balance:562      {563        const result = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});564        const events = helper.eth.normalizeEvents(result.events);565566        expect(events).to.deep.include({567          address: collectionAddress,568          event: 'Transfer',569          args: {570            from: '0x0000000000000000000000000000000000000000',571            to: user,572            tokenId: '1',573          },574        });575576        const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));577        const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));578        const userBalanceAfter =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));579580        expect(await collectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');581        expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);582        expect(userBalanceAfter).to.be.eq(userBalanceBefore);583        expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;584      }585    }));586587  [588    'setCollectionSponsorCross',589    'setCollectionSponsor', // Soft-deprecated590  ].map(testCase =>591    itEth(`[${testCase}] Check that collection admin EVM transaction spend money from sponsor eth address`, async ({helper}) => {592      const owner = await helper.eth.createAccountWithBalance(donor);593      const sponsor = await helper.eth.createAccountWithBalance(donor);594      const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);595596      const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner,'Sponsor collection', '1', '1', '');597598      const collectionSub = helper.rft.getCollectionObject(collectionId);599      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner, testCase === 'setCollectionSponsor');600      // Set collection sponsor:601      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call()).to.be.false;602      await collectionEvm.methods[testCase](testCase === 'setCollectionSponsor' ? sponsor : sponsorCross).send();603      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call()).to.be.true;604      let collectionData = (await collectionSub.getData())!;605      expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));606      await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmSponsorshipFail');607      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call()).to.be.true;608609      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});610      collectionData = (await collectionSub.getData())!;611      expect(collectionData.raw.sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));612      expect(await collectionEvm.methods.hasCollectionPendingSponsor().call()).to.be.false;613      const sponsorStruct = await collectionEvm.methods.collectionSponsor().call({from: owner});614      const sponsorSubAddress = helper.address.normalizeSubstrateToChainFormat(helper.address.ethToSubstrate(sponsor));615      const actualSubAddress = helper.address.normalizeSubstrateToChainFormat(helper.address.restoreCrossAccountFromBigInt(BigInt(sponsorStruct.sub)));616      expect(actualSubAddress).to.be.equal(sponsorSubAddress);617618      const user = helper.eth.createAccount();619      const userCross = helper.ethCrossAccount.fromAddress(user);620      await collectionEvm.methods.addCollectionAdminCross(userCross).send();621622      const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));623      const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));624625      const mintingResult = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});626      const tokenId = mintingResult.events.Transfer.returnValues.tokenId;627628      const events = helper.eth.normalizeEvents(mintingResult.events);629      const address = helper.ethAddress.fromCollectionId(collectionId);630631      expect(events).to.deep.include({632        address,633        event: 'Transfer',634        args: {635          from: '0x0000000000000000000000000000000000000000',636          to: user,637          tokenId: '1',638        },639      });640      expect(await collectionEvm.methods.tokenURI(tokenId).call({from: user})).to.be.equal('Test URI');641642      const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));643      expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);644      const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));645      expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;646    }));647648  itEth('Check that collection admin EVM transaction spend money from sponsor sub address', async ({helper}) => {649    const owner = await helper.eth.createAccountWithBalance(donor);650    const sponsor = alice;651    const sponsorCross = helper.ethCrossAccount.fromKeyringPair(sponsor);652653    const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner,'Sponsor collection', '1', '1', '');654655    const collectionSub = helper.rft.getCollectionObject(collectionId);656    const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'rft', owner, false);657    // Set collection sponsor:658    expect(await collectionEvm.methods.hasCollectionPendingSponsor().call()).to.be.false;659    await collectionEvm.methods.setCollectionSponsorCross(sponsorCross).send();660    expect(await collectionEvm.methods.hasCollectionPendingSponsor().call()).to.be.true;661    let collectionData = (await collectionSub.getData())!;662    expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(sponsor.address);663    await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmSponsorshipFail');664665    await collectionSub.confirmSponsorship(sponsor);666    collectionData = (await collectionSub.getData())!;667    expect(collectionData.raw.sponsorship.Confirmed).to.be.eq(sponsor.address);668    expect(await collectionEvm.methods.hasCollectionPendingSponsor().call()).to.be.false;669    const sponsorStruct = await collectionEvm.methods.collectionSponsor().call({from: owner});670    expect(BigInt(sponsorStruct.sub)).to.be.equal(BigInt('0x' + Buffer.from(sponsor.addressRaw).toString('hex')));671672    const user = helper.eth.createAccount();673    const userCross = helper.ethCrossAccount.fromAddress(user);674    await collectionEvm.methods.addCollectionAdminCross(userCross).send();675676    const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));677    const sponsorBalanceBefore = await helper.balance.getSubstrate(sponsor.address);678679    const mintingResult = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});680    const tokenId = mintingResult.events.Transfer.returnValues.tokenId;681682    const events = helper.eth.normalizeEvents(mintingResult.events);683684    expect(events).to.deep.include({685      address: collectionAddress,686      event: 'Transfer',687      args: {688        from: '0x0000000000000000000000000000000000000000',689        to: user,690        tokenId: '1',691      },692    });693    expect(await collectionEvm.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');694695    const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));696    expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);697    const sponsorBalanceAfter = await helper.balance.getSubstrate(sponsor.address);698    expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;699  });700701  itEth('Sponsoring collection from substrate address via access list', async ({helper}) => {702    const owner = await helper.eth.createAccountWithBalance(donor);703    const user = helper.eth.createAccount();704    const userCross =  helper.ethCrossAccount.fromAddress(user);705    const sponsor = alice;706    const sponsorCross = helper.ethCrossAccount.fromKeyringPair(sponsor);707708    const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner,'Sponsor collection', '1', '1', '');709    const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner, false);710711    await collectionEvm.methods.setCollectionSponsorCross(sponsorCross).send({from: owner});712713    const collectionSub = helper.rft.getCollectionObject(collectionId);714    await collectionSub.confirmSponsorship(sponsor);715716    const nextTokenId = await collectionEvm.methods.nextTokenId().call();717    expect(nextTokenId).to.be.equal('1');718719    await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});720721    await collectionEvm.methods.addToCollectionAllowListCross(userCross).send({from: owner});722    await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});723724    // Set token permissions725    await collectionEvm.methods.setTokenPropertyPermissions([726      ['URI', [727        [TokenPermissionField.TokenOwner, true],728        [TokenPermissionField.CollectionAdmin, true],729      ],730      ],731    ]).send({from: owner});732733    const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));734    const sponsorBalanceBefore = await helper.balance.getSubstrate(sponsor.address);735    const userBalanceBefore =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));736737    {738      const nextTokenId = await collectionEvm.methods.nextTokenId().call();739      expect(nextTokenId).to.be.equal('1');740      const mintingResult = await collectionEvm.methods.mintWithTokenURI(741        user,742        'Test URI',743      ).send({from: user});744745      const events = helper.eth.normalizeEvents(mintingResult.events);746747748      expect(events).to.deep.include({749        address: collectionAddress,750        event: 'Transfer',751        args: {752          from: '0x0000000000000000000000000000000000000000',753          to: user,754          tokenId: nextTokenId,755        },756      });757758      const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));759      const sponsorBalanceAfter = await helper.balance.getSubstrate(sponsor.address);760      const userBalanceAfter =  await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));761762      expect(await collectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');763      expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);764      expect(userBalanceAfter).to.be.eq(userBalanceBefore);765      expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;766    }767  });768769  itEth('Can reassign collection sponsor', async ({helper}) => {770    const owner = await helper.eth.createAccountWithBalance(donor);771    const sponsorEth = await helper.eth.createAccountWithBalance(donor);772    const sponsorCrossEth = helper.ethCrossAccount.fromAddress(sponsorEth);773    const [sponsorSub] = await helper.arrange.createAccounts([100n], donor);774    const sponsorCrossSub = helper.ethCrossAccount.fromKeyringPair(sponsorSub);775776    const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner,'Sponsor collection', '1', '1', '');777    const collectionSub = helper.rft.getCollectionObject(collectionId);778    const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);779780    // Set and confirm sponsor:781    await collectionEvm.methods.setCollectionSponsorCross(sponsorCrossEth).send({from: owner});782    await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsorEth});783784    // Can reassign sponsor:785    await collectionEvm.methods.setCollectionSponsorCross(sponsorCrossSub).send({from: owner});786    const collectionSponsor = (await collectionSub.getData())?.raw.sponsorship;787    expect(collectionSponsor).to.deep.eq({Unconfirmed: sponsorSub.address});788  });789790  [791    'transfer',792    'transferCross',793    'transferFrom',794    'transferFromCross',795  ].map(testCase =>796    itEth(`[${testCase}] Check that transfer via EVM spend money from sponsor address`, async ({helper}) => {797      const owner = await helper.eth.createAccountWithBalance(donor);798799      const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner,'Sponsor collection', '1', '1', '');800      const sponsor = await helper.eth.createAccountWithBalance(donor);801      const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);802      const receiver = await helper.eth.createAccountWithBalance(donor);803      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);804805      await collectionEvm.methods.setCollectionSponsorCross(sponsorCross).send();806      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});807808      const user = await helper.eth.createAccountWithBalance(donor);809      const userCross = helper.ethCrossAccount.fromAddress(user);810      await collectionEvm.methods.addCollectionAdminCross(userCross).send();811812      const result = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});813      const tokenId = result.events.Transfer.returnValues.tokenId;814815      const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));816      const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));817      const userBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));818819      switch (testCase) {820        case 'transfer':821          await collectionEvm.methods.transfer(receiver, tokenId).send({from: user});822          break;823        case 'transferCross':824          await collectionEvm.methods.transferCross(helper.ethCrossAccount.fromAddress(receiver), tokenId).send({from: user});825          break;826        case 'transferFrom':827          await collectionEvm.methods.transferFrom(user, receiver, tokenId).send({from: user});828          break;829        case 'transferFromCross':830          await collectionEvm.methods.transferFromCross(helper.ethCrossAccount.fromAddress(user), helper.ethCrossAccount.fromAddress(receiver), tokenId).send({from: user});831          break;832      }833834      const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));835      expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);836      const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));837      expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;838      const userBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));839      expect(userBalanceAfter).to.be.eq(userBalanceBefore);840    }));841});842843describe('evm RFT token sponsoring', () => {844  let donor: IKeyringPair;845846  before(async function() {847    await usingPlaygrounds(async (helper, privateKey) => {848      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);849      donor = await privateKey({url: import.meta.url});850    });851  });852853  [854    'transfer',855    'transferCross',856    'transferFrom',857    'transferFromCross',858  ].map(testCase =>859    itEth(`[${testCase}] Check that token piece transfer via EVM spend money from sponsor address`, async ({helper}) => {860      const owner = await helper.eth.createAccountWithBalance(donor);861862      const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner,'Sponsor collection', '1', '1', '');863      const sponsor = await helper.eth.createAccountWithBalance(donor);864      const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);865      const receiver = await helper.eth.createAccountWithBalance(donor);866      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);867868      await collectionEvm.methods.setCollectionSponsorCross(sponsorCross).send();869      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});870871      const user = await helper.eth.createAccountWithBalance(donor);872      const userCross = helper.ethCrossAccount.fromAddress(user);873      await collectionEvm.methods.addCollectionAdminCross(userCross).send();874875      const result = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});876      const tokenId = result.events.Transfer.returnValues.tokenId;877878      const tokenContract = await helper.ethNativeContract.rftTokenById(collectionId, tokenId, user);879      await tokenContract.methods.repartition(2).send();880881      const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));882      const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));883      const userBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));884885      switch (testCase) {886        case 'transfer':887          await tokenContract.methods.transfer(receiver, 1).send();888          break;889        case 'transferCross':890          await tokenContract.methods.transferCross(helper.ethCrossAccount.fromAddress(receiver), 1).send();891          break;892        case 'transferFrom':893          await tokenContract.methods.transferFrom(user, receiver, 1).send();894          break;895        case 'transferFromCross':896          await tokenContract.methods.transferFromCross(helper.ethCrossAccount.fromAddress(user), helper.ethCrossAccount.fromAddress(receiver), 1).send();897          break;898      }899900      const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));901      expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);902      const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));903      expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;904      const userBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));905      expect(userBalanceAfter).to.be.eq(userBalanceBefore);906    }));907908  [909    'approve',910    'approveCross',911  ].map(testCase =>912    itEth(`[${testCase}] Check that approve via EVM spend money from sponsor address`, async ({helper}) => {913      const owner = await helper.eth.createAccountWithBalance(donor);914915      const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner,'Sponsor collection', '1', '1', '');916      const sponsor = await helper.eth.createAccountWithBalance(donor);917      const sponsorCross = helper.ethCrossAccount.fromAddress(sponsor);918      const receiver = await helper.eth.createAccountWithBalance(donor);919      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'rft', owner);920921      await collectionEvm.methods.setCollectionSponsorCross(sponsorCross).send();922      await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});923924      const user = await helper.eth.createAccountWithBalance(donor);925      const userCross = helper.ethCrossAccount.fromAddress(user);926      await collectionEvm.methods.addCollectionAdminCross(userCross).send();927928      const result = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});929      const tokenId = result.events.Transfer.returnValues.tokenId;930931      const tokenContract = await helper.ethNativeContract.rftTokenById(collectionId, tokenId, user);932      await tokenContract.methods.repartition(2).send();933934      const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));935      const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));936      const userBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));937938      switch (testCase) {939        case 'approve':940          await tokenContract.methods.approve(receiver, 1).send();941          break;942        case 'approveCross':943          await tokenContract.methods.approveCross(helper.ethCrossAccount.fromAddress(receiver), 1).send();944          break;945      }946947      const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));948      expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);949      const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));950      expect(sponsorBalanceAfter < sponsorBalanceBefore).to.be.true;951      const userBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));952      expect(userBalanceAfter).to.be.eq(userBalanceBefore);953    }));954});955
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})),