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

difftreelog

test(structure) extra nesting + properties refactoring

Fahrrader2022-05-13parent: #0baf86c.patch.diff
in: master

7 files changed

modifiedtests/src/createItem.test.tsdiffbeforeafterboth
--- a/tests/src/createItem.test.ts
+++ b/tests/src/createItem.test.ts
@@ -144,7 +144,6 @@
 
   it('User doesnt have editing rights', async () => {
     await usingApi(async api => {
-      const createMode = 'NFT';
       const newCollectionID = await createCollectionWithPropsExpectSuccess({propPerm: [{key: 'key1', mutable: true, collectionAdmin: false, tokenOwner: false}]});
       const token = await createItemExpectSuccess(alice, newCollectionID, 'NFT');
 
modifiedtests/src/createMultipleItems.test.tsdiffbeforeafterboth
--- a/tests/src/createMultipleItems.test.ts
+++ b/tests/src/createMultipleItems.test.ts
@@ -146,7 +146,6 @@
       const itemsListIndexBefore = await getLastTokenId(api, collectionId);
       expect(itemsListIndexBefore).to.be.equal(0);
       const alice = privateKey('//Alice');
-      const bob = privateKey('//Bob');
       const args = [{Nft: {const_data: '0x31', variable_data: '0x31'}},
         {Nft: {const_data: '0x32', variable_data: '0x32'}},
         {Nft: {const_data: '0x33', variable_data: '0x33'}}];
@@ -182,7 +181,6 @@
       const itemsListIndexBefore = await getLastTokenId(api, collectionId);
       expect(itemsListIndexBefore).to.be.equal(0);
       const alice = privateKey('//Alice');
-      const bob = privateKey('//Bob');
       const args = [{Nft: {const_data: '0x31', variable_data: '0x31'}},
         {Nft: {const_data: '0x32', variable_data: '0x32'}},
         {Nft: {const_data: '0x33', variable_data: '0x33'}}];
@@ -218,7 +216,6 @@
       const itemsListIndexBefore = await getLastTokenId(api, collectionId);
       expect(itemsListIndexBefore).to.be.equal(0);
       const alice = privateKey('//Alice');
-      const bob = privateKey('//Bob');
       const args = [{Nft: {const_data: '0x31', variable_data: '0x31'}},
         {Nft: {const_data: '0x32', variable_data: '0x32'}},
         {Nft: {const_data: '0x33', variable_data: '0x33'}}];
modifiedtests/src/nesting/migration-check.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/migration-check.test.ts
+++ b/tests/src/nesting/migration-check.test.ts
@@ -8,8 +8,8 @@
 // Used for polkadot-launch signalling
 import find from 'find-process';
 
-// todo skip
-describe('Migration testing for pallet-common', () => {
+// todo un-skip for migrations
+describe.skip('Migration testing for pallet-common', () => {
   let alice: IKeyringPair;
 
   before(async() => {
@@ -63,16 +63,33 @@
     });
 
     // And wait for the parachain upgrade
-    while (newVersion == oldVersion! && connectionFailCounter < 2) {
-      try {
-        await usingApi(async api => {
-          await waitNewBlocks(api);
-          newVersion = (api.consts.system.version.toJSON() as any).specVersion;
-        });
-      } catch (_) {
-        connectionFailCounter++;
-        console.log(`Still waiting for the parachain upgrade from ${oldVersion!}...`);
-        await new Promise(resolve => setTimeout(resolve, 12000));
+    {
+      // Catch warnings like 'RPC methods not decorated' and keep the 'waiting' message in front
+      const stdlog = console.warn.bind(console);
+      let warnCount = 0;
+      console.warn = function(...args){
+        if (arguments.length <= 2 || !args[2].includes('RPC methods not decorated')) {
+          warnCount++;
+          stdlog.apply(console, args as any);
+        }
+      };
+
+      let oldWarnCount = 0;
+      while (newVersion == oldVersion! && connectionFailCounter < 2) {
+        try {
+          await usingApi(async api => {
+            await waitNewBlocks(api);
+            newVersion = (api.consts.system.version.toJSON() as any).specVersion;
+            if (warnCount > oldWarnCount) {
+              console.log(`Still waiting for the parachain upgrade from ${oldVersion!}...`);
+              oldWarnCount = warnCount;
+            }
+            await new Promise(resolve => setTimeout(resolve, 6000));
+          });
+        } catch (_) {
+          connectionFailCounter++;
+          await new Promise(resolve => setTimeout(resolve, 12000));
+        }
       }
     }
 
modifiedtests/src/nesting/nest.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/nest.test.ts
+++ b/tests/src/nesting/nest.test.ts
@@ -9,8 +9,7 @@
   enableAllowListExpectSuccess,
   enablePublicMintingExpectSuccess,
   getTokenOwner, 
-  getTopmostTokenOwner, 
-  normalizeAccountId, 
+  getTopmostTokenOwner,
   setCollectionLimitsExpectSuccess, 
   transferExpectFailure, 
   transferExpectSuccess, 
@@ -23,7 +22,7 @@
 
 describe('Integration Test: Nesting', () => {
   before(async () => {
-    await usingApi(async api => {
+    await usingApi(async () => {
       alice = privateKey('//Alice');
       bob = privateKey('//Bob');
     });
@@ -196,7 +195,7 @@
 
 describe('Negative Test: Nesting', async() => {
   before(async () => {
-    await usingApi(async api => {
+    await usingApi(async () => {
       alice = privateKey('//Alice');
       bob = privateKey('//Bob');
     });
@@ -212,14 +211,11 @@
       const nestedToken1 = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});
       const nestedToken2 = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, nestedToken1)});
       // The nesting depth is limited by 2
-      await expect(executeTransaction(
-        api, alice, 
-        api.tx.unique.createItem(
-          collection, 
-          {Ethereum: tokenIdToAddress(collection, nestedToken2)}, 
+      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
+        collection, 
+        {Ethereum: tokenIdToAddress(collection, nestedToken2)}, 
           {nft: {const_data: [], variable_data: []}} as any,
-        ),
-      ), 'while creating nested token').to.be.rejectedWith(/^structure\.DepthLimit$/); // OuroborosDetected?
+      )), 'while creating nested token').to.be.rejectedWith(/^structure\.DepthLimit$/);
 
       expect(await getTopmostTokenOwner(api, collection, nestedToken2)).to.be.deep.equal({Substrate: alice.address});
     });
@@ -234,24 +230,16 @@
       const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
 
       // Try to create a nested token
-      await expect(executeTransaction(
-        api, alice, 
-        api.tx.unique.createItem(
-          collection, 
-          {Ethereum: tokenIdToAddress(collection, targetToken)}, 
+      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
+        collection, 
+        {Ethereum: tokenIdToAddress(collection, targetToken)}, 
           {nft: {const_data: [], variable_data: []}} as any,
-        ),
-      ), 'while creating nested token').to.be.rejectedWith(/^common\.NestingIsDisabled$/);
+      )), 'while creating nested token').to.be.rejectedWith(/^common\.NestingIsDisabled$/);
 
       // Create a token to be nested
       const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
       // Try to nest
-      await expect(executeTransaction(
-        api, alice, 
-        api.tx.unique.transfer(
-          normalizeAccountId({Ethereum: tokenIdToAddress(collection, targetToken)}), collection, newToken, 1,
-        ),
-      ), 'while nesting new token').to.be.rejectedWith(/common\.NestingIsDisabled/); // todo to.be.rejected for all
+      await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.NestingIsDisabled/);
       expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
       expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
     });
@@ -270,23 +258,15 @@
       const targetToken = await createItemExpectSuccess(bob, collection, 'NFT');
 
       // Try to create a nested token in the wrong collection
-      await expect(executeTransaction(
-        api, alice, 
-        api.tx.unique.createItem(
-          collection, 
-          {Ethereum: tokenIdToAddress(collection, targetToken)}, 
+      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
+        collection, 
+        {Ethereum: tokenIdToAddress(collection, targetToken)}, 
           {nft: {const_data: [], variable_data: []}} as any,
-        ),
-      ), 'while creating nested token').to.be.rejectedWith(/structure\.DepthLimit/); // todo NestingIsDisabled?
+      )), 'while creating nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
 
       // Try to create and nest a token in the wrong collection
       const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
-      await expect(executeTransaction(
-        api, alice, 
-        api.tx.unique.transfer(
-          normalizeAccountId({Ethereum: tokenIdToAddress(collection, targetToken)}), collection, newToken, 1,
-        ),
-      ), 'while nesting new token').to.be.rejectedWith(/common\.AddressNotInAllowlist/);
+      await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.AddressNotInAllowlist/);
       expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
     });
   });
@@ -304,23 +284,15 @@
       const targetToken = await createItemExpectSuccess(bob, collection, 'NFT');
 
       // Try to create a nested token in the wrong collection
-      await expect(executeTransaction(
-        api, alice, 
-        api.tx.unique.createItem(
-          collection, 
-          {Ethereum: tokenIdToAddress(collection, targetToken)}, 
+      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
+        collection, 
+        {Ethereum: tokenIdToAddress(collection, targetToken)}, 
           {nft: {const_data: [], variable_data: []}} as any,
-        ),
-      ), 'while creating nested token').to.be.rejectedWith(/structure\.DepthLimit/);
+      )), 'while creating nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
 
       // Try to create and nest a token in the wrong collection
       const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
-      await expect(executeTransaction(
-        api, alice, 
-        api.tx.unique.transfer(
-          normalizeAccountId({Ethereum: tokenIdToAddress(collection, targetToken)}), collection, newToken, 1,
-        ),
-      ), 'while nesting new token').to.be.rejectedWith(/common\.AddressNotInAllowlist/);
+      await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.AddressNotInAllowlist/);
       expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
     });
   });
@@ -334,23 +306,15 @@
       const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
 
       // Try to create a nested token in the wrong collection
-      await expect(executeTransaction(
-        api, alice, 
-        api.tx.unique.createItem(
-          collection, 
-          {Ethereum: tokenIdToAddress(collection, targetToken)}, 
+      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
+        collection, 
+        {Ethereum: tokenIdToAddress(collection, targetToken)}, 
           {nft: {const_data: [], variable_data: []}} as any,
-        ),
-      ), 'while creating nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
+      )), 'while creating nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
 
       // Try to create and nest a token in the wrong collection
       const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
-      await expect(executeTransaction(
-        api, alice, 
-        api.tx.unique.transfer(
-          normalizeAccountId({Ethereum: tokenIdToAddress(collection, targetToken)}), collection, newToken, 1,
-        ),
-      ), 'while nesting new token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
+      await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
       expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
     });
   });
@@ -367,24 +331,21 @@
       const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
 
       // Try to create a nested token
