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

difftreelog

Merge pull request #776 from UniqueNetwork/feature/evm_set-get_tokenPropertyPermissions

ut-akuznetsov2022-12-16parents: #3f0dc65 #0ade15e.patch.diff
in: master
Feature/evm_set-get_tokenPropertyPermissions

22 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6342,7 +6342,7 @@
 
 [[package]]
 name = "pallet-nonfungible"
-version = "0.1.9"
+version = "0.1.11"
 dependencies = [
  "ethereum 0.14.0",
  "evm-coder",
@@ -6501,7 +6501,7 @@
 
 [[package]]
 name = "pallet-refungible"
-version = "0.2.8"
+version = "0.2.10"
 dependencies = [
  "derivative",
  "ethereum 0.14.0",
modifiedcrates/evm-coder/tests/abi_derive_generation.rsdiffbeforeafterboth
--- a/crates/evm-coder/tests/abi_derive_generation.rs
+++ b/crates/evm-coder/tests/abi_derive_generation.rs
@@ -740,7 +740,7 @@
 	/// Some docs
 	/// At multi
 	/// line
-	#[derive(AbiCoder, Debug, PartialEq, Default)]
+	#[derive(AbiCoder, Debug, PartialEq, Default, Clone, Copy)]
 	#[repr(u8)]
 	enum Color {
 		/// Docs for Red
modifiedpallets/common/src/eth.rsdiffbeforeafterboth
--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -162,3 +162,18 @@
 	CollectionAdmin,
 	TokenOwner,
 }
+
+/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) fields as an enumeration.
+#[derive(AbiCoder, Copy, Clone, Default, Debug)]
+#[repr(u8)]
+pub enum EthTokenPermissions {
+	/// Permission to change the property and property permission. See [`up_data_structs::PropertyPermission::mutable`]
+	#[default]
+	Mutable,
+
+	/// Change permission for the collection administrator. See [`up_data_structs::PropertyPermission::token_owner`]
+	TokenOwner,
+
+	/// Permission to change the property for the owner of the token. See [`up_data_structs::PropertyPermission::collection_admin`]
+	CollectionAdmin,
+}
modifiedpallets/nonfungible/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/nonfungible/CHANGELOG.md
+++ b/pallets/nonfungible/CHANGELOG.md
@@ -4,6 +4,16 @@
 
 <!-- bureaucrate goes here -->
 
+## [0.1.11] - 2022-12-16
+
+### Added
+
+- The function `tokenPropertyPermissions` and `setTokenPropertyPermissions` to `TokenProperties` interface.
+
+### Changed
+
+- Hide `setTokenPropertyPermission` function in `TokenProperties` interface.
+
 ## [0.1.10] - 2022-11-18
 
 ### Added
modifiedpallets/nonfungible/Cargo.tomldiffbeforeafterboth
--- a/pallets/nonfungible/Cargo.toml
+++ b/pallets/nonfungible/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "pallet-nonfungible"
-version = "0.1.9"
+version = "0.1.11"
 license = "GPLv3"
 edition = "2021"
 
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -34,11 +34,11 @@
 	CollectionPropertiesVec,
 };
 use pallet_evm_coder_substrate::dispatch_to_evm;
-use sp_std::vec::Vec;
+use sp_std::{vec::Vec, vec};
 use pallet_common::{
 	CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,
 	erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},
-	eth::EthCrossAccount,
+	eth::{EthCrossAccount, EthTokenPermissions},
 };
 use pallet_evm::{account::CrossAccountId, PrecompileHandle};
 use pallet_evm_coder_substrate::call;
@@ -60,6 +60,7 @@
 	/// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
 	/// @param tokenOwner Permission to mutate property by token owner if property is mutable.
 	#[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]
+	#[solidity(hide)]
 	fn set_token_property_permission(
 		&mut self,
 		caller: caller,
@@ -69,10 +70,10 @@
 		token_owner: bool,
 	) -> Result<()> {
 		let caller = T::CrossAccountId::from_eth(caller);
-		<Pallet<T>>::set_property_permission(
+		<Pallet<T>>::set_token_property_permissions(
 			self,
 			&caller,
-			PropertyKeyPermission {
+			vec![PropertyKeyPermission {
 				key: <Vec<u8>>::from(key)
 					.try_into()
 					.map_err(|_| "too long key")?,
@@ -81,11 +82,78 @@
 					collection_admin,
 					token_owner,
 				},
-			},
+			}],
 		)
 		.map_err(dispatch_to_evm::<T>)
 	}
 
+	/// @notice Set permissions for token property.
+	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
+	/// @param permissions Permissions for keys.
+	#[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]
+	fn set_token_property_permissions(
+		&mut self,
+		caller: caller,
+		permissions: Vec<(string, Vec<(EthTokenPermissions, bool)>)>,
+	) -> Result<()> {
+		let caller = T::CrossAccountId::from_eth(caller);
+		const PERMISSIONS_FIELDS_COUNT: usize = 3;
+
+		let mut perms = Vec::new();
+
+		for (key, pp) in permissions {
+			if pp.len() > PERMISSIONS_FIELDS_COUNT {
+				return Err(alloc::format!(
+					"Actual number of fields {} for {}, which exceeds the maximum value of {}",
+					pp.len(),
+					stringify!(EthTokenPermissions),
+					PERMISSIONS_FIELDS_COUNT
+				)
+				.as_str()
+				.into());
+			}
+
+			let mut token_permission = PropertyPermission::default();
+
+			for (perm, value) in pp {
+				match perm {
+					EthTokenPermissions::Mutable => token_permission.mutable = value,
+					EthTokenPermissions::TokenOwner => token_permission.token_owner = value,
+					EthTokenPermissions::CollectionAdmin => {
+						token_permission.collection_admin = value
+					}
+				}
+			}
+
+			perms.push(PropertyKeyPermission {
+				key: key.into_bytes().try_into().map_err(|_| "too long key")?,
+				permission: token_permission,
+			});
+		}
+
+		<Pallet<T>>::set_token_property_permissions(self, &caller, perms)
+			.map_err(dispatch_to_evm::<T>)
+	}
+
+	/// @notice Get permissions for token properties.
+	fn token_property_permissions(
+		&self,
+	) -> Result<Vec<(string, Vec<(EthTokenPermissions, bool)>)>> {
+		let perms = <Pallet<T>>::token_property_permission(self.id);
+		Ok(perms
+			.into_iter()
+			.map(|(key, pp)| {
+				let key = string::from_utf8(key.into_inner()).expect("Stored key must be valid");
+				let pp = vec![
+					(EthTokenPermissions::Mutable, pp.mutable),
+					(EthTokenPermissions::TokenOwner, pp.token_owner),
+					(EthTokenPermissions::CollectionAdmin, pp.collection_admin),
+				];
+				(key, pp)
+			})
+			.collect())
+	}
+
 	/// @notice Set token property value.
 	/// @dev Throws error if `msg.sender` has no permission to edit the property.
 	/// @param tokenId ID of the token.
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -103,7 +103,7 @@
 	AccessMode, CollectionId, CollectionFlags, CustomDataLimit, TokenId, CreateCollectionData,
 	CreateNftExData, mapping::TokenAddressMapping, budget::Budget, Property, PropertyPermission,
 	PropertyKey, PropertyValue, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty,
-	TokenChild, AuxPropertyValue,
+	TokenChild, AuxPropertyValue, PropertiesPermissionMap,
 };
 use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
 use pallet_common::{
@@ -824,15 +824,8 @@
 		)
 	}
 
