git.delta.rocks / unique-network / refs/commits / 1913bf6018fe

difftreelog

Merge pull request #954 from UniqueNetwork/feature/update_market_v2_contract

Yaroslav Bolyukin2023-06-29parents: #ef738f7 #54a7967.patch.diff
in: master

4 files changed

modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -47,6 +47,7 @@
     "testEthNesting": "yarn _test './**/eth/nesting/**/*.*test.ts'",
     "testEthFractionalizer": "yarn _test './**/eth/fractionalizer/**/*.*test.ts'",
     "testEthMarketplace": "yarn _test './**/eth/marketplace/**/*.*test.ts'",
+    "testEthMarket": "yarn _test './**/eth/marketplace-v2/**/*.*test.ts'",
     "testSub": "yarn _test './**/sub/**/*.*test.ts'",
     "testSubNesting": "yarn _test './**/sub/nesting/**/*.*test.ts'",
     "testEvent": "yarn _test ./src/check-event/*.*test.ts",
modifiedtests/src/eth/marketplace-v2/Market.soldiffbeforeafterboth
--- a/tests/src/eth/marketplace-v2/Market.sol
+++ b/tests/src/eth/marketplace-v2/Market.sol
@@ -1,13 +1,16 @@
 // SPDX-License-Identifier: UNLICENSED
 pragma solidity 0.8.17;
 
+import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
 import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
 import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
+import "@openzeppelin/contracts/access/Ownable.sol";
 import { UniqueNFT, CrossAddress } from "@unique-nft/solidity-interfaces/contracts/UniqueNFT.sol";
+import { UniqueFungible, CrossAddress as CrossAddressF } from "@unique-nft/solidity-interfaces/contracts/UniqueFungible.sol";
 import "@unique-nft/solidity-interfaces/contracts/CollectionHelpers.sol";
 import "./royalty/UniqueRoyaltyHelper.sol";
 