-      await expect(executeTransaction(
-        api, alice, 
-        api.tx.unique.createItem(
-          collectionFT, 
-          targetAddress, 
-          {Fungible: {Value: 10}},
-        )
-      ), 'while creating nested token').to.be.rejectedWith(/^common\.NestingIsDisabled$/);
-
+      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
+        collectionFT, 
+        targetAddress, 
+        {Fungible: {Value: 10}},
+      )), 'while creating nested token').to.be.rejectedWith(/^common\.NestingIsDisabled$/);
+      
       // Create a token to be nested
       const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
       // Try to nest
-      await expect(executeTransaction(
-        api, alice, 
-        api.tx.unique.transfer(
-          normalizeAccountId({Ethereum: tokenIdToAddress(collectionFT, targetToken)}), collectionFT, newToken, 1,
-        ),
-      ), 'while nesting new token').to.be.rejectedWith(/fungible\.FungibleDisallowsNesting/);
+      await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.NestingIsDisabled/);
+
+      // Create another token to be nested
+      const newToken2 = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
+      // Try to nest inside a fungible token
+      await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collectionFT, newToken)}, collectionFT, newToken2, 1)), 'while nesting new token inside fungible').to.be.rejectedWith(/fungible\.FungibleDisallowsNesting/);
     });
   });
 
@@ -404,31 +365,21 @@
       const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
 
       // Try to create a nested token in the wrong collection
-      await expect(executeTransaction(
-        api, alice, 
-        api.tx.unique.createItem(
-          collectionFT, 
-          targetAddress, 
-          {Fungible: {Value: 10}},
-        )
-      ), 'while creating nested token').to.be.rejectedWith(/structure\.DepthLimit/);
+      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
+        collectionFT, 
+        targetAddress, 
+        {Fungible: {Value: 10}},
+      )), 'while creating nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
 
       // Try to create and nest a token in the wrong collection
       const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
-      await expect(executeTransaction(
-        api, alice, 
-        api.tx.unique.transfer(
-          normalizeAccountId({Ethereum: tokenIdToAddress(collectionFT, targetToken)}), collectionFT, newToken, 1,
-        ),
-      ), 'while nesting new token').to.be.rejectedWith(/fungible\.FungibleDisallowsNesting/);
+      await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
     });
   });
 
   it('Fungible: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async () => {
     await usingApi(async api => {
       const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionLimitsExpectSuccess(alice, collectionNFT, {nestingRule: {OwnerRestricted:[collectionNFT]}}); // todo clear redundant restrictions?
-
       await addToAllowListExpectSuccess(alice, collectionNFT, bob.address);
       await enableAllowListExpectSuccess(alice, collectionNFT);
       await enablePublicMintingExpectSuccess(alice, collectionNFT);
@@ -438,17 +389,18 @@
       const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
 
       const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+      await setCollectionLimitsExpectSuccess(alice, collectionNFT, {nestingRule: {OwnerRestricted:[collectionFT]}});
 
       // Try to create a nested token in the wrong collection
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
         collectionFT, 
         targetAddress, 
         {Fungible: {Value: 10}},
-      ))).to.be.rejected;
+      )), 'while creating nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
 
       // Try to create and nest a token in the wrong collection
       const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
-      await transferExpectFailure(collectionFT, newToken, alice, targetAddress, 1);
+      await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
     });
   });
 
@@ -468,11 +420,11 @@
         collectionFT, 
         targetAddress, 
         {Fungible: {Value: 10}},
-      ))).to.be.rejected;
+      )), 'while creating a nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
 
       // Try to create and nest a token in the wrong collection
       const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
-      await transferExpectFailure(collectionFT, newToken, alice, targetAddress, 1);
+      await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
     });
   });
 
@@ -492,12 +444,19 @@
         collectionRFT, 
         targetAddress, 
         {ReFungible: {const_data: [], pieces: 100}},
-      ))).to.be.rejectedWith(/^common\.NestingIsDisabled$/);
+      )), 'while creating a nested token').to.be.rejectedWith(/^common\.NestingIsDisabled$/);
 
       // Create a token to be nested
       const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
       // Try to nest
       await transferExpectFailure(collectionRFT, newToken, alice, targetAddress, 100);
+      // Try to nest
+      await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionRFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.NestingIsDisabled/);
+
+      // Create another token to be nested
+      const newToken2 = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
+      // Try to nest inside a fungible token
+      await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collectionRFT, newToken)}, collectionRFT, newToken2, 1)), 'while nesting new token inside refungible').to.be.rejectedWith(/refungible\.RefungibleDisallowsNesting/);
     });
   });
 
@@ -521,19 +480,17 @@
         collectionRFT, 
         targetAddress, 
         {ReFungible: {const_data: [], pieces: 100}},
-      ))).to.be.rejected;
+      )), 'while creating a nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
 
       // Try to create and nest a token in the wrong collection
       const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
-      await transferExpectFailure(collectionRFT, newToken, alice, targetAddress, 100);
+      await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionRFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
     });
   });
 
   it('ReFungible: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async () => {
     await usingApi(async api => {
       const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionLimitsExpectSuccess(alice, collectionNFT, {nestingRule: {OwnerRestricted:[collectionNFT]}});
-
       await addToAllowListExpectSuccess(alice, collectionNFT, bob.address);
       await enableAllowListExpectSuccess(alice, collectionNFT);
       await enablePublicMintingExpectSuccess(alice, collectionNFT);
@@ -543,17 +500,18 @@
       const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
 
       const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
+      await setCollectionLimitsExpectSuccess(alice, collectionNFT, {nestingRule: {OwnerRestricted:[collectionRFT]}});
 
       // Try to create a nested token in the wrong collection
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
         collectionRFT, 
         targetAddress, 
         {ReFungible: {const_data: [], pieces: 100}},
-      ))).to.be.rejected;
+      )), 'while creating a nested token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
 
       // Try to create and nest a token in the wrong collection
       const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
-      await transferExpectFailure(collectionRFT, newToken, alice, targetAddress, 100);
+      await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionRFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.OnlyOwnerAllowedToNest/);
     });
   });
 
@@ -573,11 +531,11 @@
         collectionRFT, 
         targetAddress, 
         {ReFungible: {const_data: [], pieces: 100}},
-      ))).to.be.rejected;
+      )), 'while creating a nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
 
       // Try to create and nest a token in the wrong collection
       const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
-      await transferExpectFailure(collectionRFT, newToken, alice, targetAddress, 100);
+      await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionRFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
     });
   });
 });