-	/// Set property permissions for the collection.
-	///
-	/// Sender should be the owner or admin of the collection.
-	pub fn set_property_permission(
-		collection: &CollectionHandle<T>,
-		sender: &T::CrossAccountId,
-		permission: PropertyKeyPermission,
-	) -> DispatchResult {
-		<PalletCommon<T>>::set_property_permission(collection, sender, permission)
+	pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {
+		<PalletCommon<T>>::property_permissions(collection_id)
 	}
 
 	pub fn check_token_immediate_ownership(
modifiedpallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth
--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -18,30 +18,44 @@
 }
 
 /// @title A contract that allows to set and delete token properties and change token property permissions.
-/// @dev the ERC-165 identifier for this interface is 0x91a97a68
+/// @dev the ERC-165 identifier for this interface is 0xde0695c2
 contract TokenProperties is Dummy, ERC165 {
+	// /// @notice Set permissions for token property.
+	// /// @dev Throws error if `msg.sender` is not admin or owner of the collection.
+	// /// @param key Property key.
+	// /// @param isMutable Permission to mutate property.
+	// /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
+	// /// @param tokenOwner Permission to mutate property by token owner if property is mutable.
+	// /// @dev EVM selector for this function is: 0x222d97fa,
+	// ///  or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
+	// function setTokenPropertyPermission(string memory key, bool isMutable, bool collectionAdmin, bool tokenOwner) public {
+	// 	require(false, stub_error);
+	// 	key;
+	// 	isMutable;
+	// 	collectionAdmin;
+	// 	tokenOwner;
+	// 	dummy = 0;
+	// }
+
 	/// @notice Set permissions for token property.
 	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
-	/// @param key Property key.
-	/// @param isMutable Permission to mutate property.
-	/// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
-	/// @param tokenOwner Permission to mutate property by token owner if property is mutable.
-	/// @dev EVM selector for this function is: 0x222d97fa,
-	///  or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
-	function setTokenPropertyPermission(
-		string memory key,
-		bool isMutable,
-		bool collectionAdmin,
-		bool tokenOwner
-	) public {
+	/// @param permissions Permissions for keys.
+	/// @dev EVM selector for this function is: 0xbd92983a,
+	///  or in textual repr: setTokenPropertyPermissions((string,(uint8,bool)[])[])
+	function setTokenPropertyPermissions(Tuple48[] memory permissions) public {
 		require(false, stub_error);
-		key;
-		isMutable;
-		collectionAdmin;
-		tokenOwner;
+		permissions;
 		dummy = 0;
 	}
 
+	/// @dev EVM selector for this function is: 0xf23d7790,
+	///  or in textual repr: tokenPropertyPermissions()
+	function tokenPropertyPermissions() public view returns (Tuple48[] memory) {
+		require(false, stub_error);
+		dummy;
+		return new Tuple48[](0);
+	}
+
 	// /// @notice Set token property value.
 	// /// @dev Throws error if `msg.sender` has no permission to edit the property.
 	// /// @param tokenId ID of the token.
@@ -118,6 +132,24 @@
 	bytes value;
 }
 
+enum EthTokenPermissions {
+	Mutable,
+	TokenOwner,
+	CollectionAdmin
+}
+
+/// @dev anonymous struct
+struct Tuple48 {
+	string field_0;
+	Tuple46[] field_1;
+}
+
+/// @dev anonymous struct
+struct Tuple46 {
+	EthTokenPermissions field_0;
+	bool field_1;
+}
+
 /// @title A contract that allows you to work with collections.
 /// @dev the ERC-165 identifier for this interface is 0xb5e1747f
 contract Collection is Dummy, ERC165 {
modifiedpallets/refungible/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/refungible/CHANGELOG.md
+++ b/pallets/refungible/CHANGELOG.md
@@ -4,6 +4,16 @@
 
 <!-- bureaucrate goes here -->
 
+## [0.2.10] - 2022-12-16
+
+### Added
+
+- The function `tokenPropertyPermissions` and `setTokenPropertyPermissions` to `TokenProperties` interface.
+
+### Changed
+
+- Hide `setTokenPropertyPermission` function in `TokenProperties` interface.
+
 ## [0.2.9] - 2022-11-18
 
 ### Added
modifiedpallets/refungible/Cargo.tomldiffbeforeafterboth
--- a/pallets/refungible/Cargo.toml
+++ b/pallets/refungible/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "pallet-refungible"
-version = "0.2.8"
+version = "0.2.10"
 license = "GPLv3"
 edition = "2021"
 
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -33,7 +33,7 @@
 use pallet_common::{
 	CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,
 	erc::{CommonEvmHandler, CollectionCall, static_property::key},
-	eth::EthCrossAccount,
+	eth::{EthCrossAccount, EthTokenPermissions},
 	Error as CommonError,
 };
 use pallet_evm::{account::CrossAccountId, PrecompileHandle};
@@ -63,6 +63,7 @@
 	/// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
 	/// @param tokenOwner Permission to mutate property by token owner if property is mutable.
 	#[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]
+	#[solidity(hide)]
 	fn set_token_property_permission(
 		&mut self,
 		caller: caller,
@@ -89,6 +90,77 @@
 		.map_err(dispatch_to_evm::<T>)
 	}
 
+	/// @notice Set permissions for token property.
+	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
+	/// @param permissions Permissions for keys.
+	#[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]
+	fn set_token_property_permissions(
+		&mut self,
+		caller: caller,
+		permissions: Vec<(string, Vec<(EthTokenPermissions, bool)>)>,
+	) -> Result<()> {
+		let caller = T::CrossAccountId::from_eth(caller);
+		const PERMISSIONS_FIELDS_COUNT: usize = 3;
+
+		let mut perms = Vec::new();
+
+		for (key, pp) in permissions {
+			if pp.len() > PERMISSIONS_FIELDS_COUNT {
+				return Err(alloc::format!(
+					"Actual number of fields {} for {}, which exceeds the maximum value of {}",
+					pp.len(),
+					stringify!(EthTokenPermissions),
+					PERMISSIONS_FIELDS_COUNT
+				)
+				.as_str()
+				.into());
+			}
+
+			let mut token_permission = PropertyPermission {
+				mutable: false,
+				collection_admin: false,
+				token_owner: false,
+			};
+
+			for (perm, value) in pp {
+				match perm {
+					EthTokenPermissions::Mutable => token_permission.mutable = value,
+					EthTokenPermissions::TokenOwner => token_permission.token_owner = value,
+					EthTokenPermissions::CollectionAdmin => {
+						token_permission.collection_admin = value
+					}
+				}
+			}
+
+			perms.push(PropertyKeyPermission {
+				key: key.into_bytes().try_into().map_err(|_| "too long key")?,
+				permission: token_permission,
+			});
+		}
+
+		<Pallet<T>>::set_token_property_permissions(self, &caller, perms)
+			.map_err(dispatch_to_evm::<T>)
+	}
+
+	/// @notice Get permissions for token properties.
+	fn token_property_permissions(
+		&self,
+	) -> Result<Vec<(string, Vec<(EthTokenPermissions, bool)>)>> {
+		let perms = <Pallet<T>>::token_property_permission(self.id);
+		Ok(perms
+			.into_iter()
+			.map(|(key, pp)| {
+				let key = string::from_utf8(key.into_inner()).expect("Stored key must be valid");
+				let pp = vec![
+					(EthTokenPermissions::Mutable, pp.mutable),
+					(EthTokenPermissions::TokenOwner, pp.token_owner),
+					(EthTokenPermissions::CollectionAdmin, pp.collection_admin),
+				];
+				(key, pp)
+			})
+			.collect())
+	}
+
 	/// @notice Set token property value.
 	/// @dev Throws error if `msg.sender` has no permission to edit the property.
 	/// @param tokenId ID of the token.
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -113,7 +113,7 @@
 	AccessMode, budget::Budget, CollectionId, CollectionFlags, CollectionPropertiesVec,
 	CreateCollectionData, CustomDataLimit, mapping::TokenAddressMapping, MAX_ITEMS_PER_BATCH,
 	MAX_REFUNGIBLE_PIECES, Property, PropertyKey, PropertyKeyPermission, PropertyPermission,
-	PropertyScope, PropertyValue, TokenId, TrySetProperty,
+	PropertyScope, PropertyValue, TokenId, TrySetProperty, PropertiesPermissionMap,
 };
 
 pub use pallet::*;
@@ -1378,6 +1378,10 @@
 		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)
 	}
 
