difftreelog
feat set/get tokenPropertyPermissions for NFT
in: master
5 files changed
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -34,7 +34,7 @@
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},
@@ -70,10 +70,10 @@
token_owner: bool,
) -> Result<()> {
let caller = T::CrossAccountId::from_eth(caller);
- <Pallet<T>>::set_property_permissions(
+ <Pallet<T>>::set_token_property_permissions(
self,
&caller,
- [PropertyKeyPermission {
+ vec![PropertyKeyPermission {
key: <Vec<u8>>::from(key)
.try_into()
.map_err(|_| "too long key")?,
@@ -82,8 +82,7 @@
collection_admin,
token_owner,
},
- }]
- .into(),
+ }],
)
.map_err(dispatch_to_evm::<T>)
}
@@ -137,7 +136,8 @@
});
}
- <Pallet<T>>::set_property_permissions(self, &caller, perms).map_err(dispatch_to_evm::<T>)
+ <Pallet<T>>::set_token_property_permissions(self, &caller, perms)
+ .map_err(dispatch_to_evm::<T>)
}
fn token_property_permissions(
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -824,17 +824,6 @@
)
}
- /// Set property permissions for the collection.
- ///
- /// Sender should be the owner or admin of the collection.
- pub fn set_property_permissions(
- collection: &CollectionHandle<T>,
- sender: &T::CrossAccountId,
- permission: Vec<PropertyKeyPermission>,
- ) -> DispatchResult {
- <PalletCommon<T>>::set_token_property_permissions(collection, sender, permission)
- }
-
pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {
<PalletCommon<T>>::property_permissions(collection_id)
}
pallets/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,76 @@
.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.
+ 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: <Vec<u8>>::from(key)
+ .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>)
+ }
+
+ fn token_property_permissions(
+ &self,
+ ) -> Result<Vec<(string, Vec<(EthTokenPermissions, bool)>)>> {
+ let mut res = <Vec<_>>::new();
+ for (key, pp) in <Pallet<T>>::token_property_permission(self.id) {
+ let key = string::from_utf8(key.into_inner()).unwrap();
+ let pp = [
+ (EthTokenPermissions::Mutable, pp.mutable),
+ (EthTokenPermissions::TokenOwner, pp.token_owner),
+ (EthTokenPermissions::CollectionAdmin, pp.collection_admin),
+ ]
+ .into();
+ res.push((key, pp));
+ }
+ Ok(res)
+ }
+
/// @notice Set token property value.
/// @dev Throws error if `msg.sender` has no permission to edit the property.
/// @param tokenId ID of the token.
pallets/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,
tests/src/eth/tokenProperties.test.tsdiffbeforeafterboth1// 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.only('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.setTokenPropertyPermissions([['testKey', [[0, mutable], [1, tokenOwner], [2, collectionAdmin]]]]).send({from: caller});45 46 expect(await collection.getPropertyPermissions()).to.be.deep.equal([{47 key: 'testKey',48 permission: {mutable, collectionAdmin, tokenOwner},49 }]);5051 expect(await contract.methods.tokenPropertyPermissions().call({from: caller})).to.be.like([52 ['testKey', [['0', mutable], ['1', tokenOwner], ['2', collectionAdmin]]]53 ]);54 }55 });5657 [58 {59 method: 'setProperties',60 methodParams: [[{key: 'testKey1', value: Buffer.from('testValue1')}, {key: 'testKey2', value: Buffer.from('testValue2')}]],61 expectedProps: [{key: 'testKey1', value: 'testValue1'}, {key: 'testKey2', value: 'testValue2'}],62 },63 {64 method: 'setProperty' /*Soft-deprecated*/, 65 methodParams: ['testKey1', Buffer.from('testValue1')],66 expectedProps: [{key: 'testKey1', value: 'testValue1'}],67 },68 ].map(testCase => 69 itEth(`[${testCase.method}] Can be set`, async({helper}) => {70 const caller = await helper.eth.createAccountWithBalance(donor);71 const collection = await helper.nft.mintCollection(alice, {72 tokenPropertyPermissions: [{73 key: 'testKey1',74 permission: {75 collectionAdmin: true,76 },77 }, {78 key: 'testKey2',79 permission: {80 collectionAdmin: true,81 },82 }],83 });8485 await collection.addAdmin(alice, {Ethereum: caller});86 const token = await collection.mintToken(alice);87 88 const collectionEvm = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller, testCase.method === 'setProperty');89 90 await collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller});91 92 const properties = await token.getProperties();93 expect(properties).to.deep.equal(testCase.expectedProps);94 }));95 96 [97 {mode: 'nft' as const, requiredPallets: []},98 {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},99 ].map(testCase => 100 itEth.ifWithPallets(`Can be multiple set/read for ${testCase.mode}`, testCase.requiredPallets, async({helper}) => {101 const caller = await helper.eth.createAccountWithBalance(donor);102 103 const properties = Array(5).fill(0).map((_, i) => { return {key: `key_${i}`, value: Buffer.from(`value_${i}`)}; });104 const permissions: ITokenPropertyPermission[] = properties.map(p => { return {key: p.key, permission: {tokenOwner: true,105 collectionAdmin: true,106 mutable: true}}; });107 108 const collection = await helper[testCase.mode].mintCollection(alice, {109 tokenPrefix: 'ethp',110 tokenPropertyPermissions: permissions,111 }) as UniqueNFTCollection | UniqueRFTCollection;112 113 const token = await collection.mintToken(alice);114 115 const valuesBefore = await token.getProperties(properties.map(p => p.key));116 expect(valuesBefore).to.be.deep.equal([]);117 118 119 await collection.addAdmin(alice, {Ethereum: caller});120 121 const address = helper.ethAddress.fromCollectionId(collection.collectionId);122 const contract = helper.ethNativeContract.collection(address, testCase.mode, caller);123 124 expect(await contract.methods.properties(token.tokenId, []).call()).to.be.deep.equal([]);125 126 await contract.methods.setProperties(token.tokenId, properties).send({from: caller});127 128 const values = await token.getProperties(properties.map(p => p.key));129 expect(values).to.be.deep.equal(properties.map(p => { return {key: p.key, value: p.value.toString()}; }));130 131 expect(await contract.methods.properties(token.tokenId, []).call()).to.be.like(properties132 .map(p => { return helper.ethProperty.property(p.key, p.value.toString()); }));133 134 expect(await contract.methods.properties(token.tokenId, [properties[0].key]).call())135 .to.be.like([helper.ethProperty.property(properties[0].key, properties[0].value.toString())]);136 }));137 138 [139 {mode: 'nft' as const, requiredPallets: []},140 {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},141 ].map(testCase => 142 itEth.ifWithPallets(`Can be deleted for ${testCase.mode}`, testCase.requiredPallets, async({helper}) => {143 const caller = await helper.eth.createAccountWithBalance(donor);144 const collection = await helper[testCase.mode].mintCollection(alice, {145 tokenPropertyPermissions: [{146 key: 'testKey',147 permission: {148 mutable: true,149 collectionAdmin: true,150 },151 },152 {153 key: 'testKey_1',154 permission: {155 mutable: true,156 collectionAdmin: true,157 },158 }],159 });160 161 const token = await collection.mintToken(alice);162 await token.setProperties(alice, [{key: 'testKey', value: 'testValue'}, {key: 'testKey_1', value: 'testValue_1'}]);163 expect(await token.getProperties()).to.has.length(2);164165 await collection.addAdmin(alice, {Ethereum: caller});166167 const address = helper.ethAddress.fromCollectionId(collection.collectionId);168 const contract = helper.ethNativeContract.collection(address, testCase.mode, caller);169170 await contract.methods.deleteProperties(token.tokenId, ['testKey', 'testKey_1']).send({from: caller});171172 const result = await token.getProperties(['testKey', 'testKey_1']);173 expect(result.length).to.equal(0);174 }));175176 itEth('Can be read', async({helper}) => {177 const caller = helper.eth.createAccount();178 const collection = await helper.nft.mintCollection(alice, {179 tokenPropertyPermissions: [{180 key: 'testKey',181 permission: {182 collectionAdmin: true,183 },184 }],185 });186 187 const token = await collection.mintToken(alice);188 await token.setProperties(alice, [{key: 'testKey', value: 'testValue'}]);189190 const address = helper.ethAddress.fromCollectionId(collection.collectionId);191 const contract = helper.ethNativeContract.collection(address, 'nft', caller);192193 const value = await contract.methods.property(token.tokenId, 'testKey').call();194 expect(value).to.equal(helper.getWeb3().utils.toHex('testValue'));195 });196});197198describe('EVM token properties negative', () => {199 let donor: IKeyringPair;200 let alice: IKeyringPair;201 let caller: string;202 let aliceCollection: UniqueNFTCollection;203 let token: UniqueNFToken;204 const tokenProps = [{key: 'testKey_1', value: 'testValue_1'}, {key: 'testKey_2', value: 'testValue_2'}];205 let collectionEvm: Contract;206207 before(async function() {208 await usingEthPlaygrounds(async (helper, privateKey) => {209 donor = await privateKey({filename: __filename});210 [alice] = await helper.arrange.createAccounts([100n], donor);211 });212 });213214 beforeEach(async () => {215 // 1. create collection with props: testKey_1, testKey_2216 // 2. create token and set props testKey_1, testKey_2217 await usingEthPlaygrounds(async (helper) => {218 aliceCollection = await helper.nft.mintCollection(alice, {219 tokenPropertyPermissions: [{220 key: 'testKey_1',221 permission: {222 mutable: true,223 collectionAdmin: true,224 },225 },226 {227 key: 'testKey_2',228 permission: {229 mutable: true,230 collectionAdmin: true,231 },232 }],233 }); 234 token = await aliceCollection.mintToken(alice);235 await token.setProperties(alice, tokenProps);236 collectionEvm = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, true);237 });238 });239240 [241 {method: 'setProperty', methodParams: [tokenProps[1].key, Buffer.from('newValue')]},242 {method: 'setProperties', methodParams: [[{key: tokenProps[1].key, value: Buffer.from('newValue')}]]},243 ].map(testCase =>244 itEth(`[${testCase.method}] Cannot set properties of non-owned collection`, async ({helper}) => {245 caller = await helper.eth.createAccountWithBalance(donor);246 collectionEvm = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, true);247 // Caller not an owner and not an admin, so he cannot set properties:248 await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');249 await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;250251 // Props have not changed:252 const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));253 const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();254 expect(actualProps).to.deep.eq(expectedProps);255 }));256257 [258 {method: 'setProperty', methodParams: ['testKey_3', Buffer.from('testValue3')]},259 {method: 'setProperties', methodParams: [[{key: 'testKey_3', value: Buffer.from('testValue3')}]]},260 ].map(testCase =>261 itEth(`[${testCase.method}] Cannot set non-existing properties`, async ({helper}) => {262 caller = await helper.eth.createAccountWithBalance(donor);263 collectionEvm = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, true);264 await helper.collection.addAdmin(alice, aliceCollection.collectionId, {Ethereum: caller});265266 await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');267 await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;268269 // Props have not changed:270 const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));271 const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();272 expect(actualProps).to.deep.eq(expectedProps);273 }));274275 [276 {method: 'deleteProperty', methodParams: ['testKey_2']},277 {method: 'deleteProperties', methodParams: [['testKey_2']]},278 ].map(testCase => 279 itEth(`[${testCase.method}] Cannot delete properties of non-owned collection`, async ({helper}) => {280 caller = await helper.eth.createAccountWithBalance(donor);281 collectionEvm = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, testCase.method == 'deleteProperty');282 // Caller not an owner and not an admin, so he cannot set properties:283 await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');284 await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;285286 // Props have not changed:287 const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));288 const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();289 expect(actualProps).to.deep.eq(expectedProps);290 }));291 292 [293 {method: 'deleteProperty', methodParams: ['testKey_3']},294 {method: 'deleteProperties', methodParams: [['testKey_3']]},295 ].map(testCase => 296 itEth(`[${testCase.method}] Cannot delete non-existing properties`, async ({helper}) => {297 caller = await helper.eth.createAccountWithBalance(donor);298 collectionEvm = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, testCase.method == 'deleteProperty');299 await helper.collection.addAdmin(alice, aliceCollection.collectionId, {Ethereum: caller});300 // Caller cannot delete non-existing properties:301 await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');302 await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;303 // Props have not changed:304 const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));305 const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();306 expect(actualProps).to.deep.eq(expectedProps);307 }));308});309310311type ElementOf<A> = A extends readonly (infer T)[] ? T : never;312function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {313 if(args.length === 0) {314 yield internalRest as any;315 return;316 }317 for(const value of args[0]) {318 yield* cartesian([...internalRest, value], ...args.slice(1)) as any;319 }320}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.setTokenPropertyPermissions([['testKey', [[0, mutable], [1, tokenOwner], [2, collectionAdmin]]]]).send({from: caller});45 46 expect(await collection.getPropertyPermissions()).to.be.deep.equal([{47 key: 'testKey',48 permission: {mutable, collectionAdmin, tokenOwner},49 }]);5051 expect(await contract.methods.tokenPropertyPermissions().call({from: caller})).to.be.like([52 ['testKey', [['0', mutable], ['1', tokenOwner], ['2', collectionAdmin]]]53 ]);54 }55 });5657 [58 {59 method: 'setProperties',60 methodParams: [[{key: 'testKey1', value: Buffer.from('testValue1')}, {key: 'testKey2', value: Buffer.from('testValue2')}]],61 expectedProps: [{key: 'testKey1', value: 'testValue1'}, {key: 'testKey2', value: 'testValue2'}],62 },63 {64 method: 'setProperty' /*Soft-deprecated*/, 65 methodParams: ['testKey1', Buffer.from('testValue1')],66 expectedProps: [{key: 'testKey1', value: 'testValue1'}],67 },68 ].map(testCase => 69 itEth(`[${testCase.method}] Can be set`, async({helper}) => {70 const caller = await helper.eth.createAccountWithBalance(donor);71 const collection = await helper.nft.mintCollection(alice, {72 tokenPropertyPermissions: [{73 key: 'testKey1',74 permission: {75 collectionAdmin: true,76 },77 }, {78 key: 'testKey2',79 permission: {80 collectionAdmin: true,81 },82 }],83 });8485 await collection.addAdmin(alice, {Ethereum: caller});86 const token = await collection.mintToken(alice);87 88 const collectionEvm = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller, testCase.method === 'setProperty');89 90 await collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller});91 92 const properties = await token.getProperties();93 expect(properties).to.deep.equal(testCase.expectedProps);94 }));95 96 [97 {mode: 'nft' as const, requiredPallets: []},98 {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},99 ].map(testCase => 100 itEth.ifWithPallets(`Can be multiple set/read for ${testCase.mode}`, testCase.requiredPallets, async({helper}) => {101 const caller = await helper.eth.createAccountWithBalance(donor);102 103 const properties = Array(5).fill(0).map((_, i) => { return {key: `key_${i}`, value: Buffer.from(`value_${i}`)}; });104 const permissions: ITokenPropertyPermission[] = properties.map(p => { return {key: p.key, permission: {tokenOwner: true,105 collectionAdmin: true,106 mutable: true}}; });107 108 const collection = await helper[testCase.mode].mintCollection(alice, {109 tokenPrefix: 'ethp',110 tokenPropertyPermissions: permissions,111 }) as UniqueNFTCollection | UniqueRFTCollection;112 113 const token = await collection.mintToken(alice);114 115 const valuesBefore = await token.getProperties(properties.map(p => p.key));116 expect(valuesBefore).to.be.deep.equal([]);117 118 119 await collection.addAdmin(alice, {Ethereum: caller});120 121 const address = helper.ethAddress.fromCollectionId(collection.collectionId);122 const contract = helper.ethNativeContract.collection(address, testCase.mode, caller);123 124 expect(await contract.methods.properties(token.tokenId, []).call()).to.be.deep.equal([]);125 126 await contract.methods.setProperties(token.tokenId, properties).send({from: caller});127 128 const values = await token.getProperties(properties.map(p => p.key));129 expect(values).to.be.deep.equal(properties.map(p => { return {key: p.key, value: p.value.toString()}; }));130 131 expect(await contract.methods.properties(token.tokenId, []).call()).to.be.like(properties132 .map(p => { return helper.ethProperty.property(p.key, p.value.toString()); }));133 134 expect(await contract.methods.properties(token.tokenId, [properties[0].key]).call())135 .to.be.like([helper.ethProperty.property(properties[0].key, properties[0].value.toString())]);136 }));137 138 [139 {mode: 'nft' as const, requiredPallets: []},140 {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},141 ].map(testCase => 142 itEth.ifWithPallets(`Can be deleted for ${testCase.mode}`, testCase.requiredPallets, async({helper}) => {143 const caller = await helper.eth.createAccountWithBalance(donor);144 const collection = await helper[testCase.mode].mintCollection(alice, {145 tokenPropertyPermissions: [{146 key: 'testKey',147 permission: {148 mutable: true,149 collectionAdmin: true,150 },151 },152 {153 key: 'testKey_1',154 permission: {155 mutable: true,156 collectionAdmin: true,157 },158 }],159 });160 161 const token = await collection.mintToken(alice);162 await token.setProperties(alice, [{key: 'testKey', value: 'testValue'}, {key: 'testKey_1', value: 'testValue_1'}]);163 expect(await token.getProperties()).to.has.length(2);164165 await collection.addAdmin(alice, {Ethereum: caller});166167 const address = helper.ethAddress.fromCollectionId(collection.collectionId);168 const contract = helper.ethNativeContract.collection(address, testCase.mode, caller);169170 await contract.methods.deleteProperties(token.tokenId, ['testKey', 'testKey_1']).send({from: caller});171172 const result = await token.getProperties(['testKey', 'testKey_1']);173 expect(result.length).to.equal(0);174 }));175176 itEth('Can be read', async({helper}) => {177 const caller = helper.eth.createAccount();178 const collection = await helper.nft.mintCollection(alice, {179 tokenPropertyPermissions: [{180 key: 'testKey',181 permission: {182 collectionAdmin: true,183 },184 }],185 });186 187 const token = await collection.mintToken(alice);188 await token.setProperties(alice, [{key: 'testKey', value: 'testValue'}]);189190 const address = helper.ethAddress.fromCollectionId(collection.collectionId);191 const contract = helper.ethNativeContract.collection(address, 'nft', caller);192193 const value = await contract.methods.property(token.tokenId, 'testKey').call();194 expect(value).to.equal(helper.getWeb3().utils.toHex('testValue'));195 });196});197198describe('EVM token properties negative', () => {199 let donor: IKeyringPair;200 let alice: IKeyringPair;201 let caller: string;202 let aliceCollection: UniqueNFTCollection;203 let token: UniqueNFToken;204 const tokenProps = [{key: 'testKey_1', value: 'testValue_1'}, {key: 'testKey_2', value: 'testValue_2'}];205 let collectionEvm: Contract;206207 before(async function() {208 await usingEthPlaygrounds(async (helper, privateKey) => {209 donor = await privateKey({filename: __filename});210 [alice] = await helper.arrange.createAccounts([100n], donor);211 });212 });213214 beforeEach(async () => {215 // 1. create collection with props: testKey_1, testKey_2216 // 2. create token and set props testKey_1, testKey_2217 await usingEthPlaygrounds(async (helper) => {218 aliceCollection = await helper.nft.mintCollection(alice, {219 tokenPropertyPermissions: [{220 key: 'testKey_1',221 permission: {222 mutable: true,223 collectionAdmin: true,224 },225 },226 {227 key: 'testKey_2',228 permission: {229 mutable: true,230 collectionAdmin: true,231 },232 }],233 }); 234 token = await aliceCollection.mintToken(alice);235 await token.setProperties(alice, tokenProps);236 collectionEvm = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, true);237 });238 });239240 [241 {method: 'setProperty', methodParams: [tokenProps[1].key, Buffer.from('newValue')]},242 {method: 'setProperties', methodParams: [[{key: tokenProps[1].key, value: Buffer.from('newValue')}]]},243 ].map(testCase =>244 itEth(`[${testCase.method}] Cannot set properties of non-owned collection`, async ({helper}) => {245 caller = await helper.eth.createAccountWithBalance(donor);246 collectionEvm = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, true);247 // Caller not an owner and not an admin, so he cannot set properties:248 await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');249 await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;250251 // Props have not changed:252 const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));253 const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();254 expect(actualProps).to.deep.eq(expectedProps);255 }));256257 [258 {method: 'setProperty', methodParams: ['testKey_3', Buffer.from('testValue3')]},259 {method: 'setProperties', methodParams: [[{key: 'testKey_3', value: Buffer.from('testValue3')}]]},260 ].map(testCase =>261 itEth(`[${testCase.method}] Cannot set non-existing properties`, async ({helper}) => {262 caller = await helper.eth.createAccountWithBalance(donor);263 collectionEvm = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, true);264 await helper.collection.addAdmin(alice, aliceCollection.collectionId, {Ethereum: caller});265266 await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');267 await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;268269 // Props have not changed:270 const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));271 const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();272 expect(actualProps).to.deep.eq(expectedProps);273 }));274275 [276 {method: 'deleteProperty', methodParams: ['testKey_2']},277 {method: 'deleteProperties', methodParams: [['testKey_2']]},278 ].map(testCase => 279 itEth(`[${testCase.method}] Cannot delete properties of non-owned collection`, async ({helper}) => {280 caller = await helper.eth.createAccountWithBalance(donor);281 collectionEvm = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, testCase.method == 'deleteProperty');282 // Caller not an owner and not an admin, so he cannot set properties:283 await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');284 await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;285286 // Props have not changed:287 const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));288 const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();289 expect(actualProps).to.deep.eq(expectedProps);290 }));291 292 [293 {method: 'deleteProperty', methodParams: ['testKey_3']},294 {method: 'deleteProperties', methodParams: [['testKey_3']]},295 ].map(testCase => 296 itEth(`[${testCase.method}] Cannot delete non-existing properties`, async ({helper}) => {297 caller = await helper.eth.createAccountWithBalance(donor);298 collectionEvm = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, testCase.method == 'deleteProperty');299 await helper.collection.addAdmin(alice, aliceCollection.collectionId, {Ethereum: caller});300 // Caller cannot delete non-existing properties:301 await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');302 await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;303 // Props have not changed:304 const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));305 const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();306 expect(actualProps).to.deep.eq(expectedProps);307 }));308});309310311type ElementOf<A> = A extends readonly (infer T)[] ? T : never;312function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {313 if(args.length === 0) {314 yield internalRest as any;315 return;316 }317 for(const value of args[0]) {318 yield* cartesian([...internalRest, value], ...args.slice(1)) as any;319 }320}