modifiedtests/src/nesting/properties.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/properties.test.ts
+++ b/tests/src/nesting/properties.test.ts
@@ -18,7 +18,7 @@
 
 describe('Integration Test: Collection Properties', () => {
   before(async () => {
-    await usingApi(async api => {
+    await usingApi(async () => {
       alice = privateKey('//Alice');
       bob = privateKey('//Bob');
     });
@@ -113,7 +113,7 @@
 
 describe('Negative Integration Test: Collection Properties', () => {
   before(async () => {
-    await usingApi(async api => {
+    await usingApi(async () => {
       alice = privateKey('//Alice');
       bob = privateKey('//Bob');
     });
@@ -213,13 +213,13 @@
         api, 
         alice, 
         api.tx.unique.setCollectionProperties(collection, [{key: '', value: 'nothing must not exist'}]), 
-      ), `on rejecting an unnamed property`).to.be.rejectedWith(/common\.EmptyPropertyKey/);
+      ), 'on rejecting an unnamed property').to.be.rejectedWith(/common\.EmptyPropertyKey/);
 
       await expect(executeTransaction(
         api, 
         alice, 
         api.tx.unique.setCollectionProperties(collection, [
-          {key: 'CRISPR-Cas9', value: 'rewriting nature!'}
+          {key: 'CRISPR-Cas9', value: 'rewriting nature!'},
         ]), 
       ), 'on setting the correctly-but-still-badly-named property').to.not.be.rejected;
 
@@ -245,7 +245,7 @@
 
 describe('Integration Test: Access Rights to Token Properties', () => {
   before(async () => {
-    await usingApi(async api => {
+    await usingApi(async () => {
       alice = privateKey('//Alice');
       bob = privateKey('//Bob');
     });
@@ -311,7 +311,7 @@
 
 describe('Negative Integration Test: Access Rights to Token Properties', () => {
   before(async () => {
-    await usingApi(async api => {
+    await usingApi(async () => {
       alice = privateKey('//Alice');
       bob = privateKey('//Bob');
     });
@@ -400,7 +400,7 @@
         api, 
         alice, 
         api.tx.unique.setPropertyPermissions(collection, [{key: '', permission: {}}]), 
-      ), `on rejecting an unnamed property`).to.be.rejectedWith(/common\.EmptyPropertyKey/);
+      ), 'on rejecting an unnamed property').to.be.rejectedWith(/common\.EmptyPropertyKey/);
 
       const correctKey = '--0x03116e387820CA05'; // PolkadotJS would parse this as an already encoded hex-string
       await expect(executeTransaction(
@@ -429,7 +429,7 @@
   let permissions: {permission: any, signers: IKeyringPair[]}[];
 
   before(async () => {
-    await usingApi(async api => {
+    await usingApi(async () => {
       alice = privateKey('//Alice');
       bob = privateKey('//Bob');
       charlie = privateKey('//Charlie');
@@ -446,10 +446,12 @@
   });
 
   beforeEach(async () => {
-    collection = await createCollectionExpectSuccess();
-    token = await createItemExpectSuccess(alice, collection, 'NFT');
-    await addCollectionAdminExpectSuccess(alice, collection, bob.address);
-    await transferExpectSuccess(collection, token, alice, charlie);
+    await usingApi(async () => {
+      collection = await createCollectionExpectSuccess();
+      token = await createItemExpectSuccess(alice, collection, 'NFT');
+      await addCollectionAdminExpectSuccess(alice, collection, bob.address);
+      await transferExpectSuccess(collection, token, alice, charlie);
+    });
   });
   
   it('Reads yet empty properties of a token', async () => {
@@ -592,7 +594,7 @@
   let constitution: {permission: any, signers: IKeyringPair[], sinner: IKeyringPair}[];
 
   before(async () => {
-    await usingApi(async api => {
+    await usingApi(async () => {
       alice = privateKey('//Alice');
       bob = privateKey('//Bob');
       charlie = privateKey('//Charlie');
modifiedtests/src/nesting/unnest.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/unnest.test.ts
+++ b/tests/src/nesting/unnest.test.ts
@@ -4,11 +4,9 @@
 import usingApi, {executeTransaction} from '../substrate/substrate-api';
 import {
   createCollectionExpectSuccess,
-  createItemExpectFailure,
   createItemExpectSuccess,
   getBalance,
   getTokenOwner,
-  getTopmostTokenOwner,
   normalizeAccountId,
   setCollectionLimitsExpectSuccess,
   transferExpectSuccess,
@@ -21,7 +19,7 @@
 
 describe('Integration Test: Unnesting', () => {
   before(async () => {
-    await usingApi(async api => {
+    await usingApi(async () => {
       alice = privateKey('//Alice');
       bob = privateKey('//Bob');
     });
@@ -112,7 +110,7 @@
 
 describe('Negative Test: Unnesting', () => {
   before(async () => {
-    await usingApi(async api => {
+    await usingApi(async () => {
       alice = privateKey('//Alice');
       bob = privateKey('//Bob');
     });
@@ -133,7 +131,7 @@
         api,
         bob,
         api.tx.unique.transferFrom(normalizeAccountId(targetAddress), normalizeAccountId(bob), collection, nestedToken, 1),
-      ), 'while unnesting').to.be.rejectedWith(/^structure\.DepthLimit$/); // todo ApprovedValueTooLow?
+      ), 'while unnesting').to.be.rejectedWith(/^common\.ApprovedValueTooLow$/);
       expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
 
       // Try to burn
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
before · tests/src/util/helpers.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 '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';27import privateKey from '../substrate/privateKey';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection} from '@polkadot/types/lookup';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36  Substrate: string,37} | {38  Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42  if (typeof input === 'string') {43    if (input.length === 48 || input.length === 47) {44      return {Substrate: input};45    } else if (input.length === 42 && input.startsWith('0x')) {46      return {Ethereum: input.toLowerCase()};47    } else if (input.length === 40 && !input.startsWith('0x')) {48      return {Ethereum: '0x' + input.toLowerCase()};49    } else {50      throw new Error(`Unknown address format: "${input}"`);51    }52  }53  if ('address' in input) {54    return {Substrate: input.address};55  }56  if ('Ethereum' in input) {57    return {58      Ethereum: input.Ethereum.toLowerCase(),59    };60  } else if ('ethereum' in input) {61    return {62      Ethereum: (input as any).ethereum.toLowerCase(),63    };64  } else if ('Substrate' in input) {65    return input;66  } else if ('substrate' in input) {67    return {68      Substrate: (input as any).substrate,69    };70  }7172  // AccountId73  return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76  input = normalizeAccountId(input);77  if ('Substrate' in input) {78    return input.Substrate;79  } else {80    return evmToAddress(input.Ethereum);81  }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091type GenericResult = {92  success: boolean,93};9495interface CreateCollectionResult {96  success: boolean;97  collectionId: number;98}99100interface CreateItemResult {101  success: boolean;102  collectionId: number;103  itemId: number;104  recipient?: CrossAccountId;105}106107interface TransferResult {108  collectionId: number;109  itemId: number;110  sender?: CrossAccountId;111  recipient?: CrossAccountId;112  value: bigint;113}114115interface IReFungibleOwner {116  fraction: BN;117  owner: number[];118}119120interface IGetMessage {121  checkMsgUnqMethod: string;122  checkMsgTrsMethod: string;123  checkMsgSysMethod: string;124}125126export interface IFungibleTokenDataType {127  value: number;128}129130export interface IChainLimits {131  collectionNumbersLimit: number;132  accountTokenOwnershipLimit: number;133  collectionsAdminsLimit: number;134  customDataLimit: number;135  nftSponsorTransferTimeout: number;136  fungibleSponsorTransferTimeout: number;137  refungibleSponsorTransferTimeout: number;138  offchainSchemaLimit: number;139  constOnChainSchemaLimit: number;140}141142export interface IReFungibleTokenDataType {143  owner: IReFungibleOwner[];144  constData: number[];145  variableData: number[];146}147148export function uniqueEventMessage(events: EventRecord[]): IGetMessage {149  let checkMsgUnqMethod = '';150  let checkMsgTrsMethod = '';151  let checkMsgSysMethod = '';152  events.forEach(({event: {method, section}}) => {153    if (section === 'common') {154      checkMsgUnqMethod = method;155    } else if (section === 'treasury') {156      checkMsgTrsMethod = method;157    } else if (section === 'system') {158      checkMsgSysMethod = method;159    } else { return null; }160  });161  const result: IGetMessage = {162    checkMsgUnqMethod,163    checkMsgTrsMethod,164    checkMsgSysMethod,165  };166  return result;167}168169export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {170  const event = events.find(r => check(r.event));171  if (!event) return;172  return event.event as T;173}174175export function getGenericResult(events: EventRecord[]): GenericResult {176  const result: GenericResult = {177    success: false,178  };179  events.forEach(({event: {method}}) => {180    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);181    if (method === 'ExtrinsicSuccess') {182      result.success = true;183    }184  });185  return result;186}187188189190export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {191  let success = false;192  let collectionId = 0;193  events.forEach(({event: {data, method, section}}) => {194    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);195    if (method == 'ExtrinsicSuccess') {196      success = true;197    } else if ((section == 'common') && (method == 'CollectionCreated')) {198      collectionId = parseInt(data[0].toString(), 10);199    }200  });201  const result: CreateCollectionResult = {202    success,203    collectionId,204  };205  return result;206}207208export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {209  let success = false;210  let collectionId = 0;211  let itemId = 0;212  let recipient;213214  const results : CreateItemResult[]  = [];215216  events.forEach(({event: {data, method, section}}) => {217    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);218    if (method == 'ExtrinsicSuccess') {219      success = true;220    } else if ((section == 'common') && (method == 'ItemCreated')) {221      collectionId = parseInt(data[0].toString(), 10);222      itemId = parseInt(data[1].toString(), 10);223      recipient = normalizeAccountId(data[2].toJSON() as any);224225      const itemRes: CreateItemResult = {226        success,227        collectionId,228        itemId,229        recipient,230      };231232      results.push(itemRes);233    }234  });235236  return results;237}238239export function getCreateItemResult(events: EventRecord[]): CreateItemResult {240  let success = false;241  let collectionId = 0;242  let itemId = 0;243  let recipient;244  events.forEach(({event: {data, method, section}}) => {245    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);246    if (method == 'ExtrinsicSuccess') {247      success = true;248    } else if ((section == 'common') && (method == 'ItemCreated')) {249      collectionId = parseInt(data[0].toString(), 10);250      itemId = parseInt(data[1].toString(), 10);251      recipient = normalizeAccountId(data[2].toJSON() as any);252    }253  });254  const result: CreateItemResult = {255    success,256    collectionId,257    itemId,258    recipient,259  };260  return result;261}262263export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {264  for (const {event} of events) {265    if (api.events.common.Transfer.is(event)) {266      const [collection, token, sender, recipient, value] = event.data;267      return {268        collectionId: collection.toNumber(),269        itemId: token.toNumber(),270        sender: normalizeAccountId(sender.toJSON() as any),271        recipient: normalizeAccountId(recipient.toJSON() as any),272        value: value.toBigInt(),273      };274    }275  }276  throw new Error('no transfer event');277}278279interface Nft {280  type: 'NFT';281}282283interface Fungible {284  type: 'Fungible';285  decimalPoints: number;286}287288interface ReFungible {289  type: 'ReFungible';290}291292type CollectionMode = Nft | Fungible | ReFungible;293294export type Property = {295  key: any,296  value: any,297};298299type PropertyPermission = {300  key: any,301  mutable: boolean;302  collectionAdmin: boolean;303  tokenOwner: boolean;304}305306export type CreateCollectionParams = {307  mode: CollectionMode,308  name: string,309  description: string,310  tokenPrefix: string,311  schemaVersion: string,312  properties?: Array<Property>,313  propPerm?: Array<PropertyPermission>314};315316const defaultCreateCollectionParams: CreateCollectionParams = {317  description: 'description',318  mode: {type: 'NFT'},319  name: 'name',320  tokenPrefix: 'prefix',321  schemaVersion: 'ImageURL',322};323324export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {325  const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};326327  let collectionId = 0;328  await usingApi(async (api) => {329    // Get number of collections before the transaction330    const collectionCountBefore = await getCreatedCollectionCount(api);331332    // Run the CreateCollection transaction333    const alicePrivateKey = privateKey('//Alice');334335    let modeprm = {};336    if (mode.type === 'NFT') {337      modeprm = {nft: null};338    } else if (mode.type === 'Fungible') {339      modeprm = {fungible: mode.decimalPoints};340    } else if (mode.type === 'ReFungible') {341      modeprm = {refungible: null};342    }343344    const tx = api.tx.unique.createCollectionEx({345      name: strToUTF16(name),346      description: strToUTF16(description),347      tokenPrefix: strToUTF16(tokenPrefix),348      mode: modeprm as any,349      schemaVersion: schemaVersion,350    });351    const events = await submitTransactionAsync(alicePrivateKey, tx);352    const result = getCreateCollectionResult(events);353354    // Get number of collections after the transaction355    const collectionCountAfter = await getCreatedCollectionCount(api);356357    // Get the collection358    const collection = await queryCollectionExpectSuccess(api, result.collectionId);359360    // What to expect361    // tslint:disable-next-line:no-unused-expression362    expect(result.success).to.be.true;363    expect(result.collectionId).to.be.equal(collectionCountAfter);364    // tslint:disable-next-line:no-unused-expression365    expect(collection).to.be.not.null;366    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');367    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));368    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);369    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);370    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);371372    collectionId = result.collectionId;373  });374375  return collectionId;376}377378export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {379  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};380381  let collectionId = 0;382  await usingApi(async (api) => {383    // Get number of collections before the transaction384    const collectionCountBefore = await getCreatedCollectionCount(api);385386    // Run the CreateCollection transaction387    const alicePrivateKey = privateKey('//Alice');388389    let modeprm = {};390    if (mode.type === 'NFT') {391      modeprm = {nft: null};392    } else if (mode.type === 'Fungible') {393      modeprm = {fungible: mode.decimalPoints};394    } else if (mode.type === 'ReFungible') {395      modeprm = {refungible: null};396    }397398    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});399    const events = await submitTransactionAsync(alicePrivateKey, tx);400    const result = getCreateCollectionResult(events);401402    // Get number of collections after the transaction403    const collectionCountAfter = await getCreatedCollectionCount(api);404405    // Get the collection406    const collection = await queryCollectionExpectSuccess(api, result.collectionId);407408    // What to expect409    // tslint:disable-next-line:no-unused-expression410    expect(result.success).to.be.true;411    expect(result.collectionId).to.be.equal(collectionCountAfter);412    // tslint:disable-next-line:no-unused-expression413    expect(collection).to.be.not.null;414    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');415    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));416    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);417    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);418    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);419420421    collectionId = result.collectionId;422  });423424  return collectionId;425}426427export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {428  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};429430  const collectionId = 0;431  await usingApi(async (api) => {432    // Get number of collections before the transaction433    const collectionCountBefore = await getCreatedCollectionCount(api);434435    // Run the CreateCollection transaction436    const alicePrivateKey = privateKey('//Alice');437438    let modeprm = {};439    if (mode.type === 'NFT') {440      modeprm = {nft: null};441    } else if (mode.type === 'Fungible') {442      modeprm = {fungible: mode.decimalPoints};443    } else if (mode.type === 'ReFungible') {444      modeprm = {refungible: null};445    }446447    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});448    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;449450451    // Get number of collections after the transaction452    const collectionCountAfter = await getCreatedCollectionCount(api);453454    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');455  });456}457458export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {459  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};460461  let modeprm = {};462  if (mode.type === 'NFT') {463    modeprm = {nft: null};464  } else if (mode.type === 'Fungible') {465    modeprm = {fungible: mode.decimalPoints};466  } else if (mode.type === 'ReFungible') {467    modeprm = {refungible: null};468  }469470  await usingApi(async (api) => {471    // Get number of collections before the transaction472    const collectionCountBefore = await getCreatedCollectionCount(api);473474    // Run the CreateCollection transaction475    const alicePrivateKey = privateKey('//Alice');476    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});477    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;478479    // Get number of collections after the transaction480    const collectionCountAfter = await getCreatedCollectionCount(api);481482    // What to expect483    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');484  });485}486487export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {488  let bal = 0n;489  let unused;490  do {491    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;492    const keyring = new Keyring({type: 'sr25519'});493    unused = keyring.addFromUri(`//${randomSeed}`);494    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();495  } while (bal !== 0n);496  return unused;497}498499export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {500  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();501}502503export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {504  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));505}506507export async function findNotExistingCollection(api: ApiPromise): Promise<number> {508  const totalNumber = await getCreatedCollectionCount(api);509  const newCollection: number = totalNumber + 1;510  return newCollection;511}512513function getDestroyResult(events: EventRecord[]): boolean {514  let success = false;515  events.forEach(({event: {method}}) => {516    if (method == 'ExtrinsicSuccess') {517      success = true;518    }519  });520  return success;521}522523export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {524  await usingApi(async (api) => {525    // Run the DestroyCollection transaction526    const alicePrivateKey = privateKey(senderSeed);527    const tx = api.tx.unique.destroyCollection(collectionId);528    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;529  });530}531532export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {533  await usingApi(async (api) => {534    // Run the DestroyCollection transaction535    const alicePrivateKey = privateKey(senderSeed);536    const tx = api.tx.unique.destroyCollection(collectionId);537    const events = await submitTransactionAsync(alicePrivateKey, tx);538    const result = getDestroyResult(events);539    expect(result).to.be.true;540541    // What to expect542    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;543  });544}545546export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {547  await usingApi(async (api) => {548    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);549    const events = await submitTransactionAsync(sender, tx);550    const result = getGenericResult(events);551552    expect(result.success).to.be.true;553  });554}555556export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {557  await usingApi(async (api) => {558    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);559    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;560    const result = getGenericResult(events);561562    expect(result.success).to.be.false;563  });564}565566export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {567  await usingApi(async (api) => {568569    // Run the transaction570    const senderPrivateKey = privateKey(sender);571    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);572    const events = await submitTransactionAsync(senderPrivateKey, tx);573    const result = getGenericResult(events);574575    // Get the collection576    const collection = await queryCollectionExpectSuccess(api, collectionId);577578    // What to expect579    expect(result.success).to.be.true;580    expect(collection.sponsorship.toJSON()).to.deep.equal({581      unconfirmed: sponsor,582    });583  });584}585586export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {587  await usingApi(async (api) => {588589    // Run the transaction590    const alicePrivateKey = privateKey(sender);591    const tx = api.tx.unique.removeCollectionSponsor(collectionId);592    const events = await submitTransactionAsync(alicePrivateKey, tx);593    const result = getGenericResult(events);594595    // Get the collection596    const collection = await queryCollectionExpectSuccess(api, collectionId);597598    // What to expect599    expect(result.success).to.be.true;600    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});601  });602}603604export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {605  await usingApi(async (api) => {606607    // Run the transaction608    const alicePrivateKey = privateKey(senderSeed);609    const tx = api.tx.unique.removeCollectionSponsor(collectionId);610    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;611  });612}613614export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {615  await usingApi(async (api) => {616617    // Run the transaction618    const alicePrivateKey = privateKey(senderSeed);619    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);620    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;621  });622}623624export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {625  await usingApi(async (api) => {626627    // Run the transaction628    const sender = privateKey(senderSeed);629    const tx = api.tx.unique.confirmSponsorship(collectionId);630    const events = await submitTransactionAsync(sender, tx);631    const result = getGenericResult(events);632633    // Get the collection634    const collection = await queryCollectionExpectSuccess(api, collectionId);635636    // What to expect637    expect(result.success).to.be.true;638    expect(collection.sponsorship.toJSON()).to.be.deep.equal({639      confirmed: sender.address,640    });641  });642}643644645export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {646  await usingApi(async (api) => {647648    // Run the transaction649    const sender = privateKey(senderSeed);650    const tx = api.tx.unique.confirmSponsorship(collectionId);651    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;652  });653}654655export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {656657  await usingApi(async (api) => {658    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);659    const events = await submitTransactionAsync(sender, tx);660    const result = getGenericResult(events);661662    expect(result.success).to.be.true;663  });664}665666export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {667668  await usingApi(async (api) => {669    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);670    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;671    const result = getGenericResult(events);672673    expect(result.success).to.be.false;674  });675}676677export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {678  await usingApi(async (api) => {679    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);680    const events = await submitTransactionAsync(sender, tx);681    const result = getGenericResult(events);682683    expect(result.success).to.be.true;684  });685}686687export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {688  await usingApi(async (api) => {689    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);690    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;691    const result = getGenericResult(events);692693    expect(result.success).to.be.false;694  });695}696697export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {698699  await usingApi(async (api) => {700701    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);702    const events = await submitTransactionAsync(sender, tx);703    const result = getGenericResult(events);704705    expect(result.success).to.be.true;706  });707}708709export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {710711  await usingApi(async (api) => {712713    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);714    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;715    const result = getGenericResult(events);716717    expect(result.success).to.be.false;718  });719}720721export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {722  await usingApi(async (api) => {723    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);724    const events = await submitTransactionAsync(sender, tx);725    const result = getGenericResult(events);726727    expect(result.success).to.be.true;728  });729}730731export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {732  await usingApi(async (api) => {733    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);734    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;735    const result = getGenericResult(events);736737    expect(result.success).to.be.false;738  });739}740741export async function getNextSponsored(742  api: ApiPromise,743  collectionId: number,744  account: string | CrossAccountId,745  tokenId: number,746): Promise<number> {747  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));748}749750export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {751  await usingApi(async (api) => {752    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);753    const events = await submitTransactionAsync(sender, tx);754    const result = getGenericResult(events);755756    expect(result.success).to.be.true;757  });758}759760export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {761  let allowlisted = false;762  await usingApi(async (api) => {763    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;764  });765  return allowlisted;766}767768export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {769  await usingApi(async (api) => {770    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());771    const events = await submitTransactionAsync(sender, tx);772    const result = getGenericResult(events);773774    expect(result.success).to.be.true;775  });776}777778export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {779  await usingApi(async (api) => {780    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());781    const events = await submitTransactionAsync(sender, tx);782    const result = getGenericResult(events);783784    expect(result.success).to.be.true;785  });786}787788export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {789  await usingApi(async (api) => {790    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());791    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;792    const result = getGenericResult(events);793794    expect(result.success).to.be.false;795  });796}797798export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {799  await usingApi(async (api) => {800    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));801    const events = await submitTransactionAsync(sender, tx);802    const result = getGenericResult(events);803804    expect(result.success).to.be.true;805  });806}807808export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {809  await usingApi(async (api) => {810    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));811    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;812  });813}814815export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {816  await usingApi(async (api) => {817    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));818    const events = await submitTransactionAsync(sender, tx);819    const result = getGenericResult(events);820821    expect(result.success).to.be.true;822  });823}824825export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {826  await usingApi(async (api) => {827    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));828    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;829  });830}831832export interface CreateFungibleData {833  readonly Value: bigint;834}835836export interface CreateReFungibleData { }837export interface CreateNftData { }838839export type CreateItemData = {840  NFT: CreateNftData;841} | {842  Fungible: CreateFungibleData;843} | {844  ReFungible: CreateReFungibleData;845};846847export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {848  await usingApi(async (api) => {849    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);850    // if burning token by admin - use adminButnItemExpectSuccess851    expect(balanceBefore >= BigInt(value)).to.be.true;852853    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);854    const events = await submitTransactionAsync(sender, tx);855    const result = getGenericResult(events);856    expect(result.success).to.be.true;857858    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);859    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);860  });861}862863export async function864approveExpectSuccess(865  collectionId: number,866  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,867) {868  await usingApi(async (api: ApiPromise) => {869    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);870    const events = await submitTransactionAsync(owner, approveUniqueTx);871    const result = getGenericResult(events);872    expect(result.success).to.be.true;873874    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));875  });876}877878export async function adminApproveFromExpectSuccess(879  collectionId: number,880  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,881) {882  await usingApi(async (api: ApiPromise) => {883    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);884    const events = await submitTransactionAsync(admin, approveUniqueTx);885    const result = getGenericResult(events);886    expect(result.success).to.be.true;887888    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));889  });890}891892export async function893transferFromExpectSuccess(894  collectionId: number,895  tokenId: number,896  accountApproved: IKeyringPair,897  accountFrom: IKeyringPair | CrossAccountId,898  accountTo: IKeyringPair | CrossAccountId,899  value: number | bigint = 1,900  type = 'NFT',901) {902  await usingApi(async (api: ApiPromise) => {903    const from = normalizeAccountId(accountFrom);904    const to = normalizeAccountId(accountTo);905    let balanceBefore = 0n;906    if (type === 'Fungible' || type === 'ReFungible') {907      balanceBefore = await getBalance(api, collectionId, to, tokenId);908    }909    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);910    const events = await submitTransactionAsync(accountApproved, transferFromTx);911    const result = getCreateItemResult(events);912    // tslint:disable-next-line:no-unused-expression913    expect(result.success).to.be.true;914    if (type === 'NFT') {915      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);916    }917    if (type === 'Fungible') {918      const balanceAfter = await getBalance(api, collectionId, to, tokenId);919      if (JSON.stringify(to) !== JSON.stringify(from)) {920        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));921      } else {922        expect(balanceAfter).to.be.equal(balanceBefore);923      }924    }925    if (type === 'ReFungible') {926      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));927    }928  });929}930931export async function932transferFromExpectFail(933  collectionId: number,934  tokenId: number,935  accountApproved: IKeyringPair,936  accountFrom: IKeyringPair,937  accountTo: IKeyringPair,938  value: number | bigint = 1,939) {940  await usingApi(async (api: ApiPromise) => {941    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);942    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;943    const result = getCreateCollectionResult(events);944    // tslint:disable-next-line:no-unused-expression945    expect(result.success).to.be.false;946  });947}948949/* eslint no-async-promise-executor: "off" */950async function getBlockNumber(api: ApiPromise): Promise<number> {951  return new Promise<number>(async (resolve) => {952    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {953      unsubscribe();954      resolve(head.number.toNumber());955    });956  });957}958959export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {960  await usingApi(async (api) => {961    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));962    const events = await submitTransactionAsync(sender, changeAdminTx);963    const result = getCreateCollectionResult(events);964    expect(result.success).to.be.true;965  });966}967968export async function969getFreeBalance(account: IKeyringPair): Promise<bigint> {970  let balance = 0n;971  await usingApi(async (api) => {972    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());973  });974975  return balance;976}977978export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {979  const tx = api.tx.balances.transfer(target, amount);980  const events = await submitTransactionAsync(source, tx);981  const result = getGenericResult(events);982  expect(result.success).to.be.true;983}984985export async function986scheduleTransferExpectSuccess(987  collectionId: number,988  tokenId: number,989  sender: IKeyringPair,990  recipient: IKeyringPair,991  value: number | bigint = 1,992  blockSchedule: number,993) {994  await usingApi(async (api: ApiPromise) => {995    const blockNumber: number | undefined = await getBlockNumber(api);996    const expectedBlockNumber = blockNumber + blockSchedule;997998    expect(blockNumber).to.be.greaterThan(0);999    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);1000    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);10011002    await submitTransactionAsync(sender, scheduleTx);10031004    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10051006    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));10071008    // sleep for 4 blocks1009    await waitNewBlocks(blockSchedule + 1);10101011    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10121013    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1014    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1015  });1016}101710181019export async function1020transferExpectSuccess(1021  collectionId: number,1022  tokenId: number,1023  sender: IKeyringPair,1024  recipient: IKeyringPair | CrossAccountId,1025  value: number | bigint = 1,1026  type = 'NFT',1027) {1028  await usingApi(async (api: ApiPromise) => {1029    const from = normalizeAccountId(sender);1030    const to = normalizeAccountId(recipient);10311032    let balanceBefore = 0n;1033    if (type === 'Fungible') {1034      balanceBefore = await getBalance(api, collectionId, to, tokenId);1035    }1036    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1037    const events = await executeTransaction(api, sender, transferTx);10381039    const result = getTransferResult(api, events);1040    expect(result.collectionId).to.be.equal(collectionId);1041    expect(result.itemId).to.be.equal(tokenId);1042    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1043    expect(result.recipient).to.be.deep.equal(to);1044    expect(result.value).to.be.equal(BigInt(value));10451046    if (type === 'NFT') {1047      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1048    }1049    if (type === 'Fungible') {1050      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1051      if (JSON.stringify(to) !== JSON.stringify(from)) {1052        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1053      } else {1054        expect(balanceAfter).to.be.equal(balanceBefore);1055      }1056    }1057    if (type === 'ReFungible') {1058      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1059    }1060  });1061}10621063export async function1064transferExpectFailure(1065  collectionId: number,1066  tokenId: number,1067  sender: IKeyringPair,1068  recipient: IKeyringPair | CrossAccountId,1069  value: number | bigint = 1,1070) {1071  await usingApi(async (api: ApiPromise) => {1072    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1073    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1074    const result = getGenericResult(events);1075    // if (events && Array.isArray(events)) {1076    //   const result = getCreateCollectionResult(events);1077    // tslint:disable-next-line:no-unused-expression1078    expect(result.success).to.be.false;1079    //}1080  });1081}10821083export async function1084approveExpectFail(1085  collectionId: number,1086  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1087) {1088  await usingApi(async (api: ApiPromise) => {1089    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1090    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1091    const result = getCreateCollectionResult(events);1092    // tslint:disable-next-line:no-unused-expression1093    expect(result.success).to.be.false;1094  });1095}10961097export async function getBalance(1098  api: ApiPromise,1099  collectionId: number,1100  owner: string | CrossAccountId,1101  token: number,1102): Promise<bigint> {1103  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1104}1105export async function getTokenOwner(1106  api: ApiPromise,1107  collectionId: number,1108  token: number,1109): Promise<CrossAccountId> {1110  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1111  if (owner == null) throw new Error('owner == null');1112  return normalizeAccountId(owner);1113}1114export async function getTopmostTokenOwner(1115  api: ApiPromise,1116  collectionId: number,1117  token: number,1118): Promise<CrossAccountId> {1119  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1120  if (owner == null) throw new Error('owner == null');1121  return normalizeAccountId(owner);1122}1123export async function isTokenExists(1124  api: ApiPromise,1125  collectionId: number,1126  token: number,1127): Promise<boolean> {1128  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1129}1130export async function getLastTokenId(1131  api: ApiPromise,1132  collectionId: number,1133): Promise<number> {1134  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1135}1136export async function getAdminList(1137  api: ApiPromise,1138  collectionId: number,1139): Promise<string[]> {1140  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1141}1142export async function getVariableMetadata(1143  api: ApiPromise,1144  collectionId: number,1145  tokenId: number,1146): Promise<number[]> {1147  return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1148}1149export async function getConstMetadata(1150  api: ApiPromise,1151  collectionId: number,1152  tokenId: number,1153): Promise<number[]> {1154  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1155}11561157export async function createFungibleItemExpectSuccess(1158  sender: IKeyringPair,1159  collectionId: number,1160  data: CreateFungibleData,1161  owner: CrossAccountId | string = sender.address,1162) {1163  return await usingApi(async (api) => {1164    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11651166    const events = await submitTransactionAsync(sender, tx);1167    const result = getCreateItemResult(events);11681169    expect(result.success).to.be.true;1170    return result.itemId;1171  });1172}11731174export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1175  let newItemId = 0;1176  await usingApi(async (api) => {1177    const to = normalizeAccountId(owner);1178    const itemCountBefore = await getLastTokenId(api, collectionId);1179    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11801181    let tx;1182    if (createMode === 'Fungible') {1183      const createData = {fungible: {value: 10}};1184      tx = api.tx.unique.createItem(collectionId, to, createData as any);1185    } else if (createMode === 'ReFungible') {1186      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1187      tx = api.tx.unique.createItem(collectionId, to, createData as any);1188    } else {1189      const createData = {nft: {const_data: [], variable_data: []}};1190      tx = api.tx.unique.createItem(collectionId, to, createData as any);1191    }11921193    const events = await submitTransactionAsync(sender, tx);1194    const result = getCreateItemResult(events);11951196    const itemCountAfter = await getLastTokenId(api, collectionId);1197    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11981199    // What to expect1200    // tslint:disable-next-line:no-unused-expression1201    expect(result.success).to.be.true;1202    if (createMode === 'Fungible') {1203      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1204    } else {1205      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1206    }1207    expect(collectionId).to.be.equal(result.collectionId);1208    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1209    expect(to).to.be.deep.equal(result.recipient);1210    newItemId = result.itemId;1211  });1212  return newItemId;1213}12141215export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1216  await usingApi(async (api) => {1217    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);12181219    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1220    const result = getCreateItemResult(events);12211222    expect(result.success).to.be.false;1223  });1224}12251226export async function setPublicAccessModeExpectSuccess(1227  sender: IKeyringPair, collectionId: number,1228  accessMode: 'Normal' | 'AllowList',1229) {1230  await usingApi(async (api) => {12311232    // Run the transaction1233    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1234    const events = await submitTransactionAsync(sender, tx);1235    const result = getGenericResult(events);12361237    // Get the collection1238    const collection = await queryCollectionExpectSuccess(api, collectionId);12391240    // What to expect1241    // tslint:disable-next-line:no-unused-expression1242    expect(result.success).to.be.true;1243    expect(collection.access.toHuman()).to.be.equal(accessMode);1244  });1245}12461247export async function setPublicAccessModeExpectFail(1248  sender: IKeyringPair, collectionId: number,1249  accessMode: 'Normal' | 'AllowList',1250) {1251  await usingApi(async (api) => {12521253    // Run the transaction1254    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1255    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1256    const result = getGenericResult(events);12571258    // What to expect1259    // tslint:disable-next-line:no-unused-expression1260    expect(result.success).to.be.false;1261  });1262}12631264export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1265  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1266}12671268export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1269  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1270}12711272export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1273  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1274}12751276export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1277  await usingApi(async (api) => {12781279    // Run the transaction1280    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1281    const events = await submitTransactionAsync(sender, tx);1282    const result = getGenericResult(events);1283    expect(result.success).to.be.true;12841285    // Get the collection1286    const collection = await queryCollectionExpectSuccess(api, collectionId);12871288    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1289  });1290}12911292export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1293  await setMintPermissionExpectSuccess(sender, collectionId, true);1294}12951296export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1297  await usingApi(async (api) => {1298    // Run the transaction1299    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1300    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1301    const result = getCreateCollectionResult(events);1302    // tslint:disable-next-line:no-unused-expression1303    expect(result.success).to.be.false;1304  });1305}13061307export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1308  await usingApi(async (api) => {1309    // Run the transaction1310    const tx = api.tx.unique.setChainLimits(limits);1311    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1312    const result = getCreateCollectionResult(events);1313    // tslint:disable-next-line:no-unused-expression1314    expect(result.success).to.be.false;1315  });1316}13171318export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1319  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1320}13211322export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1323  await usingApi(async (api) => {1324    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;13251326    // Run the transaction1327    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1328    const events = await submitTransactionAsync(sender, tx);1329    const result = getGenericResult(events);1330    expect(result.success).to.be.true;13311332    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1333  });1334}13351336export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1337  await usingApi(async (api) => {13381339    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;13401341    // Run the transaction1342    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1343    const events = await submitTransactionAsync(sender, tx);1344    const result = getGenericResult(events);1345    expect(result.success).to.be.true;13461347    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1348  });1349}13501351export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1352  await usingApi(async (api) => {13531354    // Run the transaction1355    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1356    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1357    const result = getGenericResult(events);13581359    // What to expect1360    // tslint:disable-next-line:no-unused-expression1361    expect(result.success).to.be.false;1362  });1363}13641365export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1366  await usingApi(async (api) => {1367    // Run the transaction1368    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1369    const events = await submitTransactionAsync(sender, tx);1370    const result = getGenericResult(events);13711372    // What to expect1373    // tslint:disable-next-line:no-unused-expression1374    expect(result.success).to.be.true;1375  });1376}13771378export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1379  await usingApi(async (api) => {1380    // Run the transaction1381    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1382    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1383    const result = getGenericResult(events);13841385    // What to expect1386    // tslint:disable-next-line:no-unused-expression1387    expect(result.success).to.be.false;1388  });1389}13901391export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1392  : Promise<UpDataStructsRpcCollection | null> => {1393  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1394};13951396export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1397  // set global object - collectionsCount1398  return (await api.rpc.unique.collectionStats()).created.toNumber();1399};14001401export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1402  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1403}14041405export async function waitNewBlocks(blocksCount = 1): Promise<void> {1406  await usingApi(async (api) => {1407    const promise = new Promise<void>(async (resolve) => {1408      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1409        if (blocksCount > 0) {1410          blocksCount--;1411        } else {1412          unsubscribe();1413          resolve();1414        }1415      });1416    });1417    return promise;1418  });1419}
after · tests/src/util/helpers.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 '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';27import privateKey from '../substrate/privateKey';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection} from '@polkadot/types/lookup';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36  Substrate: string,37} | {38  Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42  if (typeof input === 'string') {43    if (input.length === 48 || input.length === 47) {44      return {Substrate: input};45    } else if (input.length === 42 && input.startsWith('0x')) {46      return {Ethereum: input.toLowerCase()};47    } else if (input.length === 40 && !input.startsWith('0x')) {48      return {Ethereum: '0x' + input.toLowerCase()};49    } else {50      throw new Error(`Unknown address format: "${input}"`);51    }52  }53  if ('address' in input) {54    return {Substrate: input.address};55  }56  if ('Ethereum' in input) {57    return {58      Ethereum: input.Ethereum.toLowerCase(),59    };60  } else if ('ethereum' in input) {61    return {62      Ethereum: (input as any).ethereum.toLowerCase(),63    };64  } else if ('Substrate' in input) {65    return input;66  } else if ('substrate' in input) {67    return {68      Substrate: (input as any).substrate,69    };70  }7172  // AccountId73  return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76  input = normalizeAccountId(input);77  if ('Substrate' in input) {78    return input.Substrate;79  } else {80    return evmToAddress(input.Ethereum);81  }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091type GenericResult = {92  success: boolean,93};9495interface CreateCollectionResult {96  success: boolean;97  collectionId: number;98}99100interface CreateItemResult {101  success: boolean;102  collectionId: number;103  itemId: number;104  recipient?: CrossAccountId;105}106107interface TransferResult {108  collectionId: number;109  itemId: number;110  sender?: CrossAccountId;111  recipient?: CrossAccountId;112  value: bigint;113}114115interface IReFungibleOwner {116  fraction: BN;117  owner: number[];118}119120interface IGetMessage {121  checkMsgUnqMethod: string;122  checkMsgTrsMethod: string;123  checkMsgSysMethod: string;124}125126export interface IFungibleTokenDataType {127  value: number;128}129130export interface IChainLimits {131  collectionNumbersLimit: number;132  accountTokenOwnershipLimit: number;133  collectionsAdminsLimit: number;134  customDataLimit: number;135  nftSponsorTransferTimeout: number;136  fungibleSponsorTransferTimeout: number;137  refungibleSponsorTransferTimeout: number;138  offchainSchemaLimit: number;139  constOnChainSchemaLimit: number;140}141142export interface IReFungibleTokenDataType {143  owner: IReFungibleOwner[];144  constData: number[];145  variableData: number[];146}147148export function uniqueEventMessage(events: EventRecord[]): IGetMessage {149  let checkMsgUnqMethod = '';150  let checkMsgTrsMethod = '';151  let checkMsgSysMethod = '';152  events.forEach(({event: {method, section}}) => {153    if (section === 'common') {154      checkMsgUnqMethod = method;155    } else if (section === 'treasury') {156      checkMsgTrsMethod = method;157    } else if (section === 'system') {158      checkMsgSysMethod = method;159    } else { return null; }160  });161  const result: IGetMessage = {162    checkMsgUnqMethod,163    checkMsgTrsMethod,164    checkMsgSysMethod,165  };166  return result;167}168169export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {170  const event = events.find(r => check(r.event));171  if (!event) return;172  return event.event as T;173}174175export function getGenericResult(events: EventRecord[]): GenericResult {176  const result: GenericResult = {177    success: false,178  };179  events.forEach(({event: {method}}) => {180    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);181    if (method === 'ExtrinsicSuccess') {182      result.success = true;183    }184  });185  return result;186}187188189190export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {191  let success = false;192  let collectionId = 0;193  events.forEach(({event: {data, method, section}}) => {194    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);195    if (method == 'ExtrinsicSuccess') {196      success = true;197    } else if ((section == 'common') && (method == 'CollectionCreated')) {198      collectionId = parseInt(data[0].toString(), 10);199    }200  });201  const result: CreateCollectionResult = {202    success,203    collectionId,204  };205  return result;206}207208export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {209  let success = false;210  let collectionId = 0;211  let itemId = 0;212  let recipient;213214  const results : CreateItemResult[]  = [];215216  events.forEach(({event: {data, method, section}}) => {217    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);218    if (method == 'ExtrinsicSuccess') {219      success = true;220    } else if ((section == 'common') && (method == 'ItemCreated')) {221      collectionId = parseInt(data[0].toString(), 10);222      itemId = parseInt(data[1].toString(), 10);223      recipient = normalizeAccountId(data[2].toJSON() as any);224225      const itemRes: CreateItemResult = {226        success,227        collectionId,228        itemId,229        recipient,230      };231232      results.push(itemRes);233    }234  });235236  return results;237}238239export function getCreateItemResult(events: EventRecord[]): CreateItemResult {240  let success = false;241  let collectionId = 0;242  let itemId = 0;243  let recipient;244  events.forEach(({event: {data, method, section}}) => {245    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);246    if (method == 'ExtrinsicSuccess') {247      success = true;248    } else if ((section == 'common') && (method == 'ItemCreated')) {249      collectionId = parseInt(data[0].toString(), 10);250      itemId = parseInt(data[1].toString(), 10);251      recipient = normalizeAccountId(data[2].toJSON() as any);252    }253  });254  const result: CreateItemResult = {255    success,256    collectionId,257    itemId,258    recipient,259  };260  return result;261}262263export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {264  for (const {event} of events) {265    if (api.events.common.Transfer.is(event)) {266      const [collection, token, sender, recipient, value] = event.data;267      return {268        collectionId: collection.toNumber(),269        itemId: token.toNumber(),270        sender: normalizeAccountId(sender.toJSON() as any),271        recipient: normalizeAccountId(recipient.toJSON() as any),272        value: value.toBigInt(),273      };274    }275  }276  throw new Error('no transfer event');277}278279interface Nft {280  type: 'NFT';281}282283interface Fungible {284  type: 'Fungible';285  decimalPoints: number;286}287288interface ReFungible {289  type: 'ReFungible';290}291292type CollectionMode = Nft | Fungible | ReFungible;293294export type Property = {295  key: any,296  value: any,297};298299type PropertyPermission = {300  key: any,301  mutable: boolean;302  collectionAdmin: boolean;303  tokenOwner: boolean;304}305306export type CreateCollectionParams = {307  mode: CollectionMode,308  name: string,309  description: string,310  tokenPrefix: string,311  schemaVersion: string,312  properties?: Array<Property>,313  propPerm?: Array<PropertyPermission>314};315316const defaultCreateCollectionParams: CreateCollectionParams = {317  description: 'description',318  mode: {type: 'NFT'},319  name: 'name',320  tokenPrefix: 'prefix',321  schemaVersion: 'ImageURL',322};323324export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {325  const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};326327  let collectionId = 0;328  await usingApi(async (api) => {329    // Get number of collections before the transaction330    const collectionCountBefore = await getCreatedCollectionCount(api);331332    // Run the CreateCollection transaction333    const alicePrivateKey = privateKey('//Alice');334335    let modeprm = {};336    if (mode.type === 'NFT') {337      modeprm = {nft: null};338    } else if (mode.type === 'Fungible') {339      modeprm = {fungible: mode.decimalPoints};340    } else if (mode.type === 'ReFungible') {341      modeprm = {refungible: null};342    }343344    const tx = api.tx.unique.createCollectionEx({345      name: strToUTF16(name),346      description: strToUTF16(description),347      tokenPrefix: strToUTF16(tokenPrefix),348      mode: modeprm as any,349      schemaVersion: schemaVersion,350    });351    const events = await submitTransactionAsync(alicePrivateKey, tx);352    const result = getCreateCollectionResult(events);353354    // Get number of collections after the transaction355    const collectionCountAfter = await getCreatedCollectionCount(api);356357    // Get the collection358    const collection = await queryCollectionExpectSuccess(api, result.collectionId);359360    // What to expect361    // tslint:disable-next-line:no-unused-expression362    expect(result.success).to.be.true;363    expect(result.collectionId).to.be.equal(collectionCountAfter);364    // tslint:disable-next-line:no-unused-expression365    expect(collection).to.be.not.null;366    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');367    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));368    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);369    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);370    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);371372    collectionId = result.collectionId;373  });374375  return collectionId;376}377378export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {379  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};380381  let collectionId = 0;382  await usingApi(async (api) => {383    // Get number of collections before the transaction384    const collectionCountBefore = await getCreatedCollectionCount(api);385386    // Run the CreateCollection transaction387    const alicePrivateKey = privateKey('//Alice');388389    let modeprm = {};390    if (mode.type === 'NFT') {391      modeprm = {nft: null};392    } else if (mode.type === 'Fungible') {393      modeprm = {fungible: mode.decimalPoints};394    } else if (mode.type === 'ReFungible') {395      modeprm = {refungible: null};396    }397398    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});399    const events = await submitTransactionAsync(alicePrivateKey, tx);400    const result = getCreateCollectionResult(events);401402    // Get number of collections after the transaction403    const collectionCountAfter = await getCreatedCollectionCount(api);404405    // Get the collection406    const collection = await queryCollectionExpectSuccess(api, result.collectionId);407408    // What to expect409    // tslint:disable-next-line:no-unused-expression410    expect(result.success).to.be.true;411    expect(result.collectionId).to.be.equal(collectionCountAfter);412    // tslint:disable-next-line:no-unused-expression413    expect(collection).to.be.not.null;414    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');415    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));416    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);417    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);418    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);419420421    collectionId = result.collectionId;422  });423424  return collectionId;425}426427export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {428  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};429430  await usingApi(async (api) => {431    // Get number of collections before the transaction432    const collectionCountBefore = await getCreatedCollectionCount(api);433434    // Run the CreateCollection transaction435    const alicePrivateKey = privateKey('//Alice');436437    let modeprm = {};438    if (mode.type === 'NFT') {439      modeprm = {nft: null};440    } else if (mode.type === 'Fungible') {441      modeprm = {fungible: mode.decimalPoints};442    } else if (mode.type === 'ReFungible') {443      modeprm = {refungible: null};444    }445446    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});447    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;448449450    // Get number of collections after the transaction451    const collectionCountAfter = await getCreatedCollectionCount(api);452453    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');454  });455}456457export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {458  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};459460  let modeprm = {};461  if (mode.type === 'NFT') {462    modeprm = {nft: null};463  } else if (mode.type === 'Fungible') {464    modeprm = {fungible: mode.decimalPoints};465  } else if (mode.type === 'ReFungible') {466    modeprm = {refungible: null};467  }468469  await usingApi(async (api) => {470    // Get number of collections before the transaction471    const collectionCountBefore = await getCreatedCollectionCount(api);472473    // Run the CreateCollection transaction474    const alicePrivateKey = privateKey('//Alice');475    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});476    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;477478    // Get number of collections after the transaction479    const collectionCountAfter = await getCreatedCollectionCount(api);480481    // What to expect482    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');483  });484}485486export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {487  let bal = 0n;488  let unused;489  do {490    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;491    const keyring = new Keyring({type: 'sr25519'});492    unused = keyring.addFromUri(`//${randomSeed}`);493    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();494  } while (bal !== 0n);495  return unused;496}497498export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {499  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();500}501502export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {503  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));504}505506export async function findNotExistingCollection(api: ApiPromise): Promise<number> {507  const totalNumber = await getCreatedCollectionCount(api);508  const newCollection: number = totalNumber + 1;509  return newCollection;510}511512function getDestroyResult(events: EventRecord[]): boolean {513  let success = false;514  events.forEach(({event: {method}}) => {515    if (method == 'ExtrinsicSuccess') {516      success = true;517    }518  });519  return success;520}521522export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {523  await usingApi(async (api) => {524    // Run the DestroyCollection transaction525    const alicePrivateKey = privateKey(senderSeed);526    const tx = api.tx.unique.destroyCollection(collectionId);527    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;528  });529}530531export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {532  await usingApi(async (api) => {533    // Run the DestroyCollection transaction534    const alicePrivateKey = privateKey(senderSeed);535    const tx = api.tx.unique.destroyCollection(collectionId);536    const events = await submitTransactionAsync(alicePrivateKey, tx);537    const result = getDestroyResult(events);538    expect(result).to.be.true;539540    // What to expect541    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;542  });543}544545export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {546  await usingApi(async (api) => {547    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);548    const events = await submitTransactionAsync(sender, tx);549    const result = getGenericResult(events);550551    expect(result.success).to.be.true;552  });553}554555export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {556  await usingApi(async (api) => {557    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);558    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;559    const result = getGenericResult(events);560561    expect(result.success).to.be.false;562  });563}564565export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {566  await usingApi(async (api) => {567568    // Run the transaction569    const senderPrivateKey = privateKey(sender);570    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);571    const events = await submitTransactionAsync(senderPrivateKey, tx);572    const result = getGenericResult(events);573574    // Get the collection575    const collection = await queryCollectionExpectSuccess(api, collectionId);576577    // What to expect578    expect(result.success).to.be.true;579    expect(collection.sponsorship.toJSON()).to.deep.equal({580      unconfirmed: sponsor,581    });582  });583}584585export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {586  await usingApi(async (api) => {587588    // Run the transaction589    const alicePrivateKey = privateKey(sender);590    const tx = api.tx.unique.removeCollectionSponsor(collectionId);591    const events = await submitTransactionAsync(alicePrivateKey, tx);592    const result = getGenericResult(events);593594    // Get the collection595    const collection = await queryCollectionExpectSuccess(api, collectionId);596597    // What to expect598    expect(result.success).to.be.true;599    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});600  });601}602603export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {604  await usingApi(async (api) => {605606    // Run the transaction607    const alicePrivateKey = privateKey(senderSeed);608    const tx = api.tx.unique.removeCollectionSponsor(collectionId);609    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;610  });611}612613export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {614  await usingApi(async (api) => {615616    // Run the transaction617    const alicePrivateKey = privateKey(senderSeed);618    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);619    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;620  });621}622623export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {624  await usingApi(async (api) => {625626    // Run the transaction627    const sender = privateKey(senderSeed);628    const tx = api.tx.unique.confirmSponsorship(collectionId);629    const events = await submitTransactionAsync(sender, tx);630    const result = getGenericResult(events);631632    // Get the collection633    const collection = await queryCollectionExpectSuccess(api, collectionId);634635    // What to expect636    expect(result.success).to.be.true;637    expect(collection.sponsorship.toJSON()).to.be.deep.equal({638      confirmed: sender.address,639    });640  });641}642643644export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {645  await usingApi(async (api) => {646647    // Run the transaction648    const sender = privateKey(senderSeed);649    const tx = api.tx.unique.confirmSponsorship(collectionId);650    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;651  });652}653654export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {655656  await usingApi(async (api) => {657    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);658    const events = await submitTransactionAsync(sender, tx);659    const result = getGenericResult(events);660661    expect(result.success).to.be.true;662  });663}664665export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {666667  await usingApi(async (api) => {668    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);669    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;670    const result = getGenericResult(events);671672    expect(result.success).to.be.false;673  });674}675676export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {677  await usingApi(async (api) => {678    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);679    const events = await submitTransactionAsync(sender, tx);680    const result = getGenericResult(events);681682    expect(result.success).to.be.true;683  });684}685686export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {687  await usingApi(async (api) => {688    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);689    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;690    const result = getGenericResult(events);691692    expect(result.success).to.be.false;693  });694}695696export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {697698  await usingApi(async (api) => {699700    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);701    const events = await submitTransactionAsync(sender, tx);702    const result = getGenericResult(events);703704    expect(result.success).to.be.true;705  });706}707708export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {709710  await usingApi(async (api) => {711712    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);713    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;714    const result = getGenericResult(events);715716    expect(result.success).to.be.false;717  });718}719720export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {721  await usingApi(async (api) => {722    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);723    const events = await submitTransactionAsync(sender, tx);724    const result = getGenericResult(events);725726    expect(result.success).to.be.true;727  });728}729730export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {731  await usingApi(async (api) => {732    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);733    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;734    const result = getGenericResult(events);735736    expect(result.success).to.be.false;737  });738}739740export async function getNextSponsored(741  api: ApiPromise,742  collectionId: number,743  account: string | CrossAccountId,744  tokenId: number,745): Promise<number> {746  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));747}748749export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {750  await usingApi(async (api) => {751    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);752    const events = await submitTransactionAsync(sender, tx);753    const result = getGenericResult(events);754755    expect(result.success).to.be.true;756  });757}758759export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {760  let allowlisted = false;761  await usingApi(async (api) => {762    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;763  });764  return allowlisted;765}766767export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {768  await usingApi(async (api) => {769    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());770    const events = await submitTransactionAsync(sender, tx);771    const result = getGenericResult(events);772773    expect(result.success).to.be.true;774  });775}776777export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {778  await usingApi(async (api) => {779    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());780    const events = await submitTransactionAsync(sender, tx);781    const result = getGenericResult(events);782783    expect(result.success).to.be.true;784  });785}786787export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {788  await usingApi(async (api) => {789    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());790    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;791    const result = getGenericResult(events);792793    expect(result.success).to.be.false;794  });795}796797export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {798  await usingApi(async (api) => {799    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));800    const events = await submitTransactionAsync(sender, tx);801    const result = getGenericResult(events);802803    expect(result.success).to.be.true;804  });805}806807export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {808  await usingApi(async (api) => {809    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));810    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;811  });812}813814export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {815  await usingApi(async (api) => {816    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));817    const events = await submitTransactionAsync(sender, tx);818    const result = getGenericResult(events);819820    expect(result.success).to.be.true;821  });822}823824export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {825  await usingApi(async (api) => {826    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));827    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;828  });829}830831export interface CreateFungibleData {832  readonly Value: bigint;833}834835export interface CreateReFungibleData { }836export interface CreateNftData { }837838export type CreateItemData = {839  NFT: CreateNftData;840} | {841  Fungible: CreateFungibleData;842} | {843  ReFungible: CreateReFungibleData;844};845846export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {847  await usingApi(async (api) => {848    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);849    // if burning token by admin - use adminButnItemExpectSuccess850    expect(balanceBefore >= BigInt(value)).to.be.true;851852    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);853    const events = await submitTransactionAsync(sender, tx);854    const result = getGenericResult(events);855    expect(result.success).to.be.true;856857    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);858    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);859  });860}861862export async function863approveExpectSuccess(864  collectionId: number,865  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,866) {867  await usingApi(async (api: ApiPromise) => {868    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);869    const events = await submitTransactionAsync(owner, approveUniqueTx);870    const result = getGenericResult(events);871    expect(result.success).to.be.true;872873    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));874  });875}876877export async function adminApproveFromExpectSuccess(878  collectionId: number,879  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,880) {881  await usingApi(async (api: ApiPromise) => {882    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);883    const events = await submitTransactionAsync(admin, approveUniqueTx);884    const result = getGenericResult(events);885    expect(result.success).to.be.true;886887    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));888  });889}890891export async function892transferFromExpectSuccess(893  collectionId: number,894  tokenId: number,895  accountApproved: IKeyringPair,896  accountFrom: IKeyringPair | CrossAccountId,897  accountTo: IKeyringPair | CrossAccountId,898  value: number | bigint = 1,899  type = 'NFT',900) {901  await usingApi(async (api: ApiPromise) => {902    const from = normalizeAccountId(accountFrom);903    const to = normalizeAccountId(accountTo);904    let balanceBefore = 0n;905    if (type === 'Fungible' || type === 'ReFungible') {906      balanceBefore = await getBalance(api, collectionId, to, tokenId);907    }908    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);909    const events = await submitTransactionAsync(accountApproved, transferFromTx);910    const result = getCreateItemResult(events);911    // tslint:disable-next-line:no-unused-expression912    expect(result.success).to.be.true;913    if (type === 'NFT') {914      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);915    }916    if (type === 'Fungible') {917      const balanceAfter = await getBalance(api, collectionId, to, tokenId);918      if (JSON.stringify(to) !== JSON.stringify(from)) {919        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));920      } else {921        expect(balanceAfter).to.be.equal(balanceBefore);922      }923    }924    if (type === 'ReFungible') {925      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));926    }927  });928}929930export async function931transferFromExpectFail(932  collectionId: number,933  tokenId: number,934  accountApproved: IKeyringPair,935  accountFrom: IKeyringPair,936  accountTo: IKeyringPair,937  value: number | bigint = 1,938) {939  await usingApi(async (api: ApiPromise) => {940    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);941    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;942    const result = getCreateCollectionResult(events);943    // tslint:disable-next-line:no-unused-expression944    expect(result.success).to.be.false;945  });946}947948/* eslint no-async-promise-executor: "off" */949async function getBlockNumber(api: ApiPromise): Promise<number> {950  return new Promise<number>(async (resolve) => {951    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {952      unsubscribe();953      resolve(head.number.toNumber());954    });955  });956}957958export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {959  await usingApi(async (api) => {960    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));961    const events = await submitTransactionAsync(sender, changeAdminTx);962    const result = getCreateCollectionResult(events);963    expect(result.success).to.be.true;964  });965}966967export async function968getFreeBalance(account: IKeyringPair): Promise<bigint> {969  let balance = 0n;970  await usingApi(async (api) => {971    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());972  });973974  return balance;975}976977export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {978  const tx = api.tx.balances.transfer(target, amount);979  const events = await submitTransactionAsync(source, tx);980  const result = getGenericResult(events);981  expect(result.success).to.be.true;982}983984export async function985scheduleTransferExpectSuccess(986  collectionId: number,987  tokenId: number,988  sender: IKeyringPair,989  recipient: IKeyringPair,990  value: number | bigint = 1,991  blockSchedule: number,992) {993  await usingApi(async (api: ApiPromise) => {994    const blockNumber: number | undefined = await getBlockNumber(api);995    const expectedBlockNumber = blockNumber + blockSchedule;996997    expect(blockNumber).to.be.greaterThan(0);998    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);999    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);10001001    await submitTransactionAsync(sender, scheduleTx);10021003    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10041005    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));10061007    // sleep for 4 blocks1008    await waitNewBlocks(blockSchedule + 1);10091010    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10111012    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1013    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1014  });1015}101610171018export async function1019transferExpectSuccess(1020  collectionId: number,1021  tokenId: number,1022  sender: IKeyringPair,1023  recipient: IKeyringPair | CrossAccountId,1024  value: number | bigint = 1,1025  type = 'NFT',1026) {1027  await usingApi(async (api: ApiPromise) => {1028    const from = normalizeAccountId(sender);1029    const to = normalizeAccountId(recipient);10301031    let balanceBefore = 0n;1032    if (type === 'Fungible') {1033      balanceBefore = await getBalance(api, collectionId, to, tokenId);1034    }1035    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1036    const events = await executeTransaction(api, sender, transferTx);10371038    const result = getTransferResult(api, events);1039    expect(result.collectionId).to.be.equal(collectionId);1040    expect(result.itemId).to.be.equal(tokenId);1041    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1042    expect(result.recipient).to.be.deep.equal(to);1043    expect(result.value).to.be.equal(BigInt(value));10441045    if (type === 'NFT') {1046      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1047    }1048    if (type === 'Fungible') {1049      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1050      if (JSON.stringify(to) !== JSON.stringify(from)) {1051        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1052      } else {1053        expect(balanceAfter).to.be.equal(balanceBefore);1054      }1055    }1056    if (type === 'ReFungible') {1057      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1058    }1059  });1060}10611062export async function1063transferExpectFailure(1064  collectionId: number,1065  tokenId: number,1066  sender: IKeyringPair,1067  recipient: IKeyringPair | CrossAccountId,1068  value: number | bigint = 1,1069) {1070  await usingApi(async (api: ApiPromise) => {1071    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1072    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1073    const result = getGenericResult(events);1074    // if (events && Array.isArray(events)) {1075    //   const result = getCreateCollectionResult(events);1076    // tslint:disable-next-line:no-unused-expression1077    expect(result.success).to.be.false;1078    //}1079  });1080}10811082export async function1083approveExpectFail(1084  collectionId: number,1085  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1086) {1087  await usingApi(async (api: ApiPromise) => {1088    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1089    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1090    const result = getCreateCollectionResult(events);1091    // tslint:disable-next-line:no-unused-expression1092    expect(result.success).to.be.false;1093  });1094}10951096export async function getBalance(1097  api: ApiPromise,1098  collectionId: number,1099  owner: string | CrossAccountId,1100  token: number,1101): Promise<bigint> {1102  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1103}1104export async function getTokenOwner(1105  api: ApiPromise,1106  collectionId: number,1107  token: number,1108): Promise<CrossAccountId> {1109  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1110  if (owner == null) throw new Error('owner == null');1111  return normalizeAccountId(owner);1112}1113export async function getTopmostTokenOwner(1114  api: ApiPromise,1115  collectionId: number,1116  token: number,1117): Promise<CrossAccountId> {1118  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1119  if (owner == null) throw new Error('owner == null');1120  return normalizeAccountId(owner);1121}1122export async function isTokenExists(1123  api: ApiPromise,1124  collectionId: number,1125  token: number,1126): Promise<boolean> {1127  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1128}1129export async function getLastTokenId(1130  api: ApiPromise,1131  collectionId: number,1132): Promise<number> {1133  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1134}1135export async function getAdminList(1136  api: ApiPromise,1137  collectionId: number,1138): Promise<string[]> {1139  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1140}1141export async function getVariableMetadata(1142  api: ApiPromise,1143  collectionId: number,1144  tokenId: number,1145): Promise<number[]> {1146  return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1147}1148export async function getConstMetadata(1149  api: ApiPromise,1150  collectionId: number,1151  tokenId: number,1152): Promise<number[]> {1153  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1154}11551156export async function createFungibleItemExpectSuccess(1157  sender: IKeyringPair,1158  collectionId: number,1159  data: CreateFungibleData,1160  owner: CrossAccountId | string = sender.address,1161) {1162  return await usingApi(async (api) => {1163    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11641165    const events = await submitTransactionAsync(sender, tx);1166    const result = getCreateItemResult(events);11671168    expect(result.success).to.be.true;1169    return result.itemId;1170  });1171}11721173export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1174  let newItemId = 0;1175  await usingApi(async (api) => {1176    const to = normalizeAccountId(owner);1177    const itemCountBefore = await getLastTokenId(api, collectionId);1178    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11791180    let tx;1181    if (createMode === 'Fungible') {1182      const createData = {fungible: {value: 10}};1183      tx = api.tx.unique.createItem(collectionId, to, createData as any);1184    } else if (createMode === 'ReFungible') {1185      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1186      tx = api.tx.unique.createItem(collectionId, to, createData as any);1187    } else {1188      const createData = {nft: {const_data: [], variable_data: []}};1189      tx = api.tx.unique.createItem(collectionId, to, createData as any);1190    }11911192    const events = await submitTransactionAsync(sender, tx);1193    const result = getCreateItemResult(events);11941195    const itemCountAfter = await getLastTokenId(api, collectionId);1196    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11971198    // What to expect1199    // tslint:disable-next-line:no-unused-expression1200    expect(result.success).to.be.true;1201    if (createMode === 'Fungible') {1202      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1203    } else {1204      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1205    }1206    expect(collectionId).to.be.equal(result.collectionId);1207    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1208    expect(to).to.be.deep.equal(result.recipient);1209    newItemId = result.itemId;1210  });1211  return newItemId;1212}12131214export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1215  await usingApi(async (api) => {1216    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);12171218    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1219    const result = getCreateItemResult(events);12201221    expect(result.success).to.be.false;1222  });1223}12241225export async function setPublicAccessModeExpectSuccess(1226  sender: IKeyringPair, collectionId: number,1227  accessMode: 'Normal' | 'AllowList',1228) {1229  await usingApi(async (api) => {12301231    // Run the transaction1232    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1233    const events = await submitTransactionAsync(sender, tx);1234    const result = getGenericResult(events);12351236    // Get the collection1237    const collection = await queryCollectionExpectSuccess(api, collectionId);12381239    // What to expect1240    // tslint:disable-next-line:no-unused-expression1241    expect(result.success).to.be.true;1242    expect(collection.access.toHuman()).to.be.equal(accessMode);1243  });1244}12451246export async function setPublicAccessModeExpectFail(1247  sender: IKeyringPair, collectionId: number,1248  accessMode: 'Normal' | 'AllowList',1249) {1250  await usingApi(async (api) => {12511252    // Run the transaction1253    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1254    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1255    const result = getGenericResult(events);12561257    // What to expect1258    // tslint:disable-next-line:no-unused-expression1259    expect(result.success).to.be.false;1260  });1261}12621263export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1264  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1265}12661267export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1268  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1269}12701271export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1272  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1273}12741275export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1276  await usingApi(async (api) => {12771278    // Run the transaction1279    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1280    const events = await submitTransactionAsync(sender, tx);1281    const result = getGenericResult(events);1282    expect(result.success).to.be.true;12831284    // Get the collection1285    const collection = await queryCollectionExpectSuccess(api, collectionId);12861287    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1288  });1289}12901291export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1292  await setMintPermissionExpectSuccess(sender, collectionId, true);1293}12941295export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1296  await usingApi(async (api) => {1297    // Run the transaction1298    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1299    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1300    const result = getCreateCollectionResult(events);1301    // tslint:disable-next-line:no-unused-expression1302    expect(result.success).to.be.false;1303  });1304}13051306export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1307  await usingApi(async (api) => {1308    // Run the transaction1309    const tx = api.tx.unique.setChainLimits(limits);1310    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1311    const result = getCreateCollectionResult(events);1312    // tslint:disable-next-line:no-unused-expression1313    expect(result.success).to.be.false;1314  });1315}13161317export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1318  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1319}13201321export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1322  await usingApi(async (api) => {1323    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;13241325    // Run the transaction1326    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1327    const events = await submitTransactionAsync(sender, tx);1328    const result = getGenericResult(events);1329    expect(result.success).to.be.true;13301331    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1332  });1333}13341335export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1336  await usingApi(async (api) => {13371338    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;13391340    // Run the transaction1341    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1342    const events = await submitTransactionAsync(sender, tx);1343    const result = getGenericResult(events);1344    expect(result.success).to.be.true;13451346    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1347  });1348}13491350export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1351  await usingApi(async (api) => {13521353    // Run the transaction1354    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1355    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1356    const result = getGenericResult(events);13571358    // What to expect1359    // tslint:disable-next-line:no-unused-expression1360    expect(result.success).to.be.false;1361  });1362}13631364export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1365  await usingApi(async (api) => {1366    // Run the transaction1367    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1368    const events = await submitTransactionAsync(sender, tx);1369    const result = getGenericResult(events);13701371    // What to expect1372    // tslint:disable-next-line:no-unused-expression1373    expect(result.success).to.be.true;1374  });1375}13761377export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1378  await usingApi(async (api) => {1379    // Run the transaction1380    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1381    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1382    const result = getGenericResult(events);13831384    // What to expect1385    // tslint:disable-next-line:no-unused-expression1386    expect(result.success).to.be.false;1387  });1388}13891390export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1391  : Promise<UpDataStructsRpcCollection | null> => {1392  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1393};13941395export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1396  // set global object - collectionsCount1397  return (await api.rpc.unique.collectionStats()).created.toNumber();1398};13991400export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1401  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1402}14031404export async function waitNewBlocks(blocksCount = 1): Promise<void> {1405  await usingApi(async (api) => {1406    const promise = new Promise<void>(async (resolve) => {1407      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1408        if (blocksCount > 0) {1409          blocksCount--;1410        } else {1411          unsubscribe();1412          resolve();1413        }1414      });1415    });1416    return promise;1417  });1418}