+	pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {
+		<PalletCommon<T>>::property_permissions(collection_id)
+	}
+
 	pub fn set_scoped_token_property_permissions(
 		collection: &RefungibleHandle<T>,
 		sender: &T::CrossAccountId,
modifiedpallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth
--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -18,30 +18,45 @@
 }
 
 /// @title A contract that allows to set and delete token properties and change token property permissions.
-/// @dev the ERC-165 identifier for this interface is 0x91a97a68
+/// @dev the ERC-165 identifier for this interface is 0xde0695c2
 contract TokenProperties is Dummy, ERC165 {
+	// /// @notice Set permissions for token property.
+	// /// @dev Throws error if `msg.sender` is not admin or owner of the collection.
+	// /// @param key Property key.
+	// /// @param isMutable Permission to mutate property.
+	// /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
+	// /// @param tokenOwner Permission to mutate property by token owner if property is mutable.
+	// /// @dev EVM selector for this function is: 0x222d97fa,
+	// ///  or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
+	// function setTokenPropertyPermission(string memory key, bool isMutable, bool collectionAdmin, bool tokenOwner) public {
+	// 	require(false, stub_error);
+	// 	key;
+	// 	isMutable;
+	// 	collectionAdmin;
+	// 	tokenOwner;
+	// 	dummy = 0;
+	// }
+
 	/// @notice Set permissions for token property.
 	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
-	/// @param key Property key.
-	/// @param isMutable Permission to mutate property.
-	/// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
-	/// @param tokenOwner Permission to mutate property by token owner if property is mutable.
-	/// @dev EVM selector for this function is: 0x222d97fa,
-	///  or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
-	function setTokenPropertyPermission(
-		string memory key,
-		bool isMutable,
-		bool collectionAdmin,
-		bool tokenOwner
-	) public {
+	/// @param permissions Permissions for keys.
+	/// @dev EVM selector for this function is: 0xbd92983a,
+	///  or in textual repr: setTokenPropertyPermissions((string,(uint8,bool)[])[])
+	function setTokenPropertyPermissions(Tuple53[] memory permissions) public {
 		require(false, stub_error);
-		key;
-		isMutable;
-		collectionAdmin;
-		tokenOwner;
+		permissions;
 		dummy = 0;
 	}
 
+	/// @notice Get permissions for token properties.
+	/// @dev EVM selector for this function is: 0xf23d7790,
+	///  or in textual repr: tokenPropertyPermissions()
+	function tokenPropertyPermissions() public view returns (Tuple53[] memory) {
+		require(false, stub_error);
+		dummy;
+		return new Tuple53[](0);
+	}
+
 	// /// @notice Set token property value.
 	// /// @dev Throws error if `msg.sender` has no permission to edit the property.
 	// /// @param tokenId ID of the token.
@@ -118,6 +133,24 @@
 	bytes value;
 }
 
+enum EthTokenPermissions {
+	Mutable,
+	TokenOwner,
+	CollectionAdmin
+}
+
+/// @dev anonymous struct
+struct Tuple53 {
+	string field_0;
+	Tuple51[] field_1;
+}
+
+/// @dev anonymous struct
+struct Tuple51 {
+	EthTokenPermissions field_0;
+	bool field_1;
+}
+
 /// @title A contract that allows you to work with collections.
 /// @dev the ERC-165 identifier for this interface is 0xb5e1747f
 contract Collection is Dummy, ERC165 {
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -1010,7 +1010,7 @@
 pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;
 
 /// Property permission.
-#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]
+#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone, Default)]
 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
 pub struct PropertyPermission {
 	/// Permission to change the property and property permission.
modifiedtests/src/eth/abi/nonFungible.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/nonFungible.json
+++ b/tests/src/eth/abi/nonFungible.json
@@ -697,12 +697,29 @@
   },
   {
     "inputs": [
-      { "internalType": "string", "name": "key", "type": "string" },
-      { "internalType": "bool", "name": "isMutable", "type": "bool" },
-      { "internalType": "bool", "name": "collectionAdmin", "type": "bool" },
-      { "internalType": "bool", "name": "tokenOwner", "type": "bool" }
+      {
+        "components": [
+          { "internalType": "string", "name": "field_0", "type": "string" },
+          {
+            "components": [
+              {
+                "internalType": "enum EthTokenPermissions",
+                "name": "field_0",
+                "type": "uint8"
+              },
+              { "internalType": "bool", "name": "field_1", "type": "bool" }
+            ],
+            "internalType": "struct Tuple46[]",
+            "name": "field_1",
+            "type": "tuple[]"
+          }
+        ],
+        "internalType": "struct Tuple48[]",
+        "name": "permissions",
+        "type": "tuple[]"
+      }
     ],
-    "name": "setTokenPropertyPermission",
+    "name": "setTokenPropertyPermissions",
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
@@ -743,6 +760,35 @@
     "type": "function"
   },
   {
+    "inputs": [],
+    "name": "tokenPropertyPermissions",
+    "outputs": [
+      {
+        "components": [
+          { "internalType": "string", "name": "field_0", "type": "string" },
+          {
+            "components": [
+              {
+                "internalType": "enum EthTokenPermissions",
+                "name": "field_0",
+                "type": "uint8"
+              },
+              { "internalType": "bool", "name": "field_1", "type": "bool" }
+            ],
+            "internalType": "struct Tuple46[]",
+            "name": "field_1",
+            "type": "tuple[]"
+          }
+        ],
+        "internalType": "struct Tuple48[]",
+        "name": "",
+        "type": "tuple[]"
+      }
+    ],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
     "inputs": [
       { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
     ],
modifiedtests/src/eth/abi/reFungible.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/reFungible.json
+++ b/tests/src/eth/abi/reFungible.json
@@ -679,12 +679,29 @@
   },
   {
     "inputs": [
-      { "internalType": "string", "name": "key", "type": "string" },
-      { "internalType": "bool", "name": "isMutable", "type": "bool" },
-      { "internalType": "bool", "name": "collectionAdmin", "type": "bool" },
-      { "internalType": "bool", "name": "tokenOwner", "type": "bool" }
+      {
+        "components": [
+          { "internalType": "string", "name": "field_0", "type": "string" },
+          {
+            "components": [
+              {
+                "internalType": "enum EthTokenPermissions",
+                "name": "field_0",
+                "type": "uint8"
+              },
+              { "internalType": "bool", "name": "field_1", "type": "bool" }
+            ],
+            "internalType": "struct Tuple51[]",
+            "name": "field_1",
+            "type": "tuple[]"
+          }
+        ],
+        "internalType": "struct Tuple53[]",
+        "name": "permissions",
+        "type": "tuple[]"
+      }
     ],
-    "name": "setTokenPropertyPermission",
+    "name": "setTokenPropertyPermissions",
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
@@ -734,6 +751,35 @@
     "type": "function"
   },
   {
+    "inputs": [],
+    "name": "tokenPropertyPermissions",
+    "outputs": [
+      {
+        "components": [
+          { "internalType": "string", "name": "field_0", "type": "string" },
+          {
+            "components": [
+              {
+                "internalType": "enum EthTokenPermissions",
+                "name": "field_0",
+                "type": "uint8"
+              },
+              { "internalType": "bool", "name": "field_1", "type": "bool" }
+            ],
+            "internalType": "struct Tuple51[]",
+            "name": "field_1",
+            "type": "tuple[]"
+          }
+        ],
+        "internalType": "struct Tuple53[]",
+        "name": "",
+        "type": "tuple[]"
+      }
+    ],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
     "inputs": [
       { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
     ],
modifiedtests/src/eth/api/UniqueNFT.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -13,22 +13,28 @@
 }
 
 /// @title A contract that allows to set and delete token properties and change token property permissions.
-/// @dev the ERC-165 identifier for this interface is 0x91a97a68
+/// @dev the ERC-165 identifier for this interface is 0xde0695c2
 interface TokenProperties is Dummy, ERC165 {
+	// /// @notice Set permissions for token property.
+	// /// @dev Throws error if `msg.sender` is not admin or owner of the collection.
+	// /// @param key Property key.
+	// /// @param isMutable Permission to mutate property.
+	// /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
+	// /// @param tokenOwner Permission to mutate property by token owner if property is mutable.
+	// /// @dev EVM selector for this function is: 0x222d97fa,
+	// ///  or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
+	// function setTokenPropertyPermission(string memory key, bool isMutable, bool collectionAdmin, bool tokenOwner) external;
+
 	/// @notice Set permissions for token property.
 	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
-	/// @param key Property key.
-	/// @param isMutable Permission to mutate property.
-	/// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
-	/// @param tokenOwner Permission to mutate property by token owner if property is mutable.
-	/// @dev EVM selector for this function is: 0x222d97fa,
-	///  or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
-	function setTokenPropertyPermission(
-		string memory key,
-		bool isMutable,
-		bool collectionAdmin,
-		bool tokenOwner
-	) external;
+	/// @param permissions Permissions for keys.
+	/// @dev EVM selector for this function is: 0xbd92983a,
+	///  or in textual repr: setTokenPropertyPermissions((string,(uint8,bool)[])[])
+	function setTokenPropertyPermissions(Tuple43[] memory permissions) external;
+
+	/// @dev EVM selector for this function is: 0xf23d7790,
+	///  or in textual repr: tokenPropertyPermissions()
+	function tokenPropertyPermissions() external view returns (Tuple43[] memory);
 
 	// /// @notice Set token property value.
 	// /// @dev Throws error if `msg.sender` has no permission to edit the property.
@@ -79,6 +85,24 @@
 	bytes value;
 }
 
+enum EthTokenPermissions {
+	Mutable,
+	TokenOwner,
+	CollectionAdmin
+}
+
+/// @dev anonymous struct
+struct Tuple43 {
+	string field_0;
+	Tuple41[] field_1;
+}
+
+/// @dev anonymous struct
+struct Tuple41 {
+	EthTokenPermissions field_0;
+	bool field_1;
+}
+
 /// @title A contract that allows you to work with collections.
 /// @dev the ERC-165 identifier for this interface is 0xb5e1747f
 interface Collection is Dummy, ERC165 {
modifiedtests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -13,22 +13,29 @@
 }
 
 /// @title A contract that allows to set and delete token properties and change token property permissions.
-/// @dev the ERC-165 identifier for this interface is 0x91a97a68
+/// @dev the ERC-165 identifier for this interface is 0xde0695c2
 interface TokenProperties is Dummy, ERC165 {
+	// /// @notice Set permissions for token property.
+	// /// @dev Throws error if `msg.sender` is not admin or owner of the collection.
+	// /// @param key Property key.
+	// /// @param isMutable Permission to mutate property.
+	// /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
+	// /// @param tokenOwner Permission to mutate property by token owner if property is mutable.
+	// /// @dev EVM selector for this function is: 0x222d97fa,
+	// ///  or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
+	// function setTokenPropertyPermission(string memory key, bool isMutable, bool collectionAdmin, bool tokenOwner) external;
+
 	/// @notice Set permissions for token property.
 	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
-	/// @param key Property key.
-	/// @param isMutable Permission to mutate property.
-	/// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.
-	/// @param tokenOwner Permission to mutate property by token owner if property is mutable.
-	/// @dev EVM selector for this function is: 0x222d97fa,
-	///  or in textual repr: setTokenPropertyPermission(string,bool,bool,bool)
-	function setTokenPropertyPermission(
-		string memory key,
-		bool isMutable,
-		bool collectionAdmin,
-		bool tokenOwner
-	) external;
+	/// @param permissions Permissions for keys.
+	/// @dev EVM selector for this function is: 0xbd92983a,
+	///  or in textual repr: setTokenPropertyPermissions((string,(uint8,bool)[])[])
+	function setTokenPropertyPermissions(Tuple47[] memory permissions) external;
+
+	/// @notice Get permissions for token properties.
+	/// @dev EVM selector for this function is: 0xf23d7790,
+	///  or in textual repr: tokenPropertyPermissions()
+	function tokenPropertyPermissions() external view returns (Tuple47[] memory);
 
 	// /// @notice Set token property value.
 	// /// @dev Throws error if `msg.sender` has no permission to edit the property.
@@ -79,6 +86,24 @@
 	bytes value;
 }
 
+enum EthTokenPermissions {
+	Mutable,
+	TokenOwner,
+	CollectionAdmin
+}
+
+/// @dev anonymous struct
+struct Tuple47 {
+	string field_0;
+	Tuple45[] field_1;
+}
+
+/// @dev anonymous struct
+struct Tuple45 {
+	EthTokenPermissions field_0;
+	bool field_1;
+}
+
 /// @title A contract that allows you to work with collections.
 /// @dev the ERC-165 identifier for this interface is 0xb5e1747f
 interface Collection is Dummy, ERC165 {
modifiedtests/src/eth/events.test.tsdiffbeforeafterboth
--- a/tests/src/eth/events.test.ts
+++ b/tests/src/eth/events.test.ts
@@ -19,7 +19,7 @@
 import {EthUniqueHelper, itEth, usingEthPlaygrounds} from './util';
 import {IEvent, TCollectionMode} from '../util/playgrounds/types';
 import {Pallets, requirePalletsOrSkip} from '../util';
-import {NormalizedEvent} from './util/playgrounds/types';
+import {EthTokenPermissions, NormalizedEvent} from './util/playgrounds/types';
 
 let donor: IKeyringPair;
   
@@ -119,7 +119,13 @@
     ethEvents.push(event);
   });
   const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['PropertyPermissionSet']}]);