-contract Market {
+contract Market is Ownable, ReentrancyGuard {
     using ERC165Checker for address;
 
     struct Order {
@@ -20,6 +23,7 @@
     }
 
     uint32 public constant version = 0;
+    uint32 public constant buildVersion = 3;
     bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;
     bytes4 private constant InterfaceId_ERC165 = 0x5755c3f2;
     CollectionHelpers private constant collectionHelpers =
@@ -29,7 +33,6 @@
     uint32 private idCount = 1;
     uint32 public marketFee;
     uint64 public ctime;
-    address selfAddress;
     address public ownerAddress;
     mapping(address => bool) public admins;
 
@@ -55,15 +58,11 @@
     error OrderNotFound();
     error TooManyAmountRequested();
     error NotEnoughMoneyError();
+    error InvalidRoyaltiesError(uint256 totalRoyalty);
     error FailTransferToken(string reason);
-
-    modifier onlyOwner() {
-      require(msg.sender == ownerAddress, "Only owner can");
-      _;
-    }
 
     modifier onlyAdmin() {
-      require(msg.sender == ownerAddress || admins[msg.sender], "Only admin can");
+      require(msg.sender == this.owner() || admins[msg.sender], "Only admin can");
       _;
     }
 
@@ -83,13 +82,22 @@
         marketFee = fee;
         ctime = timestamp;
 
-        if (marketFee == 0 || marketFee >= 100) {
+        if (marketFee >= 100) {
             revert InvalidMarketFee();
         }
+    }
+
+    /**
+     * Fallback that allows this contract to receive native token.
+     * We need this for self-sponsoring
+     */
+    fallback() external payable {}
 
-        ownerAddress = msg.sender;
-        selfAddress = address(this);
-    }
+    /**
+     * Receive also allows this contract to receive native token.
+     * We need this for self-sponsoring
+     */
+    receive() external payable {}
 
     function getErc721(uint32 collectionId) private view returns (IERC721) {
         address collectionAddress = collectionHelpers.collectionAddress(
@@ -110,36 +118,35 @@
         }
 
         return IERC721(collectionAddress);
-    }
-
-    // ################################################################
-    // Set new contract owner                                         #
-    // ################################################################
-
-    function setOwner() public onlyOwner {
-        ownerAddress = msg.sender;
     }
-
-    // ################################################################
-    // Add new admin                                                  #
-    // ################################################################
 
+    /**
+     * Add new admin. Only owner or an existing admin can add admins.
+     *
+     * @param admin: Address of a new admin to add
+     */
     function addAdmin(address admin) public onlyAdmin {
       admins[admin] = true;
     }
 
-    // ################################################################
-    // Remove admin                                                  #
-    // ################################################################
-
+    /**
+     * Remove an admin. Only owner or an existing admin can remove admins.
+     *
+     * @param admin: Address of a new admin to add
+     */
     function removeAdmin(address admin) public onlyAdmin {
       delete admins[admin];
     }
 
-    // ################################################################
-    // Place a token for sale                                         #
-    // ################################################################
-
+    /**
+     * Place an NFT or RFT token for sale. It must be pre-approved for transfers by this contract address.
+     *
+     * @param collectionId: ID of the token collection
+     * @param tokenId: ID of the token
+     * @param price: Price (with proper network currency decimals)
+     * @param amount: Number of token fractions to list (must always be 1 for NFT)
+     * @param seller: The seller cross-address (the beneficiary account to receive payment, may be different from transaction sender)
+     */
     function put(
         uint32 collectionId,
         uint32 tokenId,
@@ -164,7 +171,7 @@
           revert SellerIsNotOwner();
         }
 
-        if (erc721.getApproved(tokenId) != selfAddress) {
+        if (erc721.getApproved(tokenId) != address(this)) {
           revert TokenIsNotApproved();
         }
 
@@ -182,11 +189,14 @@
 
         emit TokenIsUpForSale(version, order);
     }
-
-    // ################################################################
-    // Get order                                                      #
-    // ################################################################
 
+    /**
+     * Get information about the listed token order
+     *
+     * @param collectionId: ID of the token collection
+     * @param tokenId: ID of the token
+     * @return The order information
+     */
     function getOrder(
         uint32 collectionId,
         uint32 tokenId
@@ -194,10 +204,13 @@
         return orders[collectionId][tokenId];
     }
 
-    // ################################################################
-    // Revoke the token from the sale                                 #
-    // ################################################################
-
+    /**
+     * Revoke the token from the sale. Only the original lister can use this method.
+     *
+     * @param collectionId: ID of the token collection
+     * @param tokenId: ID of the token
+     * @param amount: Number of token fractions to de-list (must always be 1 for NFT)
+     */
     function revoke(
         uint32 collectionId,
         uint32 tokenId,
@@ -239,10 +252,12 @@
         emit TokenRevoke(version, order, amount);
     }
 
-    // ################################################################
-    // Check approved                                                 #
-    // ################################################################
-
+    /**
+     * Test if the token is still approved to be transferred by this contract and delete the order if not.
+     *
+     * @param collectionId: ID of the token collection
+     * @param tokenId: ID of the token
+     */
     function checkApproved(uint32 collectionId, uint32 tokenId) public onlyAdmin {
         Order memory order = orders[collectionId][tokenId];
         if (order.price == 0) {
@@ -251,7 +266,7 @@
 
         IERC721 erc721 = getErc721(collectionId);
 
-        if (erc721.getApproved(tokenId) != selfAddress) {
+        if (erc721.getApproved(tokenId) != address(this) || erc721.ownerOf(tokenId) != getAddressFromCrossAccount(order.seller)) {
           uint32 amount = order.amount;
           order.amount = 0;
           emit TokenRevoke(version, order, amount);
@@ -262,16 +277,47 @@
         }
     }
 
-    // ################################################################
-    // Buy a token                                                    #
-    // ################################################################
+    function getAddressFromCrossAccount(CrossAddress memory account) private pure returns (address) {
+        if (account.eth != address(0)) {
+            return account.eth;
+        } else {
+            return address(uint160(account.sub >> 96));
+        }
+    }
+
+    /**
+     * Revoke the token from the sale. Only the contract admin can use this method.
+     *
+     * @param collectionId: ID of the token collection
+     * @param tokenId: ID of the token
+     */
+    function revokeAdmin(uint32 collectionId, uint32 tokenId) public onlyAdmin {
+        Order memory order = orders[collectionId][tokenId];
+        if (order.price == 0) {
+          revert OrderNotFound();
+        }
 
+        uint32 amount = order.amount;
+        order.amount = 0;
+        emit TokenRevoke(version, order, amount);
+
+        delete orders[collectionId][tokenId];
+    }
+
+    /**
+     * Buy a token (partially for an RFT).
+     *
+     * @param collectionId: ID of the token collection
+     * @param tokenId: ID of the token
+     * @param amount: Number of token fractions to buy (must always be 1 for NFT)
+     * @param buyer: Cross-address of the buyer, eth part must be equal to the transaction signer address
+     */
     function buy(
         uint32 collectionId,
         uint32 tokenId,
         uint32 amount,
         CrossAddress memory buyer
-    ) public payable validCrossAddress(buyer.eth, buyer.sub) {
+    ) public payable validCrossAddress(buyer.eth, buyer.sub) nonReentrant {
         if (msg.value == 0) {
           revert InvalidArgument("msg.value must not be zero");
         }
@@ -296,7 +342,7 @@
         }
 
         IERC721 erc721 = getErc721(order.collectionId);
-        if (erc721.getApproved(tokenId) != selfAddress) {
+        if (erc721.getApproved(tokenId) != address(this)) {
           revert TokenIsNotApproved();
         }
 
@@ -316,26 +362,30 @@
           order.tokenId
         );
 
-        (uint256 totalRoyalty, RoyaltyAmount[] memory royalties) = sendRoyalties(collectionAddress, tokenId, totalValue);
+        (uint256 totalRoyalty, RoyaltyAmount[] memory royalties) = sendRoyalties(collectionAddress, tokenId, totalValue - feeValue);
 
+        if (totalRoyalty >= totalValue - feeValue) {
+          revert InvalidRoyaltiesError(totalRoyalty);
+        }
+
         sendMoney(order.seller, totalValue - feeValue - totalRoyalty);
 
         if (msg.value > totalValue) {
-            // todo, send money to signer or buyer ?
-            payable(msg.sender).transfer(msg.value - totalValue);
+            sendMoney(buyer, msg.value - totalValue);
         }
 
         emit TokenIsPurchased(version, order, amount, buyer, royalties);
     }
 
     function sendMoney(CrossAddress memory to, uint256 money) private {
-      address payable eth;
-      if (to.eth != address(0)) {
-        eth = payable(to.eth);
-      } else {
-        eth = payable(address(uint160(to.sub >> 96)));
-      }
-      eth.transfer(money);
+      address collectionAddress = collectionHelpers.collectionAddress(0);
+
+      UniqueFungible fungible = UniqueFungible(collectionAddress);
+
+      CrossAddressF memory fromF = CrossAddressF(address(this), 0);
+      CrossAddressF memory toF = CrossAddressF(to.eth, to.sub);
+
+      fungible.transferFromCross(fromF, toF, money);
     }
 
     function sendRoyalties(address collection, uint tokenId, uint sellPrice) private returns (uint256, RoyaltyAmount[] memory) {
@@ -355,7 +405,7 @@
     }
 
     function withdraw(address transferTo) public onlyOwner {
-        uint256 balance = selfAddress.balance;
+        uint256 balance = address(this).balance;
 
         if (balance > 0) {
             payable(transferTo).transfer(balance);
modifiedtests/src/eth/marketplace-v2/marketplace.test.tsdiffbeforeafterboth
--- a/tests/src/eth/marketplace-v2/marketplace.test.ts
+++ b/tests/src/eth/marketplace-v2/marketplace.test.ts
@@ -16,13 +16,15 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import {readFile} from 'fs/promises';
-import {EthUniqueHelper, itEth, usingEthPlaygrounds} from '../util';
+import {EthUniqueHelper, SponsoringMode, itEth, usingEthPlaygrounds} from '../util';
 import {makeNames} from '../../util';
 import {expect} from 'chai';
 import Web3 from 'web3';
 
 const {dirname} = makeNames(import.meta.url);
 
+const MARKET_FEE = 1;
+
 describe('Market V2 Contract', () => {
   let donor: IKeyringPair;
 
@@ -43,10 +45,26 @@
           fsPath: `${dirname}/../api/UniqueNFT.sol`,
         },
         {
+          solPath: '@unique-nft/solidity-interfaces/contracts/UniqueFungible.sol',
+          fsPath: `${dirname}/../api/UniqueFungible.sol`,
+        },
+        {
           solPath: '@openzeppelin/contracts/utils/introspection/IERC165.sol',
           fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol`,
         },
         {
+          solPath: '@openzeppelin/contracts/access/Ownable.sol',
+          fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/access/Ownable.sol`,
+        },
+        {
+          solPath: '@openzeppelin/contracts/utils/Context.sol',
+          fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/utils/Context.sol`,
+        },
+        {
+          solPath: '@openzeppelin/contracts/security/ReentrancyGuard.sol',
+          fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/security/ReentrancyGuard.sol`,
+        },
+        {
           solPath: '@openzeppelin/contracts/utils/introspection/ERC165Checker.sol',
           fsPath: `${dirname}/../../../node_modules/@openzeppelin/contracts/utils/introspection/ERC165Checker.sol`,
         },
@@ -72,7 +90,7 @@
         },
       ],
       15000000,
-      [1, 0],
+      [MARKET_FEE, 0],
     );
   }
 
@@ -90,63 +108,135 @@
   });
 
   itEth('Put + Buy [eth]', async ({helper}) => {
-    const marketOwner = await helper.eth.createAccountWithBalance(donor, 600n);
+    const ONE_TOKEN = helper.balance.getOneTokenNominal();
+    const PRICE = 2n * ONE_TOKEN;  // 2 UNQ
+    const marketOwner = await helper.eth.createAccountWithBalance(donor, 60000n);
     const market = await deployMarket(helper, marketOwner);
+    const contractHelpers = helper.ethNativeContract.contractHelpers(marketOwner);
+
+    // Set external sponsoring
+    await contractHelpers.methods.setSponsor(market.options.address, marketOwner).send({from: marketOwner});
+    await contractHelpers.methods.confirmSponsorship(market.options.address).send({from: marketOwner});
 
+    // Configure sponsoring
+    await contractHelpers.methods.setSponsoringMode(market.options.address, SponsoringMode.Generous).send({from: marketOwner});
+    await contractHelpers.methods.setSponsoringRateLimit(market.options.address, 0).send({from: marketOwner});
+
     const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(marketOwner, 'Sponsor', 'absolutely anything', 'ROC');
-    const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', marketOwner);
+    const collection = helper.ethNativeContract.collection(collectionAddress, 'nft', marketOwner, true);
+
+    // Set collection sponsoring
+    await collection.methods.setCollectionSponsor(marketOwner).send({from: marketOwner});
+    await collection.methods.confirmCollectionSponsorship().send({from: marketOwner});
 
-    const sellerCross = await helper.ethCrossAccount.createAccountWithBalance(donor, 600n);
+    const sellerCross = helper.ethCrossAccount.createAccount();
     const result = await collection.methods.mintCross(sellerCross, []).send();
     const tokenId = result.events.Transfer.returnValues.tokenId;
     await collection.methods.approve(market.options.address, tokenId).send({from: sellerCross.eth});
 
-    const putResult = await market.methods.put(collectionId, tokenId, 1, 1, sellerCross).send({from: sellerCross.eth});
+    // Seller has no funds at all, his transactions are sponsored
+    const sellerBalance = await helper.balance.getEthereum(sellerCross.eth);
+    expect(sellerBalance).to.be.eq(0n);
+
+    const putResult = await market.methods.put(collectionId, tokenId, PRICE.toString(), 1, sellerCross).send({
+      from: sellerCross.eth, gasLimit: 1_000_000,
+    });
     expect(putResult.events.TokenIsUpForSale).is.not.undefined;
+
+    // Seller balance are still 0
+    const sellerBalanceAfter = await helper.balance.getEthereum(sellerCross.eth);
+    expect(sellerBalanceAfter).to.be.eq(0n);
+
     let ownerCross = await collection.methods.ownerOfCross(tokenId).call();
     expect(ownerCross.eth).to.be.eq(sellerCross.eth);
     expect(ownerCross.sub).to.be.eq(sellerCross.sub);
 
-    const buyerCross = await helper.ethCrossAccount.createAccountWithBalance(donor, 600n);
-    const buyResult = await market.methods.buy(collectionId, tokenId, 1, buyerCross).send({from: buyerCross.eth, value: 1});
+    const buyerCross = await helper.ethCrossAccount.createAccountWithBalance(donor, 10n);
+
+    // Buyer has only 10 UNQ
+    const buyerBalance = await helper.balance.getEthereum(buyerCross.eth);
+    expect(buyerBalance).to.be.eq(10n * ONE_TOKEN);
+
+    const buyResult = await market.methods.buy(collectionId, tokenId, 1, buyerCross).send({from: buyerCross.eth, value: PRICE.toString(), gasLimit: 1_000_000});
     expect(buyResult.events.TokenIsPurchased).is.not.undefined;
+
+    // Buyer pays only value, transaction use sponsoring
+    const buyerBalanceAfter = await helper.balance.getEthereum(buyerCross.eth);
+    expect(buyerBalanceAfter).to.be.eq(10n * ONE_TOKEN - PRICE);
+
     ownerCross = await collection.methods.ownerOfCross(tokenId).call();
     expect(ownerCross.eth).to.be.eq(buyerCross.eth);
     expect(ownerCross.sub).to.be.eq(buyerCross.sub);
   });
 
   itEth('Put + Buy [sub]', async ({helper}) => {
-    const PRICE = 1n;
+    const ONE_TOKEN = helper.balance.getOneTokenNominal();
+    const PRICE = 2n * ONE_TOKEN;  // 2 UNQ
     const web3 = helper.getWeb3();
     const marketOwner = await helper.eth.createAccountWithBalance(donor, 600n);
     const market = await deployMarket(helper, marketOwner);
+    const contractHelpers = helper.ethNativeContract.contractHelpers(marketOwner);
+
+    // Set self sponsoring from contract balance
+    await contractHelpers.methods.selfSponsoredEnable(market.options.address).send({from: marketOwner});
+    await helper.eth.transferBalanceFromSubstrate(donor, market.options.address, 10n);
+
+    // Configure sponsoring
+    await contractHelpers.methods.setSponsoringMode(market.options.address, SponsoringMode.Generous).send({from: marketOwner});
+    await contractHelpers.methods.setSponsoringRateLimit(market.options.address, 0).send({from: marketOwner});
 
     const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(marketOwner, 'Sponsor', 'absolutely anything', 'ROC');
-    const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', marketOwner);
+    const collection = helper.ethNativeContract.collection(collectionAddress, 'nft', marketOwner, true);
+
+    // Set collection sponsoring
+    await collection.methods.setCollectionSponsor(marketOwner).send({from: marketOwner});
+    await collection.methods.confirmCollectionSponsorship().send({from: marketOwner});
 
-    const [seller] = await helper.arrange.createAccounts([600n], donor);
-    const sellerMirror = helper.address.substrateToEth(seller.address);
+    const seller = helper.util.fromSeed(`//Market-seller-${(new Date()).getTime()}`);
     const sellerCross = helper.ethCrossAccount.fromKeyringPair(seller);
+
+    // Seller has no funds at all, his transactions are sponsored
+    {
+      const sellerBalance = await helper.balance.getSubstrate(seller.address);
+      expect(sellerBalance).to.be.eq(0n);
+    }
+
     const result = await collection.methods.mintCross(sellerCross, []).send();
     const tokenId = result.events.Transfer.returnValues.tokenId;
-    await helper.nft.approveToken(seller, collectionId, tokenId, {Ethereum: market.options.address}, 1n);
+    await helper.nft.approveToken(seller, collectionId, tokenId, {Ethereum: market.options.address});
 
     await helper.eth.sendEVM(seller, market.options.address, market.methods.put(collectionId, tokenId, PRICE, 1, sellerCross).encodeABI(), '0');
+    // Seller balance is still zero
+    {
+      const sellerBalance = await helper.balance.getSubstrate(seller.address);
+      expect(sellerBalance).to.be.eq(0n);
+    }
     let ownerCross = await collection.methods.ownerOfCross(tokenId).call();
     expect(ownerCross.eth).to.be.eq(sellerCross.eth);
     expect(substrateAddressToHex(ownerCross.sub, web3)).to.be.eq(substrateAddressToHex(sellerCross.sub, web3));
 
     const [buyer] = await helper.arrange.createAccounts([600n], donor);
+    // Buyer has only expected balance
+    {
+      const buyerBalance = await helper.balance.getSubstrate(buyer.address);
+      expect(buyerBalance).to.be.eq(600n * ONE_TOKEN);
+    }
     const buyerMirror = helper.address.substrateToEth(buyer.address);
     const buyerCross = helper.ethCrossAccount.fromKeyringPair(buyer);
-    await helper.eth.transferBalanceFromSubstrate(donor, buyerMirror, 1n);
-    //TODO: change balance check to helper.balance.getSubstrate when implementation of sendMoney will be fixed in contract
-    const sellerBalance = BigInt(await web3.eth.getBalance(sellerMirror));
+    await helper.eth.transferBalanceFromSubstrate(donor, buyerMirror, PRICE, false);
+
+    const buyerBalanceBefore = await helper.balance.getSubstrate(buyer.address);
     await helper.eth.sendEVM(buyer, market.options.address, market.methods.buy(collectionId, tokenId, 1, buyerCross).encodeABI(), PRICE.toString());
-    const sellerBalanceAfterBuy = BigInt(await web3.eth.getBalance(sellerMirror));
+    const buyerBalanceAfter = await helper.balance.getSubstrate(buyer.address);
+    // Buyer balance not changed: transaction is sponsored
+    expect(buyerBalanceBefore).to.be.eq(buyerBalanceAfter);
+
+    const sellerBalanceAfterBuy = BigInt(await helper.balance.getSubstrate(seller.address));
     ownerCross = await collection.methods.ownerOfCross(tokenId).call();
     expect(ownerCross.eth).to.be.eq(buyerCross.eth);
     expect(substrateAddressToHex(ownerCross.sub, web3)).to.be.eq(substrateAddressToHex(buyerCross.sub, web3));
-    expect(sellerBalance + PRICE).to.be.equal(sellerBalanceAfterBuy);
+
+    // Seller got only PRICE - MARKET_FEE
+    expect(sellerBalanceAfterBuy).to.be.eq(PRICE * BigInt(100 - MARKET_FEE) / 100n);
   });
 });
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';23import {TokenPermissionField} 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({url: import.meta.url});32      [alice] = await helper.arrange.createAccounts([1000n], 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}] Can set all possible 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            [TokenPermissionField.Mutable, mutable],51            [TokenPermissionField.TokenOwner, tokenOwner],52            [TokenPermissionField.CollectionAdmin, collectionAdmin]],53          ],54        ]).send({from: caller.eth});5556        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            [TokenPermissionField.Mutable.toString(), mutable],64            [TokenPermissionField.TokenOwner.toString(), tokenOwner],65            [TokenPermissionField.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}] Can set multiple token property permissions as owner`, testCase.requiredPallets, async({helper}) => {76      const owner = await helper.eth.createAccountWithBalance(donor);7778      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          [TokenPermissionField.Mutable, true],84          [TokenPermissionField.TokenOwner, true],85          [TokenPermissionField.CollectionAdmin, true]],86        ],87        ['testKey_1', [88          [TokenPermissionField.Mutable, true],89          [TokenPermissionField.TokenOwner, false],90          [TokenPermissionField.CollectionAdmin, true]],91        ],92        ['testKey_2', [93          [TokenPermissionField.Mutable, false],94          [TokenPermissionField.TokenOwner, true],95          [TokenPermissionField.CollectionAdmin, false]],96        ],97      ]).send({from: owner});9899      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          [TokenPermissionField.Mutable.toString(), true],117          [TokenPermissionField.TokenOwner.toString(), true],118          [TokenPermissionField.CollectionAdmin.toString(), true]],119        ],120        ['testKey_1', [121          [TokenPermissionField.Mutable.toString(), true],122          [TokenPermissionField.TokenOwner.toString(), false],123          [TokenPermissionField.CollectionAdmin.toString(), true]],124        ],125        ['testKey_2', [126          [TokenPermissionField.Mutable.toString(), false],127          [TokenPermissionField.TokenOwner.toString(), true],128          [TokenPermissionField.CollectionAdmin.toString(), false]],129        ],130      ]);131    }));132133  [134    {mode: 'nft' as const, requiredPallets: []},135    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},136  ].map(testCase =>137    itEth.ifWithPallets(`[${testCase.mode}] Can set multiple token property permissions as admin`, testCase.requiredPallets, async({helper}) => {138      const owner = await helper.eth.createAccountWithBalance(donor);139      const caller = await helper.ethCrossAccount.createAccountWithBalance(donor);140141      const {collectionId, collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');142      const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);143      await collection.methods.addCollectionAdminCross(caller).send({from: owner});144145      await collection.methods.setTokenPropertyPermissions([146        ['testKey_0', [147          [TokenPermissionField.Mutable, true],148          [TokenPermissionField.TokenOwner, true],149          [TokenPermissionField.CollectionAdmin, true]],150        ],151        ['testKey_1', [152          [TokenPermissionField.Mutable, true],153          [TokenPermissionField.TokenOwner, false],154          [TokenPermissionField.CollectionAdmin, true]],155        ],156        ['testKey_2', [157          [TokenPermissionField.Mutable, false],158          [TokenPermissionField.TokenOwner, true],159          [TokenPermissionField.CollectionAdmin, false]],160        ],161      ]).send({from: caller.eth});162163      expect(await helper[testCase.mode].getPropertyPermissions(collectionId)).to.be.deep.equal([164        {165          key: 'testKey_0',166          permission: {mutable: true, tokenOwner: true, collectionAdmin: true},167        },168        {169          key: 'testKey_1',170          permission: {mutable: true, tokenOwner: false, collectionAdmin: true},171        },172        {173          key: 'testKey_2',174          permission: {mutable: false, tokenOwner: true, collectionAdmin: false},175        },176      ]);177178      expect(await collection.methods.tokenPropertyPermissions().call({from: caller.eth})).to.be.like([179        ['testKey_0', [180          [TokenPermissionField.Mutable.toString(), true],181          [TokenPermissionField.TokenOwner.toString(), true],182          [TokenPermissionField.CollectionAdmin.toString(), true]],183        ],184        ['testKey_1', [185          [TokenPermissionField.Mutable.toString(), true],186          [TokenPermissionField.TokenOwner.toString(), false],187          [TokenPermissionField.CollectionAdmin.toString(), true]],188        ],189        ['testKey_2', [190          [TokenPermissionField.Mutable.toString(), false],191          [TokenPermissionField.TokenOwner.toString(), true],192          [TokenPermissionField.CollectionAdmin.toString(), false]],193        ],194      ]);195196    }));197198  [199    {200      method: 'setProperties',201      methodParams: [[{key: 'testKey1', value: Buffer.from('testValue1')}, {key: 'testKey2', value: Buffer.from('testValue2')}]],202      expectedProps: [{key: 'testKey1', value: 'testValue1'}, {key: 'testKey2', value: 'testValue2'}],203    },204    {205      method: 'setProperty' /*Soft-deprecated*/,206      methodParams: ['testKey1', Buffer.from('testValue1')],207      expectedProps: [{key: 'testKey1', value: 'testValue1'}],208    },209  ].map(testCase =>210    itEth(`[${testCase.method}] Can be set`, async({helper}) => {211      const caller = await helper.eth.createAccountWithBalance(donor);212      const collection = await helper.nft.mintCollection(alice, {213        tokenPropertyPermissions: [{214          key: 'testKey1',215          permission: {216            collectionAdmin: true,217          },218        }, {219          key: 'testKey2',220          permission: {221            collectionAdmin: true,222          },223        }],224      });225226      await collection.addAdmin(alice, {Ethereum: caller});227      const token = await collection.mintToken(alice);228229      const collectionEvm = await helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller, testCase.method === 'setProperty');230231      await collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller});232233      const properties = await token.getProperties();234      expect(properties).to.deep.equal(testCase.expectedProps);235    }));236237  [238    {mode: 'nft' as const, requiredPallets: []},239    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},240  ].map(testCase =>241    itEth.ifWithPallets(`Can be multiple set/read for ${testCase.mode}`, testCase.requiredPallets, async({helper}) => {242      const caller = await helper.eth.createAccountWithBalance(donor);243244      const properties = Array(5).fill(0).map((_, i) => ({key: `key_${i}`, value: Buffer.from(`value_${i}`)}));245      const permissions: ITokenPropertyPermission[] = properties.map(p => ({key: p.key, permission: {tokenOwner: true,246        collectionAdmin: true,247        mutable: true}}));248249      const collection = await helper[testCase.mode].mintCollection(alice, {250        tokenPrefix: 'ethp',251        tokenPropertyPermissions: permissions,252      }) as UniqueNFTCollection | UniqueRFTCollection;253254      const token = await collection.mintToken(alice);255256      const valuesBefore = await token.getProperties(properties.map(p => p.key));257      expect(valuesBefore).to.be.deep.equal([]);258259260      await collection.addAdmin(alice, {Ethereum: caller});261262      const address = helper.ethAddress.fromCollectionId(collection.collectionId);263      const contract = await helper.ethNativeContract.collection(address, testCase.mode, caller);264265      expect(await contract.methods.properties(token.tokenId, []).call()).to.be.deep.equal([]);266267      await contract.methods.setProperties(token.tokenId, properties).send({from: caller});268269      const values = await token.getProperties(properties.map(p => p.key));270      expect(values).to.be.deep.equal(properties.map(p => ({key: p.key, value: p.value.toString()})));271272      expect(await contract.methods.properties(token.tokenId, []).call()).to.be.like(properties273        .map(p => helper.ethProperty.property(p.key, p.value.toString())));274275      expect(await contract.methods.properties(token.tokenId, [properties[0].key]).call())276        .to.be.like([helper.ethProperty.property(properties[0].key, properties[0].value.toString())]);277    }));278279  [280    {mode: 'nft' as const, requiredPallets: []},281    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},282  ].map(testCase =>283    itEth.ifWithPallets(`Can be deleted for ${testCase.mode}`, testCase.requiredPallets, async({helper}) => {284      const caller = await helper.eth.createAccountWithBalance(donor);285      const collection = await helper[testCase.mode].mintCollection(alice, {286        tokenPropertyPermissions: [{287          key: 'testKey',288          permission: {289            mutable: true,290            collectionAdmin: true,291          },292        },293        {294          key: 'testKey_1',295          permission: {296            mutable: true,297            collectionAdmin: true,298          },299        }],300      });301302      const token = await collection.mintToken(alice);303      await token.setProperties(alice, [{key: 'testKey', value: 'testValue'}, {key: 'testKey_1', value: 'testValue_1'}]);304      expect(await token.getProperties()).to.has.length(2);305306      await collection.addAdmin(alice, {Ethereum: caller});307308      const address = helper.ethAddress.fromCollectionId(collection.collectionId);309      const contract = await helper.ethNativeContract.collection(address, testCase.mode, caller);310311      await contract.methods.deleteProperties(token.tokenId, ['testKey', 'testKey_1']).send({from: caller});312313      const result = await token.getProperties(['testKey', 'testKey_1']);314      expect(result.length).to.equal(0);315    }));316317  itEth('Can be read', async({helper}) => {318    const caller = helper.eth.createAccount();319    const collection = await helper.nft.mintCollection(alice, {320      tokenPropertyPermissions: [{321        key: 'testKey',322        permission: {323          collectionAdmin: true,324        },325      }],326    });327328    const token = await collection.mintToken(alice);329    await token.setProperties(alice, [{key: 'testKey', value: 'testValue'}]);330331    const address = helper.ethAddress.fromCollectionId(collection.collectionId);332    const contract = await helper.ethNativeContract.collection(address, 'nft', caller);333334    const value = await contract.methods.property(token.tokenId, 'testKey').call();335    expect(value).to.equal(helper.getWeb3().utils.toHex('testValue'));336  });337});338339describe('EVM token properties negative', () => {340  let donor: IKeyringPair;341  let alice: IKeyringPair;342  let caller: string;343  let aliceCollection: UniqueNFTCollection;344  let token: UniqueNFToken;345  const tokenProps = [{key: 'testKey_1', value: 'testValue_1'}, {key: 'testKey_2', value: 'testValue_2'}];346  let collectionEvm: Contract;347348  before(async function() {349    await usingEthPlaygrounds(async (helper, privateKey) => {350      donor = await privateKey({url: import.meta.url});351      [alice] = await helper.arrange.createAccounts([100n], donor);352    });353  });354355  beforeEach(async () => {356    // 1. create collection with props: testKey_1, testKey_2357    // 2. create token and set props testKey_1, testKey_2358    await usingEthPlaygrounds(async (helper) => {359      aliceCollection = await helper.nft.mintCollection(alice, {360        tokenPropertyPermissions: [{361          key: 'testKey_1',362          permission: {363            mutable: true,364            collectionAdmin: true,365          },366        },367        {368          key: 'testKey_2',369          permission: {370            mutable: true,371            collectionAdmin: true,372          },373        }],374      });375      token = await aliceCollection.mintToken(alice);376      await token.setProperties(alice, tokenProps);377      collectionEvm = await helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, true);378    });379  });380381  [382    {method: 'setProperty', methodParams: [tokenProps[1].key, Buffer.from('newValue')]},383    {method: 'setProperties', methodParams: [[{key: tokenProps[1].key, value: Buffer.from('newValue')}]]},384  ].map(testCase =>385    itEth(`[${testCase.method}] Cannot set properties of non-owned collection`, async ({helper}) => {386      caller = await helper.eth.createAccountWithBalance(donor);387      collectionEvm = await helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, true);388      // Caller not an owner and not an admin, so he cannot set properties:389      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');390      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;391392      // Props have not changed:393      const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));394      const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();395      expect(actualProps).to.deep.eq(expectedProps);396    }));397398  [399    {method: 'setProperty', methodParams: ['testKey_3', Buffer.from('testValue3')]},400    {method: 'setProperties', methodParams: [[{key: 'testKey_3', value: Buffer.from('testValue3')}]]},401  ].map(testCase =>402    itEth(`[${testCase.method}] Cannot set non-existing properties`, async ({helper}) => {403      caller = await helper.eth.createAccountWithBalance(donor);404      collectionEvm = await helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, true);405      await helper.collection.addAdmin(alice, aliceCollection.collectionId, {Ethereum: caller});406407      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');408      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;409410      // Props have not changed:411      const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));412      const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();413      expect(actualProps).to.deep.eq(expectedProps);414    }));415416  [417    {method: 'deleteProperty', methodParams: ['testKey_2']},418    {method: 'deleteProperties', methodParams: [['testKey_2']]},419  ].map(testCase =>420    itEth(`[${testCase.method}] Cannot delete properties of non-owned collection`, async ({helper}) => {421      caller = await helper.eth.createAccountWithBalance(donor);422      collectionEvm = await helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, testCase.method == 'deleteProperty');423      // Caller not an owner and not an admin, so he cannot set properties:424      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');425      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;426427      // Props have not changed:428      const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));429      const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();430      expect(actualProps).to.deep.eq(expectedProps);431    }));432433  [434    {method: 'deleteProperty', methodParams: ['testKey_3']},435    {method: 'deleteProperties', methodParams: [['testKey_3']]},436  ].map(testCase =>437    itEth(`[${testCase.method}] Cannot delete non-existing properties`, async ({helper}) => {438      caller = await helper.eth.createAccountWithBalance(donor);439      collectionEvm = await helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, testCase.method == 'deleteProperty');440      await helper.collection.addAdmin(alice, aliceCollection.collectionId, {Ethereum: caller});441      // Caller cannot delete non-existing properties:442      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');443      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;444      // Props have not changed:445      const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));446      const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();447      expect(actualProps).to.deep.eq(expectedProps);448    }));449450  [451    {mode: 'nft' as const, requiredPallets: []},452    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},453  ].map(testCase =>454    itEth.ifWithPallets(`[${testCase.mode}] Cannot set token property permissions as non owner or admin`, testCase.requiredPallets, async({helper}) => {455      const owner = await helper.eth.createAccountWithBalance(donor);456      const caller = await helper.eth.createAccountWithBalance(donor);457458      const {collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');459      const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);460461      await expect(collection.methods.setTokenPropertyPermissions([462        ['testKey_0', [463          [TokenPermissionField.Mutable, true],464          [TokenPermissionField.TokenOwner, true],465          [TokenPermissionField.CollectionAdmin, true]],466        ],467      ]).call({from: caller})).to.be.rejectedWith('NoPermission');468    }));469470  [471    {mode: 'nft' as const, requiredPallets: []},472    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},473  ].map(testCase =>474    itEth.ifWithPallets(`[${testCase.mode}] Cannot set token property permissions with invalid character`, testCase.requiredPallets, async({helper}) => {475      const owner = await helper.eth.createAccountWithBalance(donor);476477      const {collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');478      const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);479480      await expect(collection.methods.setTokenPropertyPermissions([481        // "Space" is invalid character482        ['testKey 0', [483          [TokenPermissionField.Mutable, true],484          [TokenPermissionField.TokenOwner, true],485          [TokenPermissionField.CollectionAdmin, true]],486        ],487      ]).call({from: owner})).to.be.rejectedWith('InvalidCharacterInPropertyKey');488    }));489490  [491    {mode: 'nft' as const, requiredPallets: []},492    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},493  ].map(testCase =>494    itEth.ifWithPallets(`[${testCase.mode}] Can reconfigure token property permissions to stricter ones`, testCase.requiredPallets, async({helper}) => {495      const owner = await helper.eth.createAccountWithBalance(donor);496497      const {collectionAddress, collectionId} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');498      const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);499500      // 1. Owner sets strict property-permissions:501      await collection.methods.setTokenPropertyPermissions([502        ['testKey', [503          [TokenPermissionField.Mutable, true],504          [TokenPermissionField.TokenOwner, true],505          [TokenPermissionField.CollectionAdmin, true]],506        ],507      ]).send({from: owner});508509      // 2. Owner can set stricter property-permissions:510      for(const values of [[true, true, false], [true, false, false], [false, false, false]]) {511        await collection.methods.setTokenPropertyPermissions([512          ['testKey', [513            [TokenPermissionField.Mutable, values[0]],514            [TokenPermissionField.TokenOwner, values[1]],515            [TokenPermissionField.CollectionAdmin, values[2]]],516          ],517        ]).send({from: owner});518      }519520      expect(await helper[testCase.mode].getPropertyPermissions(collectionId)).to.be.deep.equal([{521        key: 'testKey',522        permission: {mutable: false, collectionAdmin: false, tokenOwner: false},523      }]);524    }));525526  [527    {mode: 'nft' as const, requiredPallets: []},528    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},529  ].map(testCase =>530    itEth.ifWithPallets(`[${testCase.mode}] Cannot reconfigure token property permissions to less strict ones`, testCase.requiredPallets, async({helper}) => {531      const owner = await helper.eth.createAccountWithBalance(donor);532533      const {collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');534      const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);535536      // 1. Owner sets strict property-permissions:537      await collection.methods.setTokenPropertyPermissions([538        ['testKey', [539          [TokenPermissionField.Mutable, false],540          [TokenPermissionField.TokenOwner, false],541          [TokenPermissionField.CollectionAdmin, false]],542        ],543      ]).send({from: owner});544545      // 2. Owner cannot set less strict property-permissions:546      for(const values of [[true, false, false], [false, true, false], [false, false, true]]) {547        await expect(collection.methods.setTokenPropertyPermissions([548          ['testKey', [549            [TokenPermissionField.Mutable, values[0]],550            [TokenPermissionField.TokenOwner, values[1]],551            [TokenPermissionField.CollectionAdmin, values[2]]],552          ],553        ]).call({from: owner})).to.be.rejectedWith('NoPermission');554      }555    }));556557  [558    {mode: 'nft' as const, requiredPallets: []},559    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},560  ].map(testCase =>561    itEth.ifWithPallets(`[${testCase.mode}] Can't be multiple set/read for non-existent token`, testCase.requiredPallets, async({helper}) => {562      const caller = await helper.eth.createAccountWithBalance(donor);563564      const properties = Array(5).fill(0).map((_, i) => { return {key: `key_${i}`, value: Buffer.from(`value_${i}`)}; });565      const permissions: ITokenPropertyPermission[] = properties.map(p => { return {key: p.key, permission: {tokenOwner: true,566        collectionAdmin: true,567        mutable: true}}; });568569      const collection = await helper[testCase.mode].mintCollection(alice, {570        tokenPrefix: 'ethp',571        tokenPropertyPermissions: permissions,572      }) as UniqueNFTCollection | UniqueRFTCollection;573574      await collection.addAdmin(alice, {Ethereum: caller});575576      const address = helper.ethAddress.fromCollectionId(collection.collectionId);577      const contract = await helper.ethNativeContract.collection(address, testCase.mode, caller);578579      await expect(contract.methods.setProperties(1, properties).call({from: caller})).to.be.rejectedWith('TokenNotFound');580    }));581582  [583    {mode: 'nft' as const, requiredPallets: []},584    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},585  ].map(testCase =>586    itEth.ifWithPallets(`[${testCase.mode}] Can't be deleted for non-existent token`, testCase.requiredPallets, async({helper}) => {587      const caller = await helper.eth.createAccountWithBalance(donor);588      const collection = await helper[testCase.mode].mintCollection(alice, {589        tokenPropertyPermissions: [{590          key: 'testKey',591          permission: {592            mutable: true,593            collectionAdmin: true,594          },595        },596        {597          key: 'testKey_1',598          permission: {599            mutable: true,600            collectionAdmin: true,601          },602        }],603      });604605606      await collection.addAdmin(alice, {Ethereum: caller});607608      const address = helper.ethAddress.fromCollectionId(collection.collectionId);609      const contract = await helper.ethNativeContract.collection(address, testCase.mode, caller);610611      await expect(contract.methods.deleteProperties(1, ['testKey', 'testKey_1']).call({from: caller})).to.be.rejectedWith('TokenNotFound');612    }));613});614615616type ElementOf<A> = A extends readonly (infer T)[] ? T : never;617function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {618  if(args.length === 0) {619    yield internalRest as any;620    return;621  }622  for(const value of args[0]) {623    yield* cartesian([...internalRest, value], ...args.slice(1)) as any;624  }625}
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 {TokenPermissionField} 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({url: import.meta.url});32      [alice] = await helper.arrange.createAccounts([1000n], 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}] Can set all possible 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            [TokenPermissionField.Mutable, mutable],51            [TokenPermissionField.TokenOwner, tokenOwner],52            [TokenPermissionField.CollectionAdmin, collectionAdmin]],53          ],54        ]).send({from: caller.eth});5556        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            [TokenPermissionField.Mutable.toString(), mutable],64            [TokenPermissionField.TokenOwner.toString(), tokenOwner],65            [TokenPermissionField.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}] Can set multiple token property permissions as owner`, testCase.requiredPallets, async({helper}) => {76      const owner = await helper.eth.createAccountWithBalance(donor);7778      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          [TokenPermissionField.Mutable, true],84          [TokenPermissionField.TokenOwner, true],85          [TokenPermissionField.CollectionAdmin, true]],86        ],87        ['testKey_1', [88          [TokenPermissionField.Mutable, true],89          [TokenPermissionField.TokenOwner, false],90          [TokenPermissionField.CollectionAdmin, true]],91        ],92        ['testKey_2', [93          [TokenPermissionField.Mutable, false],94          [TokenPermissionField.TokenOwner, true],95          [TokenPermissionField.CollectionAdmin, false]],96        ],97      ]).send({from: owner});9899      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          [TokenPermissionField.Mutable.toString(), true],117          [TokenPermissionField.TokenOwner.toString(), true],118          [TokenPermissionField.CollectionAdmin.toString(), true]],119        ],120        ['testKey_1', [121          [TokenPermissionField.Mutable.toString(), true],122          [TokenPermissionField.TokenOwner.toString(), false],123          [TokenPermissionField.CollectionAdmin.toString(), true]],124        ],125        ['testKey_2', [126          [TokenPermissionField.Mutable.toString(), false],127          [TokenPermissionField.TokenOwner.toString(), true],128          [TokenPermissionField.CollectionAdmin.toString(), false]],129        ],130      ]);131    }));132133  [134    {mode: 'nft' as const, requiredPallets: []},135    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},136  ].map(testCase =>137    itEth.ifWithPallets(`[${testCase.mode}] Can set multiple token property permissions as admin`, testCase.requiredPallets, async({helper}) => {138      const owner = await helper.eth.createAccountWithBalance(donor);139      const caller = await helper.ethCrossAccount.createAccountWithBalance(donor);140141      const {collectionId, collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');142      const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);143      await collection.methods.addCollectionAdminCross(caller).send({from: owner});144145      await collection.methods.setTokenPropertyPermissions([146        ['testKey_0', [147          [TokenPermissionField.Mutable, true],148          [TokenPermissionField.TokenOwner, true],149          [TokenPermissionField.CollectionAdmin, true]],150        ],151        ['testKey_1', [152          [TokenPermissionField.Mutable, true],153          [TokenPermissionField.TokenOwner, false],154          [TokenPermissionField.CollectionAdmin, true]],155        ],156        ['testKey_2', [157          [TokenPermissionField.Mutable, false],158          [TokenPermissionField.TokenOwner, true],159          [TokenPermissionField.CollectionAdmin, false]],160        ],161      ]).send({from: caller.eth});162163      expect(await helper[testCase.mode].getPropertyPermissions(collectionId)).to.be.deep.equal([164        {165          key: 'testKey_0',166          permission: {mutable: true, tokenOwner: true, collectionAdmin: true},167        },168        {169          key: 'testKey_1',170          permission: {mutable: true, tokenOwner: false, collectionAdmin: true},171        },172        {173          key: 'testKey_2',174          permission: {mutable: false, tokenOwner: true, collectionAdmin: false},175        },176      ]);177178      expect(await collection.methods.tokenPropertyPermissions().call({from: caller.eth})).to.be.like([179        ['testKey_0', [180          [TokenPermissionField.Mutable.toString(), true],181          [TokenPermissionField.TokenOwner.toString(), true],182          [TokenPermissionField.CollectionAdmin.toString(), true]],183        ],184        ['testKey_1', [185          [TokenPermissionField.Mutable.toString(), true],186          [TokenPermissionField.TokenOwner.toString(), false],187          [TokenPermissionField.CollectionAdmin.toString(), true]],188        ],189        ['testKey_2', [190          [TokenPermissionField.Mutable.toString(), false],191          [TokenPermissionField.TokenOwner.toString(), true],192          [TokenPermissionField.CollectionAdmin.toString(), false]],193        ],194      ]);195196    }));197198  [199    {200      method: 'setProperties',201      methodParams: [[{key: 'testKey1', value: Buffer.from('testValue1')}, {key: 'testKey2', value: Buffer.from('testValue2')}]],202      expectedProps: [{key: 'testKey1', value: 'testValue1'}, {key: 'testKey2', value: 'testValue2'}],203    },204    {205      method: 'setProperty' /*Soft-deprecated*/,206      methodParams: ['testKey1', Buffer.from('testValue1')],207      expectedProps: [{key: 'testKey1', value: 'testValue1'}],208    },209  ].map(testCase =>210    itEth(`[${testCase.method}] Can be set`, async({helper}) => {211      const caller = await helper.eth.createAccountWithBalance(donor);212      const collection = await helper.nft.mintCollection(alice, {213        tokenPropertyPermissions: [{214          key: 'testKey1',215          permission: {216            collectionAdmin: true,217          },218        }, {219          key: 'testKey2',220          permission: {221            collectionAdmin: true,222          },223        }],224      });225226      await collection.addAdmin(alice, {Ethereum: caller});227      const token = await collection.mintToken(alice);228229      const collectionEvm = await helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller, testCase.method === 'setProperty');230231      await collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller});232233      const properties = await token.getProperties();234      expect(properties).to.deep.equal(testCase.expectedProps);235    }));236237  [238    {mode: 'nft' as const, requiredPallets: []},239    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},240  ].map(testCase =>241    itEth.ifWithPallets(`Can be multiple set/read for ${testCase.mode}`, testCase.requiredPallets, async({helper}) => {242      const caller = await helper.eth.createAccountWithBalance(donor);243244      const properties = Array(5).fill(0).map((_, i) => ({key: `key_${i}`, value: Buffer.from(`value_${i}`)}));245      const permissions: ITokenPropertyPermission[] = properties.map(p => ({key: p.key, permission: {tokenOwner: true,246        collectionAdmin: true,247        mutable: true}}));248249      const collection = await helper[testCase.mode].mintCollection(alice, {250        tokenPrefix: 'ethp',251        tokenPropertyPermissions: permissions,252      }) as UniqueNFTCollection | UniqueRFTCollection;253254      const token = await collection.mintToken(alice);255256      const valuesBefore = await token.getProperties(properties.map(p => p.key));257      expect(valuesBefore).to.be.deep.equal([]);258259260      await collection.addAdmin(alice, {Ethereum: caller});261262      const address = helper.ethAddress.fromCollectionId(collection.collectionId);263      const contract = await helper.ethNativeContract.collection(address, testCase.mode, caller);264265      expect(await contract.methods.properties(token.tokenId, []).call()).to.be.deep.equal([]);266267      await contract.methods.setProperties(token.tokenId, properties).send({from: caller});268269      const values = await token.getProperties(properties.map(p => p.key));270      expect(values).to.be.deep.equal(properties.map(p => ({key: p.key, value: p.value.toString()})));271272      expect(await contract.methods.properties(token.tokenId, []).call()).to.be.like(properties273        .map(p => helper.ethProperty.property(p.key, p.value.toString())));274275      expect(await contract.methods.properties(token.tokenId, [properties[0].key]).call())276        .to.be.like([helper.ethProperty.property(properties[0].key, properties[0].value.toString())]);277    }));278279  [280    {mode: 'nft' as const, requiredPallets: []},281    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},282  ].map(testCase =>283    itEth.ifWithPallets(`Can be deleted for ${testCase.mode}`, testCase.requiredPallets, async({helper}) => {284      const caller = await helper.eth.createAccountWithBalance(donor);285      const collection = await helper[testCase.mode].mintCollection(alice, {286        tokenPropertyPermissions: [{287          key: 'testKey',288          permission: {289            mutable: true,290            collectionAdmin: true,291          },292        },293        {294          key: 'testKey_1',295          permission: {296            mutable: true,297            collectionAdmin: true,298          },299        }],300      });301302      const token = await collection.mintToken(alice);303      await token.setProperties(alice, [{key: 'testKey', value: 'testValue'}, {key: 'testKey_1', value: 'testValue_1'}]);304      expect(await token.getProperties()).to.has.length(2);305306      await collection.addAdmin(alice, {Ethereum: caller});307308      const address = helper.ethAddress.fromCollectionId(collection.collectionId);309      const contract = await helper.ethNativeContract.collection(address, testCase.mode, caller);310311      await contract.methods.deleteProperties(token.tokenId, ['testKey', 'testKey_1']).send({from: caller});312313      const result = await token.getProperties(['testKey', 'testKey_1']);314      expect(result.length).to.equal(0);315    }));316317  itEth('Can be read', async({helper}) => {318    const caller = helper.eth.createAccount();319    const collection = await helper.nft.mintCollection(alice, {320      tokenPropertyPermissions: [{321        key: 'testKey',322        permission: {323          collectionAdmin: true,324        },325      }],326    });327328    const token = await collection.mintToken(alice);329    await token.setProperties(alice, [{key: 'testKey', value: 'testValue'}]);330331    const address = helper.ethAddress.fromCollectionId(collection.collectionId);332    const contract = await helper.ethNativeContract.collection(address, 'nft', caller);333334    const value = await contract.methods.property(token.tokenId, 'testKey').call();335    expect(value).to.equal(helper.getWeb3().utils.toHex('testValue'));336  });337});338339describe('EVM token properties negative', () => {340  let donor: IKeyringPair;341  let alice: IKeyringPair;342  let caller: string;343  let aliceCollection: UniqueNFTCollection;344  let token: UniqueNFToken;345  const tokenProps = [{key: 'testKey_1', value: 'testValue_1'}, {key: 'testKey_2', value: 'testValue_2'}];346  let collectionEvm: Contract;347348  before(async function() {349    await usingEthPlaygrounds(async (helper, privateKey) => {350      donor = await privateKey({url: import.meta.url});351      [alice] = await helper.arrange.createAccounts([100n], donor);352    });353  });354355  beforeEach(async () => {356    // 1. create collection with props: testKey_1, testKey_2357    // 2. create token and set props testKey_1, testKey_2358    await usingEthPlaygrounds(async (helper) => {359      aliceCollection = await helper.nft.mintCollection(alice, {360        tokenPropertyPermissions: [{361          key: 'testKey_1',362          permission: {363            mutable: true,364            collectionAdmin: true,365          },366        },367        {368          key: 'testKey_2',369          permission: {370            mutable: true,371            collectionAdmin: true,372          },373        }],374      });375      token = await aliceCollection.mintToken(alice);376      await token.setProperties(alice, tokenProps);377      collectionEvm = await helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, true);378    });379  });380381  [382    {method: 'setProperty', methodParams: [tokenProps[1].key, Buffer.from('newValue')]},383    {method: 'setProperties', methodParams: [[{key: tokenProps[1].key, value: Buffer.from('newValue')}]]},384  ].map(testCase =>385    itEth(`[${testCase.method}] Cannot set properties of non-owned collection`, async ({helper}) => {386      caller = await helper.eth.createAccountWithBalance(donor);387      collectionEvm = await helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, true);388      // Caller not an owner and not an admin, so he cannot set properties:389      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');390      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;391392      // Props have not changed:393      const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));394      const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();395      expect(actualProps).to.deep.eq(expectedProps);396    }));397398  [399    {method: 'setProperty', methodParams: ['testKey_3', Buffer.from('testValue3')]},400    {method: 'setProperties', methodParams: [[{key: 'testKey_3', value: Buffer.from('testValue3')}]]},401  ].map(testCase =>402    itEth(`[${testCase.method}] Cannot set non-existing properties`, async ({helper}) => {403      caller = await helper.eth.createAccountWithBalance(donor);404      collectionEvm = await helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, true);405      await helper.collection.addAdmin(alice, aliceCollection.collectionId, {Ethereum: caller});406407      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');408      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;409410      // Props have not changed:411      const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));412      const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();413      expect(actualProps).to.deep.eq(expectedProps);414    }));415416  [417    {method: 'deleteProperty', methodParams: ['testKey_2']},418    {method: 'deleteProperties', methodParams: [['testKey_2']]},419  ].map(testCase =>420    itEth(`[${testCase.method}] Cannot delete properties of non-owned collection`, async ({helper}) => {421      caller = await helper.eth.createAccountWithBalance(donor);422      collectionEvm = await helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, testCase.method == 'deleteProperty');423      // Caller not an owner and not an admin, so he cannot set properties:424      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');425      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;426427      // Props have not changed:428      const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));429      const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();430      expect(actualProps).to.deep.eq(expectedProps);431    }));432433  [434    {method: 'deleteProperty', methodParams: ['testKey_3']},435    {method: 'deleteProperties', methodParams: [['testKey_3']]},436  ].map(testCase =>437    itEth(`[${testCase.method}] Cannot delete non-existing properties`, async ({helper}) => {438      caller = await helper.eth.createAccountWithBalance(donor);439      collectionEvm = await helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(aliceCollection.collectionId), 'nft', caller, testCase.method == 'deleteProperty');440      await helper.collection.addAdmin(alice, aliceCollection.collectionId, {Ethereum: caller});441      // Caller cannot delete non-existing properties:442      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).call({from: caller})).to.be.rejectedWith('NoPermission');443      await expect(collectionEvm.methods[testCase.method](token.tokenId, ...testCase.methodParams).send({from: caller})).to.be.rejected;444      // Props have not changed:445      const expectedProps = tokenProps.map(p => helper.ethProperty.property(p.key, p.value.toString()));446      const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();447      expect(actualProps).to.deep.eq(expectedProps);448    }));449450  [451    {mode: 'nft' as const, requiredPallets: []},452    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},453  ].map(testCase =>454    itEth.ifWithPallets(`[${testCase.mode}] Cannot set token property permissions as non owner or admin`, testCase.requiredPallets, async({helper}) => {455      const owner = await helper.eth.createAccountWithBalance(donor);456      const caller = await helper.eth.createAccountWithBalance(donor);457458      const {collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');459      const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);460461      await expect(collection.methods.setTokenPropertyPermissions([462        ['testKey_0', [463          [TokenPermissionField.Mutable, true],464          [TokenPermissionField.TokenOwner, true],465          [TokenPermissionField.CollectionAdmin, true]],466        ],467      ]).call({from: caller})).to.be.rejectedWith('NoPermission');468    }));469470  [471    {mode: 'nft' as const, requiredPallets: []},472    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},473  ].map(testCase =>474    itEth.ifWithPallets(`[${testCase.mode}] Cannot set token property permissions with invalid character`, testCase.requiredPallets, async({helper}) => {475      const owner = await helper.eth.createAccountWithBalance(donor);476477      const {collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');478      const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);479480      await expect(collection.methods.setTokenPropertyPermissions([481        // "Space" is invalid character482        ['testKey 0', [483          [TokenPermissionField.Mutable, true],484          [TokenPermissionField.TokenOwner, true],485          [TokenPermissionField.CollectionAdmin, true]],486        ],487      ]).call({from: owner})).to.be.rejectedWith('InvalidCharacterInPropertyKey');488    }));489490  [491    {mode: 'nft' as const, requiredPallets: []},492    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},493  ].map(testCase =>494    itEth.ifWithPallets(`[${testCase.mode}] Can reconfigure token property permissions to stricter ones`, testCase.requiredPallets, async({helper}) => {495      const owner = await helper.eth.createAccountWithBalance(donor);496497      const {collectionAddress, collectionId} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');498      const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);499500      // 1. Owner sets strict property-permissions:501      await collection.methods.setTokenPropertyPermissions([502        ['testKey', [503          [TokenPermissionField.Mutable, true],504          [TokenPermissionField.TokenOwner, true],505          [TokenPermissionField.CollectionAdmin, true]],506        ],507      ]).send({from: owner});508509      // 2. Owner can set stricter property-permissions:510      for(const values of [[true, true, false], [true, false, false], [false, false, false]]) {511        await collection.methods.setTokenPropertyPermissions([512          ['testKey', [513            [TokenPermissionField.Mutable, values[0]],514            [TokenPermissionField.TokenOwner, values[1]],515            [TokenPermissionField.CollectionAdmin, values[2]]],516          ],517        ]).send({from: owner});518      }519520      expect(await helper[testCase.mode].getPropertyPermissions(collectionId)).to.be.deep.equal([{521        key: 'testKey',522        permission: {mutable: false, collectionAdmin: false, tokenOwner: false},523      }]);524    }));525526  [527    {mode: 'nft' as const, requiredPallets: []},528    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},529  ].map(testCase =>530    itEth.ifWithPallets(`[${testCase.mode}] Cannot reconfigure token property permissions to less strict ones`, testCase.requiredPallets, async({helper}) => {531      const owner = await helper.eth.createAccountWithBalance(donor);532533      const {collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');534      const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);535536      // 1. Owner sets strict property-permissions:537      await collection.methods.setTokenPropertyPermissions([538        ['testKey', [539          [TokenPermissionField.Mutable, false],540          [TokenPermissionField.TokenOwner, false],541          [TokenPermissionField.CollectionAdmin, false]],542        ],543      ]).send({from: owner});544545      // 2. Owner cannot set less strict property-permissions:546      for(const values of [[true, false, false], [false, true, false], [false, false, true]]) {547        await expect(collection.methods.setTokenPropertyPermissions([548          ['testKey', [549            [TokenPermissionField.Mutable, values[0]],550            [TokenPermissionField.TokenOwner, values[1]],551            [TokenPermissionField.CollectionAdmin, values[2]]],552          ],553        ]).call({from: owner})).to.be.rejectedWith('NoPermission');554      }555    }));556557  [558    {mode: 'nft' as const, requiredPallets: []},559    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},560  ].map(testCase =>561    itEth.ifWithPallets(`[${testCase.mode}] Can't be multiple set/read for non-existent token`, testCase.requiredPallets, async({helper}) => {562      const caller = await helper.eth.createAccountWithBalance(donor);563564      const properties = Array(5).fill(0).map((_, i) => ({key: `key_${i}`, value: Buffer.from(`value_${i}`)}));565      const permissions: ITokenPropertyPermission[] = properties.map(p => ({key: p.key, permission: {tokenOwner: true,566        collectionAdmin: true,567        mutable: true}}));568569      const collection = await helper[testCase.mode].mintCollection(alice, {570        tokenPrefix: 'ethp',571        tokenPropertyPermissions: permissions,572      }) as UniqueNFTCollection | UniqueRFTCollection;573574      await collection.addAdmin(alice, {Ethereum: caller});575576      const address = helper.ethAddress.fromCollectionId(collection.collectionId);577      const contract = await helper.ethNativeContract.collection(address, testCase.mode, caller);578579      await expect(contract.methods.setProperties(1, properties).call({from: caller})).to.be.rejectedWith('TokenNotFound');580    }));581582  [583    {mode: 'nft' as const, requiredPallets: []},584    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},585  ].map(testCase =>586    itEth.ifWithPallets(`[${testCase.mode}] Can't be deleted for non-existent token`, testCase.requiredPallets, async({helper}) => {587      const caller = await helper.eth.createAccountWithBalance(donor);588      const collection = await helper[testCase.mode].mintCollection(alice, {589        tokenPropertyPermissions: [{590          key: 'testKey',591          permission: {592            mutable: true,593            collectionAdmin: true,594          },595        },596        {597          key: 'testKey_1',598          permission: {599            mutable: true,600            collectionAdmin: true,601          },602        }],603      });604605606      await collection.addAdmin(alice, {Ethereum: caller});607608      const address = helper.ethAddress.fromCollectionId(collection.collectionId);609      const contract = await helper.ethNativeContract.collection(address, testCase.mode, caller);610611      await expect(contract.methods.deleteProperties(1, ['testKey', 'testKey_1']).call({from: caller})).to.be.rejectedWith('TokenNotFound');612    }));613});614615616type ElementOf<A> = A extends readonly (infer T)[] ? T : never;617function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {618  if(args.length === 0) {619    yield internalRest as any;620    return;621  }622  for(const value of args[0]) {623    yield* cartesian([...internalRest, value], ...args.slice(1)) as any;624  }625}