-  await collection.methods.setTokenPropertyPermission('testKey', true, true, true).send({from: owner});
+  await collection.methods.setTokenPropertyPermissions([
+    ['A', [
+      [EthTokenPermissions.Mutable, true], 
+      [EthTokenPermissions.TokenOwner, true], 
+      [EthTokenPermissions.CollectionAdmin, true]],
+    ],
+  ]).send({from: owner});
   await helper.wait.newBlocks(1);
   expect(ethEvents).to.be.like([
     {
@@ -374,7 +380,13 @@
   const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
   const result = await collection.methods.mint(owner).send({from: owner});
   const tokenId = result.events.Transfer.returnValues.tokenId;
-  await collection.methods.setTokenPropertyPermission('A', true, true, true).send({from: owner});
+  await collection.methods.setTokenPropertyPermissions([
+    ['A', [
+      [EthTokenPermissions.Mutable, true], 
+      [EthTokenPermissions.TokenOwner, true], 
+      [EthTokenPermissions.CollectionAdmin, true]],
+    ],
+  ]).send({from: owner});
 
 
   const ethEvents: any = [];
modifiedtests/src/eth/tokenProperties.test.tsdiffbeforeafterboth
before · tests/src/eth/tokenProperties.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 {Contract} from 'web3-eth-contract';19import {itEth, usingEthPlaygrounds, expect} from './util';20import {ITokenPropertyPermission} from '../util/playgrounds/types';21import {Pallets} from '../util';22import {UniqueNFTCollection, UniqueNFToken, UniqueRFTCollection} from '../util/playgrounds/unique';2324describe('EVM token properties', () => {25  let donor: IKeyringPair;26  let alice: IKeyringPair;2728  before(async function() {29    await usingEthPlaygrounds(async (helper, privateKey) => {30      donor = await privateKey({filename: __filename});31      [alice] = await helper.arrange.createAccounts([100n], donor);32    });33  });3435  itEth('Can be reconfigured', async({helper}) => {36    const caller = await helper.eth.createAccountWithBalance(donor);37    for(const [mutable,collectionAdmin, tokenOwner] of cartesian([], [false, true], [false, true], [false, true])) {38      const collection = await helper.nft.mintCollection(alice);39      await collection.addAdmin(alice, {Ethereum: caller});40      41      const address = helper.ethAddress.fromCollectionId(collection.collectionId);42      const contract = helper.ethNativeContract.collection(address, 'nft', caller);43  44      await contract.methods.setTokenPropertyPermission('testKey', mutable, collectionAdmin, tokenOwner).send({from: caller});45  46      expect(await collection.getPropertyPermissions()).to.be.deep.equal([{47        key: 'testKey',48        permission: {mutable, collectionAdmin, tokenOwner},49      }]);50    }51  });5253  [54    {55      method: 'setProperties',56      methodParams: [[{key: 'testKey1', value: Buffer.from('testValue1')}, {key: 'testKey2', value: Buffer.from('testValue2')}]],57      expectedProps: [{key: 'testKey1', value: 'testValue1'}, {key: 'testKey2', value: 'testValue2'}],58    },59    {60      method: 'setProperty' /*Soft-deprecated*/, 61      methodParams: ['testKey1', Buffer.from('testValue1')],62      expectedProps: [{key: 'testKey1', value: 'testValue1'}],63    },64  ].map(testCase => 65    itEth(`[${testCase.method}] Can be set`, async({helper}) => {66      const caller = await helper.eth.createAccountWithBalance(donor);67      const collection = await helper.nft.mintCollection(alice, {68        tokenPropertyPermissions: [{69          key: 'testKey1',70          permission: {71            collectionAdmin: true,72          },73        }, {74          key: 'testKey2',75          permission: {76            collectionAdmin: true,77          },78        }],79      });8081      await collection.addAdmin(alice, {Ethereum: caller});82      const token = await collection.mintToken(alice);83  84      const collectionEvm = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller, testCase.method === 'setProperty');85  86      await collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller});87  88      const properties = await token.getProperties();89      expect(properties).to.deep.equal(testCase.expectedProps);90    }));91  92  [93    {mode: 'nft' as const, requiredPallets: []},94    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},95  ].map(testCase => 96    itEth.ifWithPallets(`Can be multiple set/read for ${testCase.mode}`, testCase.requiredPallets, async({helper}) => {97      const caller = await helper.eth.createAccountWithBalance(donor);98      99      const properties = Array(5).fill(0).map((_, i) => { return {key: `key_${i}`, value: Buffer.from(`value_${i}`)}; });100      const permissions: ITokenPropertyPermission[] = properties.map(p => { return {key: p.key, permission: {tokenOwner: true,101        collectionAdmin: true,102        mutable: true}}; });103      104      const collection = await helper[testCase.mode].mintCollection(alice, {105        tokenPrefix: 'ethp',106        tokenPropertyPermissions: permissions,107      }) as UniqueNFTCollection | UniqueRFTCollection;108      109      const token = await collection.mintToken(alice);110      111      const valuesBefore = await token.getProperties(properties.map(p => p.key));112      expect(valuesBefore).to.be.deep.equal([]);113      114      115      await collection.addAdmin(alice, {Ethereum: caller});116      117      const address = helper.ethAddress.fromCollectionId(collection.collectionId);118      const contract = helper.ethNativeContract.collection(address, testCase.mode, caller);119      120      expect(await contract.methods.properties(token.tokenId, []).call()).to.be.deep.equal([]);121  122      await contract.methods.setProperties(token.tokenId, properties).send({from: caller});123  124      const values = await token.getProperties(properties.map(p => p.key));125      expect(values).to.be.deep.equal(properties.map(p => { return {key: p.key, value: p.value.toString()}; }));126      127      expect(await contract.methods.properties(token.tokenId, []).call()).to.be.like(properties128        .map(p => { return helper.ethProperty.property(p.key, p.value.toString()); }));129      130      expect(await contract.methods.properties(token.tokenId, [properties[0].key]).call())131        .to.be.like([helper.ethProperty.property(properties[0].key, properties[0].value.toString())]);132    }));133  134  [135    {mode: 'nft' as const, requiredPallets: []},136    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},137  ].map(testCase => 138    itEth.ifWithPallets(`Can be deleted for ${testCase.mode}`, testCase.requiredPallets, async({helper}) => {139      const caller = await helper.eth.createAccountWithBalance(donor);140      const collection = await helper[testCase.mode].mintCollection(alice, {141        tokenPropertyPermissions: [{142          key: 'testKey',143          permission: {144            mutable: true,145            collectionAdmin: true,146          },147        },148        {149          key: 'testKey_1',150          permission: {151            mutable: true,152            collectionAdmin: true,153          },154        }],155      });156    157      const token = await collection.mintToken(alice);158      await token.setProperties(alice, [{key: 'testKey', value: 'testValue'}, {key: 'testKey_1', value: 'testValue_1'}]);159      expect(await token.getProperties()).to.has.length(2);160161      await collection.addAdmin(alice, {Ethereum: caller});162163      const address = helper.ethAddress.fromCollectionId(collection.collectionId);164      const contract = helper.ethNativeContract.collection(address, testCase.mode, caller);165166      await contract.methods.deleteProperties(token.tokenId, ['testKey', 'testKey_1']).send({from: caller});167168      const result = await token.getProperties(['testKey', 'testKey_1']);169      expect(result.length).to.equal(0);170    }));171172  itEth('Can be read', async({helper}) => {173    const caller = helper.eth.createAccount();174    const collection = await helper.nft.mintCollection(alice, {175      tokenPropertyPermissions: [{176        key: 'testKey',177        permission: {178          collectionAdmin: true,179        },180      }],181    });182  183    const token = await collection.mintToken(alice);184    await token.setProperties(alice, [{key: 'testKey', value: 'testValue'}]);185186    const address = helper.ethAddress.fromCollectionId(collection.collectionId);187    const contract = helper.ethNativeContract.collection(address, 'nft', caller);188189    const value = await contract.methods.property(token.tokenId, 'testKey').call();190    expect(value).to.equal(helper.getWeb3().utils.toHex('testValue'));191  });192});193194describe('EVM token properties negative', () => {195  let donor: IKeyringPair;196  let alice: IKeyringPair;197  let caller: string;198  let aliceCollection: UniqueNFTCollection;199  let token: UniqueNFToken;200  const tokenProps = [{key: 'testKey_1', value: 'testValue_1'}, {key: 'testKey_2', value: 'testValue_2'}];201  let collectionEvm: Contract;202203  before(async function() {204    await usingEthPlaygrounds(async (helper, privateKey) => {205      donor = await privateKey({filename: __filename});206      [alice] = await helper.arrange.createAccounts([100n], donor);207    });208  });209210  beforeEach(async () => {211    // 1. create collection with props: testKey_1, testKey_2212    // 2. create token and set props testKey_1, testKey_2213    await usingEthPlaygrounds(async (helper) => {214      aliceCollection = await helper.nft.mintCollection(alice, {215        tokenPropertyPermissions: [{216          key: 'testKey_1',217          permission: {218            mutable: true,219            collectionAdmin: true,220          },221        },222        {223          key: 'testKey_2',224          permission: {225            mutable: true,226            collectionAdmin: true,227          },228        }],229      }); 230      token = await aliceCollection.mintToken(alice);231      await token.setProperties(alice, tokenProps);232      collectionEvm = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, true);233    });234  });235236  [237    {method: 'setProperty', methodParams: [tokenProps[1].key, Buffer.from('newValue')]},238    {method: 'setProperties', methodParams: [[{key: tokenProps[1].key, value: Buffer.from('newValue')}]]},239  ].map(testCase =>240    itEth(`[${testCase.method}] Cannot set properties of non-owned collection`, async ({helper}) => {241      caller = await helper.eth.createAccountWithBalance(donor);242      collectionEvm = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, true);243      // Caller not an owner and not an admin, so he cannot set properties:244      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');245      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;246247      // Props have not changed:248      const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));249      const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();250      expect(actualProps).to.deep.eq(expectedProps);251    }));252253  [254    {method: 'setProperty', methodParams: ['testKey_3', Buffer.from('testValue3')]},255    {method: 'setProperties', methodParams: [[{key: 'testKey_3', value: Buffer.from('testValue3')}]]},256  ].map(testCase =>257    itEth(`[${testCase.method}] Cannot set non-existing properties`, async ({helper}) => {258      caller = await helper.eth.createAccountWithBalance(donor);259      collectionEvm = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, true);260      await helper.collection.addAdmin(alice, aliceCollection.collectionId, {Ethereum: caller});261262      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');263      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;264265      // Props have not changed:266      const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));267      const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();268      expect(actualProps).to.deep.eq(expectedProps);269    }));270271  [272    {method: 'deleteProperty', methodParams: ['testKey_2']},273    {method: 'deleteProperties', methodParams: [['testKey_2']]},274  ].map(testCase =>  275    itEth(`[${testCase.method}] Cannot delete properties of non-owned collection`, async ({helper}) => {276      caller = await helper.eth.createAccountWithBalance(donor);277      collectionEvm = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, testCase.method == 'deleteProperty');278      // Caller not an owner and not an admin, so he cannot set properties:279      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');280      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;281282      // Props have not changed:283      const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));284      const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();285      expect(actualProps).to.deep.eq(expectedProps);286    }));287   288  [289    {method: 'deleteProperty', methodParams: ['testKey_3']},290    {method: 'deleteProperties', methodParams: [['testKey_3']]},291  ].map(testCase =>  292    itEth(`[${testCase.method}] Cannot delete non-existing properties`, async ({helper}) => {293      caller = await helper.eth.createAccountWithBalance(donor);294      collectionEvm = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, testCase.method == 'deleteProperty');295      await helper.collection.addAdmin(alice, aliceCollection.collectionId, {Ethereum: caller});296      // Caller cannot delete non-existing properties:297      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');298      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;299      // Props have not changed:300      const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));301      const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();302      expect(actualProps).to.deep.eq(expectedProps);303    }));304});305306307type ElementOf<A> = A extends readonly (infer T)[] ? T : never;308function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {309  if(args.length === 0) {310    yield internalRest as any;311    return;312  }313  for(const value of args[0]) {314    yield* cartesian([...internalRest, value], ...args.slice(1)) as any;315  }316}
after · tests/src/eth/tokenProperties.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 {Contract} from 'web3-eth-contract';19import {itEth, usingEthPlaygrounds, expect} from './util';20import {ITokenPropertyPermission} from '../util/playgrounds/types';21import {Pallets} from '../util';22import {UniqueNFTCollection, UniqueNFToken, UniqueRFTCollection} from '../util/playgrounds/unique';23import {EthTokenPermissions} from './util/playgrounds/types';2425describe('EVM token properties', () => {26  let donor: IKeyringPair;27  let alice: IKeyringPair;2829  before(async function() {30    await usingEthPlaygrounds(async (helper, privateKey) => {31      donor = await privateKey({filename: __filename});32      [alice] = await helper.arrange.createAccounts([100n], donor);33    });34  });3536  [37    {mode: 'nft' as const, requiredPallets: []},38    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},39  ].map(testCase =>40    itEth.ifWithPallets(`[${testCase.mode}] Set and get token property permissions`, testCase.requiredPallets, async({helper}) => {41      const owner = await helper.eth.createAccountWithBalance(donor);42      const caller = await helper.ethCrossAccount.createAccountWithBalance(donor);43      for(const [mutable,collectionAdmin, tokenOwner] of cartesian([], [false, true], [false, true], [false, true])) {44        const {collectionId, collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');45        const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);46        await collection.methods.addCollectionAdminCross(caller).send({from: owner});4748        await collection.methods.setTokenPropertyPermissions([49          ['testKey', [50            [EthTokenPermissions.Mutable, mutable], 51            [EthTokenPermissions.TokenOwner, tokenOwner], 52            [EthTokenPermissions.CollectionAdmin, collectionAdmin]],53          ],54        ]).send({from: caller.eth});55      56        expect(await helper[testCase.mode].getPropertyPermissions(collectionId)).to.be.deep.equal([{57          key: 'testKey',58          permission: {mutable, collectionAdmin, tokenOwner},59        }]);6061        expect(await collection.methods.tokenPropertyPermissions().call({from: caller.eth})).to.be.like([62          ['testKey', [63            [EthTokenPermissions.Mutable.toString(), mutable], 64            [EthTokenPermissions.TokenOwner.toString(), tokenOwner], 65            [EthTokenPermissions.CollectionAdmin.toString(), collectionAdmin]],66          ],67        ]);68      }69    }));7071  [72    {mode: 'nft' as const, requiredPallets: []},73    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},74  ].map(testCase =>75    itEth.ifWithPallets(`[${testCase.mode}] Set and get multiple token property permissions as owner`, testCase.requiredPallets, async({helper}) => {76      const owner = await helper.eth.createAccountWithBalance(donor);77      78      const {collectionId, collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');79      const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);8081      await collection.methods.setTokenPropertyPermissions([82        ['testKey_0', [83          [EthTokenPermissions.Mutable, true], 84          [EthTokenPermissions.TokenOwner, true], 85          [EthTokenPermissions.CollectionAdmin, true]],86        ],87        ['testKey_1', [88          [EthTokenPermissions.Mutable, true], 89          [EthTokenPermissions.TokenOwner, false], 90          [EthTokenPermissions.CollectionAdmin, true]],91        ],92        ['testKey_2', [93          [EthTokenPermissions.Mutable, false], 94          [EthTokenPermissions.TokenOwner, true], 95          [EthTokenPermissions.CollectionAdmin, false]],96        ],97      ]).send({from: owner});98      99      expect(await helper[testCase.mode].getPropertyPermissions(collectionId)).to.be.deep.equal([100        {101          key: 'testKey_0',102          permission: {mutable: true, tokenOwner: true, collectionAdmin: true},103        },104        {105          key: 'testKey_1',106          permission: {mutable: true, tokenOwner: false, collectionAdmin: true},107        },108        {109          key: 'testKey_2',110          permission: {mutable: false, tokenOwner: true, collectionAdmin: false},111        },112      ]);113114      expect(await collection.methods.tokenPropertyPermissions().call({from: owner})).to.be.like([115        ['testKey_0', [116          [EthTokenPermissions.Mutable.toString(), true], 117          [EthTokenPermissions.TokenOwner.toString(), true], 118          [EthTokenPermissions.CollectionAdmin.toString(), true]],119        ],120        ['testKey_1', [121          [EthTokenPermissions.Mutable.toString(), true], 122          [EthTokenPermissions.TokenOwner.toString(), false], 123          [EthTokenPermissions.CollectionAdmin.toString(), true]],124        ],125        ['testKey_2', [126          [EthTokenPermissions.Mutable.toString(), false], 127          [EthTokenPermissions.TokenOwner.toString(), true], 128          [EthTokenPermissions.CollectionAdmin.toString(), false]],129        ],130      ]);131      132    }));133134  [135    {mode: 'nft' as const, requiredPallets: []},136    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},137  ].map(testCase =>138    itEth.ifWithPallets(`[${testCase.mode}] Set and get multiple token property permissions as admin`, testCase.requiredPallets, async({helper}) => {139      const owner = await helper.eth.createAccountWithBalance(donor);140      const caller = await helper.ethCrossAccount.createAccountWithBalance(donor);141      142      const {collectionId, collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');143      const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);144      await collection.methods.addCollectionAdminCross(caller).send({from: owner});145146      await collection.methods.setTokenPropertyPermissions([147        ['testKey_0', [148          [EthTokenPermissions.Mutable, true], 149          [EthTokenPermissions.TokenOwner, true], 150          [EthTokenPermissions.CollectionAdmin, true]],151        ],152        ['testKey_1', [153          [EthTokenPermissions.Mutable, true], 154          [EthTokenPermissions.TokenOwner, false], 155          [EthTokenPermissions.CollectionAdmin, true]],156        ],157        ['testKey_2', [158          [EthTokenPermissions.Mutable, false], 159          [EthTokenPermissions.TokenOwner, true], 160          [EthTokenPermissions.CollectionAdmin, false]],161        ],162      ]).send({from: caller.eth});163      164      expect(await helper[testCase.mode].getPropertyPermissions(collectionId)).to.be.deep.equal([165        {166          key: 'testKey_0',167          permission: {mutable: true, tokenOwner: true, collectionAdmin: true},168        },169        {170          key: 'testKey_1',171          permission: {mutable: true, tokenOwner: false, collectionAdmin: true},172        },173        {174          key: 'testKey_2',175          permission: {mutable: false, tokenOwner: true, collectionAdmin: false},176        },177      ]);178179      expect(await collection.methods.tokenPropertyPermissions().call({from: caller.eth})).to.be.like([180        ['testKey_0', [181          [EthTokenPermissions.Mutable.toString(), true], 182          [EthTokenPermissions.TokenOwner.toString(), true], 183          [EthTokenPermissions.CollectionAdmin.toString(), true]],184        ],185        ['testKey_1', [186          [EthTokenPermissions.Mutable.toString(), true], 187          [EthTokenPermissions.TokenOwner.toString(), false], 188          [EthTokenPermissions.CollectionAdmin.toString(), true]],189        ],190        ['testKey_2', [191          [EthTokenPermissions.Mutable.toString(), false], 192          [EthTokenPermissions.TokenOwner.toString(), true], 193          [EthTokenPermissions.CollectionAdmin.toString(), false]],194        ],195      ]);196      197    }));198199  [200    {201      method: 'setProperties',202      methodParams: [[{key: 'testKey1', value: Buffer.from('testValue1')}, {key: 'testKey2', value: Buffer.from('testValue2')}]],203      expectedProps: [{key: 'testKey1', value: 'testValue1'}, {key: 'testKey2', value: 'testValue2'}],204    },205    {206      method: 'setProperty' /*Soft-deprecated*/, 207      methodParams: ['testKey1', Buffer.from('testValue1')],208      expectedProps: [{key: 'testKey1', value: 'testValue1'}],209    },210  ].map(testCase => 211    itEth(`[${testCase.method}] Can be set`, async({helper}) => {212      const caller = await helper.eth.createAccountWithBalance(donor);213      const collection = await helper.nft.mintCollection(alice, {214        tokenPropertyPermissions: [{215          key: 'testKey1',216          permission: {217            collectionAdmin: true,218          },219        }, {220          key: 'testKey2',221          permission: {222            collectionAdmin: true,223          },224        }],225      });226227      await collection.addAdmin(alice, {Ethereum: caller});228      const token = await collection.mintToken(alice);229  230      const collectionEvm = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller, testCase.method === 'setProperty');231  232      await collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller});233  234      const properties = await token.getProperties();235      expect(properties).to.deep.equal(testCase.expectedProps);236    }));237  238  [239    {mode: 'nft' as const, requiredPallets: []},240    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},241  ].map(testCase => 242    itEth.ifWithPallets(`Can be multiple set/read for ${testCase.mode}`, testCase.requiredPallets, async({helper}) => {243      const caller = await helper.eth.createAccountWithBalance(donor);244      245      const properties = Array(5).fill(0).map((_, i) => { return {key: `key_${i}`, value: Buffer.from(`value_${i}`)}; });246      const permissions: ITokenPropertyPermission[] = properties.map(p => { return {key: p.key, permission: {tokenOwner: true,247        collectionAdmin: true,248        mutable: true}}; });249      250      const collection = await helper[testCase.mode].mintCollection(alice, {251        tokenPrefix: 'ethp',252        tokenPropertyPermissions: permissions,253      }) as UniqueNFTCollection | UniqueRFTCollection;254      255      const token = await collection.mintToken(alice);256      257      const valuesBefore = await token.getProperties(properties.map(p => p.key));258      expect(valuesBefore).to.be.deep.equal([]);259      260      261      await collection.addAdmin(alice, {Ethereum: caller});262      263      const address = helper.ethAddress.fromCollectionId(collection.collectionId);264      const contract = helper.ethNativeContract.collection(address, testCase.mode, caller);265      266      expect(await contract.methods.properties(token.tokenId, []).call()).to.be.deep.equal([]);267  268      await contract.methods.setProperties(token.tokenId, properties).send({from: caller});269  270      const values = await token.getProperties(properties.map(p => p.key));271      expect(values).to.be.deep.equal(properties.map(p => { return {key: p.key, value: p.value.toString()}; }));272      273      expect(await contract.methods.properties(token.tokenId, []).call()).to.be.like(properties274        .map(p => { return helper.ethProperty.property(p.key, p.value.toString()); }));275      276      expect(await contract.methods.properties(token.tokenId, [properties[0].key]).call())277        .to.be.like([helper.ethProperty.property(properties[0].key, properties[0].value.toString())]);278    }));279  280  [281    {mode: 'nft' as const, requiredPallets: []},282    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},283  ].map(testCase => 284    itEth.ifWithPallets(`Can be deleted for ${testCase.mode}`, testCase.requiredPallets, async({helper}) => {285      const caller = await helper.eth.createAccountWithBalance(donor);286      const collection = await helper[testCase.mode].mintCollection(alice, {287        tokenPropertyPermissions: [{288          key: 'testKey',289          permission: {290            mutable: true,291            collectionAdmin: true,292          },293        },294        {295          key: 'testKey_1',296          permission: {297            mutable: true,298            collectionAdmin: true,299          },300        }],301      });302    303      const token = await collection.mintToken(alice);304      await token.setProperties(alice, [{key: 'testKey', value: 'testValue'}, {key: 'testKey_1', value: 'testValue_1'}]);305      expect(await token.getProperties()).to.has.length(2);306307      await collection.addAdmin(alice, {Ethereum: caller});308309      const address = helper.ethAddress.fromCollectionId(collection.collectionId);310      const contract = helper.ethNativeContract.collection(address, testCase.mode, caller);311312      await contract.methods.deleteProperties(token.tokenId, ['testKey', 'testKey_1']).send({from: caller});313314      const result = await token.getProperties(['testKey', 'testKey_1']);315      expect(result.length).to.equal(0);316    }));317318  itEth('Can be read', async({helper}) => {319    const caller = helper.eth.createAccount();320    const collection = await helper.nft.mintCollection(alice, {321      tokenPropertyPermissions: [{322        key: 'testKey',323        permission: {324          collectionAdmin: true,325        },326      }],327    });328  329    const token = await collection.mintToken(alice);330    await token.setProperties(alice, [{key: 'testKey', value: 'testValue'}]);331332    const address = helper.ethAddress.fromCollectionId(collection.collectionId);333    const contract = helper.ethNativeContract.collection(address, 'nft', caller);334335    const value = await contract.methods.property(token.tokenId, 'testKey').call();336    expect(value).to.equal(helper.getWeb3().utils.toHex('testValue'));337  });338});339340describe('EVM token properties negative', () => {341  let donor: IKeyringPair;342  let alice: IKeyringPair;343  let caller: string;344  let aliceCollection: UniqueNFTCollection;345  let token: UniqueNFToken;346  const tokenProps = [{key: 'testKey_1', value: 'testValue_1'}, {key: 'testKey_2', value: 'testValue_2'}];347  let collectionEvm: Contract;348349  before(async function() {350    await usingEthPlaygrounds(async (helper, privateKey) => {351      donor = await privateKey({filename: __filename});352      [alice] = await helper.arrange.createAccounts([100n], donor);353    });354  });355356  beforeEach(async () => {357    // 1. create collection with props: testKey_1, testKey_2358    // 2. create token and set props testKey_1, testKey_2359    await usingEthPlaygrounds(async (helper) => {360      aliceCollection = await helper.nft.mintCollection(alice, {361        tokenPropertyPermissions: [{362          key: 'testKey_1',363          permission: {364            mutable: true,365            collectionAdmin: true,366          },367        },368        {369          key: 'testKey_2',370          permission: {371            mutable: true,372            collectionAdmin: true,373          },374        }],375      }); 376      token = await aliceCollection.mintToken(alice);377      await token.setProperties(alice, tokenProps);378      collectionEvm = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, true);379    });380  });381382  [383    {method: 'setProperty', methodParams: [tokenProps[1].key, Buffer.from('newValue')]},384    {method: 'setProperties', methodParams: [[{key: tokenProps[1].key, value: Buffer.from('newValue')}]]},385  ].map(testCase =>386    itEth(`[${testCase.method}] Cannot set properties of non-owned collection`, async ({helper}) => {387      caller = await helper.eth.createAccountWithBalance(donor);388      collectionEvm = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, true);389      // Caller not an owner and not an admin, so he cannot set properties:390      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');391      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;392393      // Props have not changed:394      const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));395      const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();396      expect(actualProps).to.deep.eq(expectedProps);397    }));398399  [400    {method: 'setProperty', methodParams: ['testKey_3', Buffer.from('testValue3')]},401    {method: 'setProperties', methodParams: [[{key: 'testKey_3', value: Buffer.from('testValue3')}]]},402  ].map(testCase =>403    itEth(`[${testCase.method}] Cannot set non-existing properties`, async ({helper}) => {404      caller = await helper.eth.createAccountWithBalance(donor);405      collectionEvm = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, true);406      await helper.collection.addAdmin(alice, aliceCollection.collectionId, {Ethereum: caller});407408      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');409      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;410411      // Props have not changed:412      const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));413      const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();414      expect(actualProps).to.deep.eq(expectedProps);415    }));416417  [418    {method: 'deleteProperty', methodParams: ['testKey_2']},419    {method: 'deleteProperties', methodParams: [['testKey_2']]},420  ].map(testCase =>  421    itEth(`[${testCase.method}] Cannot delete properties of non-owned collection`, async ({helper}) => {422      caller = await helper.eth.createAccountWithBalance(donor);423      collectionEvm = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, testCase.method == 'deleteProperty');424      // Caller not an owner and not an admin, so he cannot set properties:425      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');426      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;427428      // Props have not changed:429      const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));430      const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();431      expect(actualProps).to.deep.eq(expectedProps);432    }));433   434  [435    {method: 'deleteProperty', methodParams: ['testKey_3']},436    {method: 'deleteProperties', methodParams: [['testKey_3']]},437  ].map(testCase =>  438    itEth(`[${testCase.method}] Cannot delete non-existing properties`, async ({helper}) => {439      caller = await helper.eth.createAccountWithBalance(donor);440      collectionEvm = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, testCase.method == 'deleteProperty');441      await helper.collection.addAdmin(alice, aliceCollection.collectionId, {Ethereum: caller});442      // Caller cannot delete non-existing properties:443      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');444      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;445      // Props have not changed:446      const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));447      const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();448      expect(actualProps).to.deep.eq(expectedProps);449    }));450451  [452    {mode: 'nft' as const, requiredPallets: []},453    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},454  ].map(testCase =>455    itEth.ifWithPallets(`[${testCase.mode}] Cant set token property permissions as non owner or admin`, testCase.requiredPallets, async({helper}) => {456      const owner = await helper.eth.createAccountWithBalance(donor);457      const caller = await helper.eth.createAccountWithBalance(donor);458        459      const {collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');460      const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);461  462      await expect(collection.methods.setTokenPropertyPermissions([463        ['testKey_0', [464          [EthTokenPermissions.Mutable, true], 465          [EthTokenPermissions.TokenOwner, true], 466          [EthTokenPermissions.CollectionAdmin, true]],467        ],468      ]).call({from: caller})).to.be.rejectedWith('NoPermission');  469    }));470471  [472    {mode: 'nft' as const, requiredPallets: []},473    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},474  ].map(testCase =>475    itEth.ifWithPallets(`[${testCase.mode}] Cant set token property permissions with invalid character`, testCase.requiredPallets, async({helper}) => {476      const owner = await helper.eth.createAccountWithBalance(donor);477        478      const {collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');479      const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);480  481      await expect(collection.methods.setTokenPropertyPermissions([482        // "Space" is invalid character483        ['testKey 0', [484          [EthTokenPermissions.Mutable, true], 485          [EthTokenPermissions.TokenOwner, true], 486          [EthTokenPermissions.CollectionAdmin, true]],487        ],488      ]).call({from: owner})).to.be.rejectedWith('InvalidCharacterInPropertyKey');  489    }));490  491});492493494type ElementOf<A> = A extends readonly (infer T)[] ? T : never;495function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {496  if(args.length === 0) {497    yield internalRest as any;498    return;499  }500  for(const value of args[0]) {501    yield* cartesian([...internalRest, value], ...args.slice(1)) as any;502  }503}
modifiedtests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth
--- a/tests/src/eth/util/playgrounds/types.ts
+++ b/tests/src/eth/util/playgrounds/types.ts
@@ -20,3 +20,8 @@
 
 export type EthProperty = string[];
 
+export enum EthTokenPermissions {
+  Mutable,
+  TokenOwner,
+  CollectionAdmin
+}
\ No newline at end of file