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

difftreelog

test(structure) refactor properties and nesting

Fahrrader2022-05-13parent: #1c4a2b3.patch.diff
in: master

7 files changed

modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -33,7 +33,9 @@
     "loadTransfer": "ts-node src/transfer.nload.ts",
     "testCollision": "mocha --timeout 9999999 -r ts-node/register ./src/collision-tests/*.test.ts",
     "testEvent": "mocha --timeout 9999999 -r ts-node/register ./src/check-event/*.test.ts",
-    "testNesting": "mocha --timeout 9999999 -r ts-node/register ./**/nesting/**.test.ts",
+    "testNesting": "mocha --timeout 9999999 -r ts-node/register ./**/nest.test.ts",
+    "testUnnesting": "mocha --timeout 9999999 -r ts-node/register ./**/unnest.test.ts",
+    "testStructure": "mocha --timeout 9999999 -r ts-node/register ./**/nesting/**.test.ts",
     "testProperties": "mocha --timeout 9999999 -r ts-node/register ./**/properties.test.ts",
     "testMigrationStructure": "mocha --timeout 9999999 -r ts-node/register ./**/nesting/migration-check.test.ts",
     "testAddCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/addCollectionAdmin.test.ts",
modifiedtests/src/nesting/graphs.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/graphs.test.ts
+++ b/tests/src/nesting/graphs.test.ts
@@ -14,7 +14,7 @@
  * ```
  */
 async function buildComplexObjectGraph(api: ApiPromise, sender: IKeyringPair): Promise<number> {
-  const events = await executeTransaction(api, sender, api.tx.unique.createCollectionEx({mode: 'NFT'}));
+  const events = await executeTransaction(api, sender, api.tx.unique.createCollectionEx({mode: 'NFT', limits: {nestingRule: 'Owner'}}));
   const {collectionId} = getCreateCollectionResult(events);
 
   await executeTransaction(api, sender, api.tx.unique.createMultipleItemsEx(collectionId, {NFT: Array(8).fill({owner: {Substrate: sender.address}})}));
@@ -32,20 +32,26 @@
   return collectionId;
 }
 
-describe('graphs', () => {
-  it('ouroboros can\'t be created in graph', async () => {
+describe('Graphs', () => {
+  it('Ouroboros can\'t be created in a complex graph', async () => {
     await usingApi(async api => {
       const alice = privateKey('//Alice');
       const collection = await buildComplexObjectGraph(api, alice);
 
       // to self
-      await expect(executeTransaction(api, alice, api.tx.unique.transfer(tokenIdToCross(collection, 1), collection, 1, 1)))
-        .to.be.rejectedWith(/structure\.OuroborosDetected/);
+      await expect(
+        executeTransaction(api, alice, api.tx.unique.transfer(tokenIdToCross(collection, 1), collection, 1, 1)),
+        'first transaction',  
+      ).to.be.rejectedWith(/structure\.OuroborosDetected/);
       // to nested part of graph
-      await expect(executeTransaction(api, alice, api.tx.unique.transfer(tokenIdToCross(collection, 5), collection, 1, 1)))
-        .to.be.rejectedWith(/structure\.OuroborosDetected/);
-      await expect(executeTransaction(api, alice, api.tx.unique.transfer(tokenIdToCross(collection, 8), collection, 2, 1)))
-        .to.be.rejectedWith(/structure\.OuroborosDetected/);
+      await expect(
+        executeTransaction(api, alice, api.tx.unique.transfer(tokenIdToCross(collection, 5), collection, 1, 1)),
+        'second transaction',
+      ).to.be.rejectedWith(/structure\.OuroborosDetected/);
+      await expect(
+        executeTransaction(api, alice, api.tx.unique.transfer(tokenIdToCross(collection, 8), collection, 2, 1)),
+        'third transaction',
+      ).to.be.rejectedWith(/structure\.OuroborosDetected/);
     });
   });
 });
modifiedtests/src/nesting/migration-check.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/migration-check.test.ts
+++ b/tests/src/nesting/migration-check.test.ts
@@ -18,7 +18,7 @@
     });
   });
 
-  it('Preserves collection settings', async () => {
+  it('Preserves collection settings after migration', async () => {
     let oldVersion: number;
     let collectionId: number;
     let collectionOld: any;
@@ -71,6 +71,7 @@
         });
       } catch (_) {
         connectionFailCounter++;
+        console.log(`Still waiting for the parachain upgrade from ${oldVersion!}...`);
         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
@@ -5,12 +5,12 @@
 import {
   addToAllowListExpectSuccess,
   createCollectionExpectSuccess,
-  createItemExpectFailure, 
   createItemExpectSuccess,
   enableAllowListExpectSuccess,
   enablePublicMintingExpectSuccess,
   getTokenOwner, 
   getTopmostTokenOwner, 
+  normalizeAccountId, 
   setCollectionLimitsExpectSuccess, 
   transferExpectFailure, 
   transferExpectSuccess, 
@@ -29,11 +29,7 @@
     });
   });
 
-  // ---------- Non-Fungible ----------
-
-  // todo refactor names
-  // todo remove excessive bundling, leave it for a single test
-  it('NFT: allows to nest/unnest token if nesting rule is Owner', async () => {
+  it('Performs the full suite: bundles a token, transfers, and allows to unnest', async () => {
     await usingApi(async api => {
       const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
       await setCollectionLimitsExpectSuccess(alice, collection, {nestingRule: 'Owner'});
@@ -49,8 +45,8 @@
       
       // Nest
       await transferExpectSuccess(collection, newToken, alice, {Ethereum: tokenIdToAddress(collection, targetToken)});
-      expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: alice.address});
-      expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
+      expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
+      expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
 
       // Move bundle to different user
       await transferExpectSuccess(collection, targetToken, alice, {Substrate: bob.address});
@@ -63,10 +59,12 @@
     });
   });
 
-  it('NFT: allows to nest/unnest token if Owner-Restricted', async () => {
+  // ---------- Non-Fungible ----------
+
+  it('NFT: allows an Owner to nest/unnest their token', async () => {
     await usingApi(async api => {
       const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionLimitsExpectSuccess(alice, collection, {nestingRule: {OwnerRestricted:[collection]}});
+      await setCollectionLimitsExpectSuccess(alice, collection, {nestingRule: 'Owner'});
       const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
 
       // Create a nested token
@@ -74,28 +72,36 @@
       expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: alice.address});
       expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
 
-      // Create a token to be nested
+      // Create a token to be nested and nest
       const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
-      
-      // Nest
       await transferExpectSuccess(collection, newToken, alice, {Ethereum: tokenIdToAddress(collection, targetToken)});
+      expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
+      expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
+    });
+  });
+
+  it('NFT: allows an Owner to nest/unnest their token (Restricted nesting)', async () => {
+    await usingApi(async api => {
+      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+      await setCollectionLimitsExpectSuccess(alice, collection, {nestingRule: {OwnerRestricted:[collection]}});
+      const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
+
+      // Create a nested token
+      const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});
       expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: alice.address});
       expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
 
-      // Move bundle to different user
-      await transferExpectSuccess(collection, targetToken, alice, {Substrate: bob.address});
-      expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: bob.address});
-      expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
-      
-      // Unnest
-      await transferFromExpectSuccess(collection, newToken, bob, {Ethereum: tokenIdToAddress(collection, targetToken)}, {Substrate: bob.address});
-      expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: bob.address});
+      // Create a token to be nested and nest
+      const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
+      await transferExpectSuccess(collection, newToken, alice, {Ethereum: tokenIdToAddress(collection, targetToken)});
+      expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
+      expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
     });
   });
 
   // ---------- Fungible ----------
 
-  it('Fungible: allows to nest/unnest token if Owner', async () => {
+  it('Fungible: allows an Owner to nest/unnest their token', async () => {
     await usingApi(async api => {
       const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
       await setCollectionLimitsExpectSuccess(alice, collectionNFT, {nestingRule: 'Owner'});
@@ -111,18 +117,13 @@
         {Fungible: {Value: 10}},
       ))).to.not.be.rejected;
 
-      // Create a token to be nested
+      // Nest a new token
       const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
-      // Nest
       await transferExpectSuccess(collectionFT, newToken, alice, targetAddress, 1, 'Fungible');
-      // Move bundle to different user
-      await transferExpectSuccess(collectionNFT, targetToken, alice, {Substrate: bob.address});
-      // Unnest
-      await transferFromExpectSuccess(collectionFT, newToken, bob, targetAddress, {Substrate: bob.address}, 1, 'Fungible');
     });
   });
 
-  it('Fungible: allows to nest/unnest token if Owner-Restricted', async () => {
+  it('Fungible: allows an Owner to nest/unnest their token (Restricted nesting)', async () => {
     await usingApi(async api => {
       const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
       const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT', {Substrate: alice.address});
@@ -139,20 +140,15 @@
         {Fungible: {Value: 10}},
       ))).to.not.be.rejected;
 
-      // Create a token to be nested
+      // Nest a new token
       const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
-      // Nest
       await transferExpectSuccess(collectionFT, newToken, alice, targetAddress, 1, 'Fungible');
-      // Move bundle to different user
-      await transferExpectSuccess(collectionNFT, targetToken, alice, {Substrate: bob.address});
-      // Unnest
-      await transferFromExpectSuccess(collectionFT, newToken, bob, targetAddress, {Substrate: bob.address}, 1, 'Fungible');
     });
   });
 
   // ---------- Re-Fungible ----------
 
-  it('ReFungible: allows to nest/unnest token if Owner', async () => {
+  it('ReFungible: allows an Owner to nest/unnest their token', async () => {
     await usingApi(async api => {
       const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
       await setCollectionLimitsExpectSuccess(alice, collectionNFT, {nestingRule: 'Owner'});
@@ -165,21 +161,16 @@
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
         collectionRFT, 
         targetAddress, 
-        {ReFungible: {const_data: [], variable_data: [], pieces: 100}},
+        {ReFungible: {const_data: [], pieces: 100}},
       ))).to.not.be.rejected;
 
-      // Create a token to be nested
+      // Nest a new token
       const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
-      // Nest
       await transferExpectSuccess(collectionRFT, newToken, alice, targetAddress, 100, 'ReFungible');
-      // Move bundle to different user
-      await transferExpectSuccess(collectionNFT, targetToken, alice, {Substrate: bob.address});
-      // Unnest
-      await transferFromExpectSuccess(collectionRFT, newToken, bob, targetAddress, {Substrate: bob.address}, 100, 'ReFungible');
     });
   });
 
-  it('ReFungible: allows to nest/unnest token if Owner-Restricted', async () => {
+  it('ReFungible: allows an Owner to nest/unnest their token (Restricted nesting)', async () => {
     await usingApi(async api => {
       const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
       const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT', {Substrate: alice.address});
@@ -193,17 +184,12 @@
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
         collectionRFT, 
         targetAddress,
-        {ReFungible: {const_data: [], variable_data: [], pieces: 100}},
+        {ReFungible: {const_data: [], pieces: 100}},
       ))).to.not.be.rejected;
 
-      // Create a token to be nested
+      // Nest a new token
       const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
-      // Nest
       await transferExpectSuccess(collectionRFT, newToken, alice, targetAddress, 100, 'ReFungible');
-      // Move bundle to different user
-      await transferExpectSuccess(collectionNFT, targetToken, alice, {Substrate: bob.address});
-      // Unnest
-      await transferFromExpectSuccess(collectionRFT, newToken, bob, targetAddress, {Substrate: bob.address}, 100, 'ReFungible');
     });
   });
 });
@@ -216,6 +202,29 @@
     });
   });
 
+  it('Disallows excessive token nesting', async () => {
+    await usingApi(async api => {
+      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+      await setCollectionLimitsExpectSuccess(alice, collection, {nestingRule: 'Owner'});
+      const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
+
+      // Create a nested-token matryoshka
+      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)}, 
+          {nft: {const_data: [], variable_data: []}} as any,
+        ),
+      ), 'while creating nested token').to.be.rejectedWith(/^structure\.DepthLimit$/); // OuroborosDetected?
+
+      expect(await getTopmostTokenOwner(api, collection, nestedToken2)).to.be.deep.equal({Substrate: alice.address});
+    });
+  });
+
   // ---------- Non-Fungible ----------
 
   it('NFT: disallows to nest token if nesting is disabled', async () => {
@@ -225,22 +234,30 @@
       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)}, 
-        {nft: {const_data: [], variable_data: []}} as any,
-      ))).to.be.rejectedWith(/^common\.NestingIsDisabled$/);
+      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$/);
 
       // Create a token to be nested
       const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
       // Try to nest
-      await transferExpectFailure(collection, newToken, alice, {Ethereum: tokenIdToAddress(collection, targetToken)}); // todo to.be.rejected
+      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
       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});
     });
   });
 
-  it('NFT: disallows to nest token if not Owner', async () => {
+  it('NFT: disallows a non-Owner to nest someone else\'s token', async () => {
     await usingApi(async api => {
       const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
       await setCollectionLimitsExpectSuccess(alice, collection, {nestingRule: 'Owner'});
@@ -253,16 +270,28 @@
       const targetToken = await createItemExpectSuccess(bob, collection, 'NFT');
 
       // Try to create a nested token in the wrong collection
-      await createItemExpectFailure(alice, collection, 'NFT', {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?
 
       // Try to create and nest a token in the wrong collection
       const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
-      await transferExpectFailure(collection, newToken, alice, {Ethereum: tokenIdToAddress(collection, targetToken)});
+      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/);
       expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
     });
   });
 
-  it('NFT: disallows to nest token if not Owner (Restricted nesting)', async () => {
+  it('NFT: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async () => {
     await usingApi(async api => {
       const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
       await setCollectionLimitsExpectSuccess(alice, collection, {nestingRule: {OwnerRestricted:[collection]}});
@@ -275,16 +304,28 @@
       const targetToken = await createItemExpectSuccess(bob, collection, 'NFT');
 
       // Try to create a nested token in the wrong collection
-      await createItemExpectFailure(alice, collection, 'NFT', {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/);
 
       // Try to create and nest a token in the wrong collection
       const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
-      await transferExpectFailure(collection, newToken, alice, {Ethereum: tokenIdToAddress(collection, targetToken)});
+      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/);
       expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
     });
   });
 
-  it('NFT: disallows to nest token to an unlisted collection', async () => {
+  it('NFT: disallows to nest token in an unlisted collection', async () => {
     await usingApi(async api => {
       const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
       await setCollectionLimitsExpectSuccess(alice, collection, {nestingRule: {OwnerRestricted:[]}});
@@ -293,11 +334,23 @@
       const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
 
       // Try to create a nested token in the wrong collection
-      await createItemExpectFailure(alice, collection, 'NFT', {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/);
 
       // Try to create and nest a token in the wrong collection
       const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
-      await transferExpectFailure(collection, newToken, alice, {Ethereum: tokenIdToAddress(collection, targetToken)});
+      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/);
       expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
     });
   });
@@ -314,20 +367,28 @@
       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}},
-      ))).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 transferExpectFailure(collectionFT, newToken, alice, targetAddress, 1);
+      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/);
     });
   });
 
-  it('Fungible: disallows to nest token if not Owner', async () => {
+  it('Fungible: disallows a non-Owner to nest someone else\'s token', async () => {
     await usingApi(async api => {
       const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
       await setCollectionLimitsExpectSuccess(alice, collectionNFT, {nestingRule: 'Owner'});
@@ -343,22 +404,30 @@
       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}},
-      ))).to.be.rejected;
+      await expect(executeTransaction(
+        api, alice, 
+        api.tx.unique.createItem(
+          collectionFT, 
+          targetAddress, 
+          {Fungible: {Value: 10}},
+        )
+      ), 'while creating nested token').to.be.rejectedWith(/structure\.DepthLimit/);
 
       // 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(
+          normalizeAccountId({Ethereum: tokenIdToAddress(collectionFT, targetToken)}), collectionFT, newToken, 1,
+        ),
+      ), 'while nesting new token').to.be.rejectedWith(/fungible\.FungibleDisallowsNesting/);
     });
   });
 
-  it('Fungible: disallows to nest token if not Owner (Restricted nesting)', async () => {
+  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 setCollectionLimitsExpectSuccess(alice, collectionNFT, {nestingRule: {OwnerRestricted:[collectionNFT]}}); // todo clear redundant restrictions?
 
       await addToAllowListExpectSuccess(alice, collectionNFT, bob.address);
       await enableAllowListExpectSuccess(alice, collectionNFT);
@@ -383,7 +452,7 @@
     });
   });
 
-  it('Fungible: disallows to nest token to an unlisted collection', async () => {
+  it('Fungible: disallows to nest token in an unlisted collection', async () => {
     await usingApi(async api => {
       const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
       await setCollectionLimitsExpectSuccess(alice, collectionNFT, {nestingRule: {OwnerRestricted:[]}});
@@ -422,7 +491,7 @@
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
         collectionRFT, 
         targetAddress, 
-        {ReFungible: {const_data: [], variable_data: [], pieces: 100}},
+        {ReFungible: {const_data: [], pieces: 100}},
       ))).to.be.rejectedWith(/^common\.NestingIsDisabled$/);
 
       // Create a token to be nested
@@ -432,7 +501,7 @@
     });
   });
 
-  it('ReFungible: disallows to nest token if not Owner', async () => {
+  it('ReFungible: disallows a non-Owner to nest someone else\'s token', async () => {
     await usingApi(async api => {
       const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
       await setCollectionLimitsExpectSuccess(alice, collectionNFT, {nestingRule: 'Owner'});
@@ -451,7 +520,7 @@
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
         collectionRFT, 
         targetAddress, 
-        {ReFungible: {const_data: [], variable_data: [], pieces: 100}},
+        {ReFungible: {const_data: [], pieces: 100}},
       ))).to.be.rejected;
 
       // Try to create and nest a token in the wrong collection
@@ -460,7 +529,7 @@
     });
   });
 
-  it('ReFungible: disallows to nest token if not Owner (Restricted nesting)', async () => {
+  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]}});
@@ -479,7 +548,7 @@
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
         collectionRFT, 
         targetAddress, 
-        {ReFungible: {const_data: [], variable_data: [], pieces: 100}},
+        {ReFungible: {const_data: [], pieces: 100}},
       ))).to.be.rejected;
 
       // Try to create and nest a token in the wrong collection
@@ -503,7 +572,7 @@
       await expect(executeTransaction(api, alice, api.tx.unique.createItem(
         collectionRFT, 
         targetAddress, 
-        {ReFungible: {const_data: [], variable_data: [], pieces: 100}},
+        {ReFungible: {const_data: [], pieces: 100}},
       ))).to.be.rejected;
 
       // Try to create and nest a token in the wrong collection
modifiedtests/src/nesting/properties.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/properties.test.ts
+++ b/tests/src/nesting/properties.test.ts
@@ -51,13 +51,13 @@
       await expect(executeTransaction(
         api, 
         alice, 
-        api.tx.unique.setCollectionProperties(collectionId, [{key: 'black hole'}]), 
+        api.tx.unique.setCollectionProperties(collectionId, [{key: 'black_hole'}]), 
       )).to.not.be.rejected;
 
-      const properties = (await api.rpc.unique.collectionProperties(collectionId, ['electron', 'black hole'])).toJSON();
+      const properties = (await api.rpc.unique.collectionProperties(collectionId, ['electron', 'black_hole'])).toHuman();
       expect(properties).to.be.deep.equal([
-        {key: `0x${Buffer.from('electron').toString('hex')}`, value: `0x${Buffer.from('come bond').toString('hex')}`},
-        {key: `0x${Buffer.from('black hole').toString('hex')}`, value: `0x${Buffer.from('').toString('hex')}`},
+        {key: 'electron', value: 'come bond'},
+        {key: 'black_hole', value: ''},
       ]);
     });
   });
@@ -69,20 +69,20 @@
       await expect(executeTransaction(
         api, 
         alice, 
-        api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'come bond'}, {key: 'black hole'}]), 
+        api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'come bond'}, {key: 'black_hole'}]), 
       )).to.not.be.rejected;
 
       // Mutate the properties
       await expect(executeTransaction(
         api, 
         alice, 
-        api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'bonded'}, {key: 'black hole', value: 'LIGO'}]), 
+        api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'bonded'}, {key: 'black_hole', value: 'LIGO'}]), 
       )).to.not.be.rejected;
 
-      const properties = (await api.rpc.unique.collectionProperties(collection, ['electron', 'black hole'])).toJSON();
+      const properties = (await api.rpc.unique.collectionProperties(collection, ['electron', 'black_hole'])).toHuman();
       expect(properties).to.be.deep.equal([
-        {key: `0x${Buffer.from('electron').toString('hex')}`, value: `0x${Buffer.from('bonded').toString('hex')}`},
-        {key: `0x${Buffer.from('black hole').toString('hex')}`, value: `0x${Buffer.from('LIGO').toString('hex')}`},
+        {key: 'electron', value: 'bonded'},
+        {key: 'black_hole', value: 'LIGO'},
       ]);
     });
   });
@@ -94,7 +94,7 @@
       await expect(executeTransaction(
         api, 
         alice, 
-        api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'come bond'}, {key: 'black hole', value: 'LIGO'}]), 
+        api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}]), 
       )).to.not.be.rejected;
 
       await expect(executeTransaction(
@@ -103,9 +103,9 @@
         api.tx.unique.deleteCollectionProperties(collection, ['electron']), 
       )).to.not.be.rejected;
 
-      const properties = (await api.rpc.unique.collectionProperties(collection, ['electron', 'black hole'])).toJSON();
+      const properties = (await api.rpc.unique.collectionProperties(collection, ['electron', 'black_hole'])).toHuman();
       expect(properties).to.be.deep.equal([
-        {key: `0x${Buffer.from('black hole').toString('hex')}`, value: `0x${Buffer.from('LIGO').toString('hex')}`},
+        {key: 'black_hole', value: 'LIGO'},
       ]);
     });
   });
@@ -126,7 +126,7 @@
       await expect(executeTransaction(
         api, 
         bob, 
-        api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'come bond'}, {key: 'black hole', value: 'LIGO'}]), 
+        api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}]), 
       )).to.be.rejectedWith(/common\.NoPermission/);
   
       const properties = (await api.query.common.collectionProperties(collection)).toJSON();
@@ -158,7 +158,7 @@
         alice, 
         api.tx.unique.setCollectionProperties(collection, [
           {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 18))}, 
-          {key: 'black hole', value: '0'.repeat(Math.ceil(spaceLimit! / 2))}, 
+          {key: 'black_hole', value: '0'.repeat(Math.ceil(spaceLimit! / 2))}, 
         ]), 
       )).to.be.rejectedWith(/common\.NoSpaceForProperty/);
 
@@ -174,7 +174,7 @@
       const propertiesToBeSet = [];
       for (let i = 0; i < 65; i++) {
         propertiesToBeSet.push({
-          key: 'electron ' + i,
+          key: 'electron_' + i,
           value: Math.random() > 0.5 ? 'high' : 'low',
         });
       }
@@ -190,6 +190,55 @@
       expect(properties.consumedSpace).to.equal(0);
     });
   });
+
+  it('Fails to set properties with invalid names', async () => {
+    await usingApi(async api => {
+      const collection = await createCollectionExpectSuccess();
+
+      const invalidProperties = [
+        [{key: 'electron', value: 'negative'}, {key: 'string theory', value: 'understandable'}],
+        [{key: 'Mr.Sandman', value: 'Bring me a gene'}],
+        [{key: 'déjà vu', value: 'hmm...'}],
+      ];
+
+      for (let i = 0; i < invalidProperties.length; i++) {
+        await expect(executeTransaction(
+          api, 
+          alice, 
+          api.tx.unique.setCollectionProperties(collection, invalidProperties[i]), 
+        ), `on rejecting the new badly-named property #${i}`).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
+      }
+
+      await expect(executeTransaction(
+        api, 
+        alice, 
+        api.tx.unique.setCollectionProperties(collection, [{key: '', value: 'nothing must not exist'}]), 
+      ), `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!'}
+        ]), 
+      ), 'on setting the correctly-but-still-badly-named property').to.not.be.rejected;
+
+      const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat('CRISPR-Cas9').concat('');
+
+      const properties = (await api.rpc.unique.collectionProperties(collection, keys)).toHuman();
+      expect(properties).to.be.deep.equal([
+        {key: 'CRISPR-Cas9', value: 'rewriting nature!'},
+      ]);
+
+      for (let i = 0; i < invalidProperties.length; i++) {
+        await expect(executeTransaction(
+          api, 
+          alice, 
+          api.tx.unique.deleteCollectionProperties(collection, invalidProperties[i].map(propertySet => propertySet.key)), 
+        ), `on trying to delete the non-existent badly-named property #${i}`).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
+      }
+    });
+  });
 });
 
 // ---------- ACCESS RIGHTS
@@ -228,10 +277,10 @@
         api.tx.unique.setPropertyPermissions(collection, [{key: 'mindgame', permission: {collectionAdmin: true, tokenOwner: false}}]), 
       )).to.not.be.rejected;
 
-      const propertyRights = (await api.rpc.unique.propertyPermissions(collection, ['skullduggery', 'mindgame'])).toJSON();
+      const propertyRights = (await api.rpc.unique.propertyPermissions(collection, ['skullduggery', 'mindgame'])).toHuman();
       expect(propertyRights).to.be.deep.equal([
-        {key: `0x${Buffer.from('skullduggery').toString('hex')}`, permission: {'mutable': true, 'collectionAdmin': false, 'tokenOwner': false}},
-        {key: `0x${Buffer.from('mindgame').toString('hex')}`, permission: {'mutable': false, 'collectionAdmin': true, 'tokenOwner': false}},
+        {key: 'skullduggery', permission: {'mutable': true, 'collectionAdmin': false, 'tokenOwner': false}},
+        {key: 'mindgame', permission: {'mutable': false, 'collectionAdmin': true, 'tokenOwner': false}},
       ]);
     });
   });
@@ -252,9 +301,9 @@
         api.tx.unique.setPropertyPermissions(collection, [{key: 'skullduggery', permission: {mutable: false, tokenOwner: true}}]), 
       )).to.not.be.rejected;
 
-      const propertyRights = (await api.rpc.unique.propertyPermissions(collection, ['skullduggery'])).toJSON();
+      const propertyRights = (await api.rpc.unique.propertyPermissions(collection, ['skullduggery'])).toHuman();
       expect(propertyRights).to.be.deep.equal([
-        {key: `0x${Buffer.from('skullduggery').toString('hex')}`, permission: {'mutable': false, 'collectionAdmin': false, 'tokenOwner': true}},
+        {key: 'skullduggery', permission: {'mutable': false, 'collectionAdmin': false, 'tokenOwner': true}},
       ]);
     });
   });
@@ -290,7 +339,7 @@
       const constitution = [];
       for (let i = 0; i < 65; i++) {
         constitution.push({
-          key: 'property ' + i,
+          key: 'property_' + i,
           permission: Math.random() > 0.5 ? {mutable: true, collectionAdmin: true, tokenOwner: true} : {},
         });
       }
@@ -322,9 +371,51 @@
         api.tx.unique.setPropertyPermissions(collection, [{key: 'skullduggery', permission: {}}]), 
       )).to.be.rejectedWith(/common\.NoPermission/);
 
-      const propertyRights = (await api.rpc.unique.propertyPermissions(collection, ['skullduggery'])).toJSON();
+      const propertyRights = (await api.rpc.unique.propertyPermissions(collection, ['skullduggery'])).toHuman();
       expect(propertyRights).to.deep.equal([
-        {key: `0x${Buffer.from('skullduggery').toString('hex')}`, permission: {'mutable': false, 'collectionAdmin': false, 'tokenOwner': true}},
+        {key: 'skullduggery', permission: {'mutable': false, 'collectionAdmin': false, 'tokenOwner': true}},
+      ]);
+    });
+  });
+
+  it('Prevents adding properties with invalid names', async () => {
+    await usingApi(async api => {
+      const collection = await createCollectionExpectSuccess();
+
+      const invalidProperties = [
+        [{key: 'skullduggery', permission: {tokenOwner: true}}, {key: 'im possible', permission: {collectionAdmin: true}}],
+        [{key: 'G#4', permission: {tokenOwner: true}}],
+        [{key: 'HÆMILTON', permission: {mutable: false, collectionAdmin: true, tokenOwner: true}}],
+      ];
+
+      for (let i = 0; i < invalidProperties.length; i++) {
+        await expect(executeTransaction(
+          api, 
+          alice, 
+          api.tx.unique.setPropertyPermissions(collection, invalidProperties[i]), 
+        ), `on setting the new badly-named property #${i}`).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
+      }
+
+      await expect(executeTransaction(
+        api, 
+        alice, 
+        api.tx.unique.setPropertyPermissions(collection, [{key: '', permission: {}}]), 
+      ), `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(
+        api, 
+        alice, 
+        api.tx.unique.setPropertyPermissions(collection, [
+          {key: correctKey, permission: {collectionAdmin: true}},
+        ]), 
+      ), 'on setting the correctly-but-still-badly-named property').to.not.be.rejected;
+
+      const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat(correctKey).concat('');
+
+      const propertyRights = (await api.rpc.unique.propertyPermissions(collection, keys)).toHuman();
+      expect(propertyRights).to.be.deep.equal([
+        {key: correctKey, permission: {mutable: false, collectionAdmin: true, tokenOwner: false}},
       ]);
     });
   });
@@ -361,7 +452,7 @@
     await transferExpectSuccess(collection, token, alice, charlie);
   });
   
-  it('Reads properties of a token', async () => {
+  it('Reads yet empty properties of a token', async () => {
     await usingApi(async api => {
       const collection = await createCollectionExpectSuccess();
       const token = await createItemExpectSuccess(alice, collection, 'NFT');
@@ -381,7 +472,7 @@
       let i = 0;
       for (const permission of permissions) {
         for (const signer of permission.signers) {
-          const key = i + ' ' + signer.address;
+          const key = i + '_' + signer.address;
           propertyKeys.push(key);
 
           await expect(executeTransaction(
@@ -400,11 +491,11 @@
         i++;
       }
 
-      const properties = (await api.rpc.unique.tokenProperties(collection, token, propertyKeys)).toJSON() as any[];
-      const tokensData = (await api.rpc.unique.tokenData(collection, token, propertyKeys)).toJSON().properties as any[];
+      const properties = (await api.rpc.unique.tokenProperties(collection, token, propertyKeys)).toHuman() as any[];
+      const tokensData = (await api.rpc.unique.tokenData(collection, token, propertyKeys)).toHuman().properties as any[];
       for (let i = 0; i < properties.length; i++) {
-        expect(properties[i].value).to.be.equal(`0x${Buffer.from('Serotonin increase').toString('hex')}`);
-        expect(tokensData[i].value).to.be.equal(`0x${Buffer.from('Serotonin increase').toString('hex')}`);
+        expect(properties[i].value).to.be.equal('Serotonin increase');
+        expect(tokensData[i].value).to.be.equal('Serotonin increase');
       }
     });
   });
@@ -417,7 +508,7 @@
         if (!permission.permission.mutable) continue;
         
         for (const signer of permission.signers) {
-          const key = i + ' ' + signer.address;
+          const key = i + '_' + signer.address;
           propertyKeys.push(key);
 
           await expect(executeTransaction(
@@ -442,11 +533,11 @@
         i++;
       }
 
-      const properties = (await api.rpc.unique.tokenProperties(collection, token, propertyKeys)).toJSON() as any[];
-      const tokensData = (await api.rpc.unique.tokenData(collection, token, propertyKeys)).toJSON().properties as any[];
+      const properties = (await api.rpc.unique.tokenProperties(collection, token, propertyKeys)).toHuman() as any[];
+      const tokensData = (await api.rpc.unique.tokenData(collection, token, propertyKeys)).toHuman().properties as any[];
       for (let i = 0; i < properties.length; i++) {
-        expect(properties[i].value).to.be.equal(`0x${Buffer.from('Serotonin stable').toString('hex')}`);
-        expect(tokensData[i].value).to.be.equal(`0x${Buffer.from('Serotonin stable').toString('hex')}`);
+        expect(properties[i].value).to.be.equal('Serotonin stable');
+        expect(tokensData[i].value).to.be.equal('Serotonin stable');
       }
     });
   });
@@ -460,7 +551,7 @@
         if (!permission.permission.mutable) continue;
         
         for (const signer of permission.signers) {
-          const key = i + ' ' + signer.address;
+          const key = i + '_' + signer.address;
           propertyKeys.push(key);
 
           await expect(executeTransaction(
@@ -532,13 +623,13 @@
         await expect(executeTransaction(
           api, 
           alice, 
-          api.tx.unique.setPropertyPermissions(collection, [{key: i, permission: passage.permission}]), 
+          api.tx.unique.setPropertyPermissions(collection, [{key: `${i}`, permission: passage.permission}]), 
         ), `on setting permission ${i} by ${signer.address}`).to.not.be.rejected;
 
         await expect(executeTransaction(
           api, 
           signer, 
-          api.tx.unique.setTokenProperties(collection, token, [{key: i, value: 'Serotonin increase'}]), 
+          api.tx.unique.setTokenProperties(collection, token, [{key: `${i}`, value: 'Serotonin increase'}]), 
         ), `on adding property ${i} by ${signer.address}`).to.not.be.rejected;
 
         i++;
@@ -558,17 +649,16 @@
         await expect(executeTransaction(
           api, 
           forbiddance.sinner, 
-          api.tx.unique.setTokenProperties(collection, token, [{key: i, value: 'Serotonin down'}]), 
+          api.tx.unique.setTokenProperties(collection, token, [{key: `${i}`, value: 'Serotonin down'}]), 
         ), `on failing to change property ${i} by ${forbiddance.sinner.address}`).to.be.rejectedWith(/common\.NoPermission/);
 
         await expect(executeTransaction(
           api, 
           forbiddance.sinner, 
-          api.tx.unique.deleteTokenProperties(collection, token, [forbiddance.permission]), 
+          api.tx.unique.deleteTokenProperties(collection, token, [`${i}`]), 
         ), `on failing to delete property ${i} by ${forbiddance.sinner.address}`).to.be.rejectedWith(/common\.NoPermission/);
       }
 
-      // todo RPC?
       const properties = (await api.query.nonfungible.tokenProperties(collection, token)).toJSON();
       expect(properties.consumedSpace).to.be.equal(originalSpace);
     });
@@ -584,7 +674,7 @@
         await expect(executeTransaction(
           api, 
           permission.signers[0], 
-          api.tx.unique.setTokenProperties(collection, token, [{key: i, value: 'Serotonin down'}]), 
+          api.tx.unique.setTokenProperties(collection, token, [{key: `${i}`, value: 'Serotonin down'}]), 
         ), `on failing to change property ${i} by ${permission.signers[0].address}`).to.be.rejectedWith(/common\.NoPermission/);
 
         await expect(executeTransaction(
@@ -594,7 +684,6 @@
         ), `on failing to delete property ${i} by ${permission.signers[0].address}`).to.be.rejectedWith(/common\.NoPermission/);
       }
 
-      // todo RPC?
       const properties = (await api.query.nonfungible.tokenProperties(collection, token)).toJSON();
       expect(properties.consumedSpace).to.be.equal(originalSpace);
     });
@@ -632,8 +721,8 @@
         api, 
         alice, 
         api.tx.unique.setPropertyPermissions(collection, [
-          {key: 'a holy book', permission: {collectionAdmin: true, tokenOwner: true}}, 
-          {key: 'young years', permission: {collectionAdmin: true, tokenOwner: true}},
+          {key: 'a_holy_book', permission: {collectionAdmin: true, tokenOwner: true}}, 
+          {key: 'young_years', permission: {collectionAdmin: true, tokenOwner: true}},
         ]), 
       ), 'on setting a new non-permitted property').to.not.be.rejected;
 
@@ -643,7 +732,7 @@
         await expect(executeTransaction(
           api, 
           alice, 
-          api.tx.unique.setCollectionProperties(collection, [{key: 'a holy book', value: 'word '.repeat(6554)}]), 
+          api.tx.unique.setCollectionProperties(collection, [{key: 'a_holy_book', value: 'word '.repeat(6554)}]), 
         )).to.be.rejected;
       }
 
@@ -651,12 +740,12 @@
         api, 
         alice, 
         api.tx.unique.setTokenProperties(collection, token, [
-          {key: 'a holy book', value: 'word '.repeat(3277)}, 
-          {key: 'young years', value: 'neverending'.repeat(1490)},
+          {key: 'a_holy_book', value: 'word '.repeat(3277)}, 
+          {key: 'young_years', value: 'neverending'.repeat(1490)},
         ]), 
       )).to.be.rejectedWith(/common\.NoSpaceForProperty/);
 
-      expect((await api.rpc.unique.tokenProperties(collection, token, ['a holy book', 'young years'])).toJSON()).to.be.empty;
+      expect((await api.rpc.unique.tokenProperties(collection, token, ['a_holy_book', 'young years'])).toJSON()).to.be.empty;
       const propertiesMap = (await api.query.nonfungible.tokenProperties(collection, token)).toJSON();
       expect(propertiesMap.consumedSpace).to.be.equal(originalSpace);
     });
modifiedtests/src/nesting/unnest.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/unnest.test.ts
+++ b/tests/src/nesting/unnest.test.ts
@@ -6,11 +6,13 @@
   createCollectionExpectSuccess,
   createItemExpectFailure,
   createItemExpectSuccess,
+  getBalance,
   getTokenOwner,
   getTopmostTokenOwner,
   normalizeAccountId,
   setCollectionLimitsExpectSuccess,
   transferExpectSuccess,
+  transferFromExpectSuccess,
 } from '../util/helpers';
 import {IKeyringPair} from '@polkadot/types/types';
 
@@ -25,7 +27,7 @@
     });
   });
 
-  it('Allows the owner to successfully unnest a token', async () => {
+  it('NFT: allows the owner to successfully unnest a token', async () => {
     await usingApi(async api => {
       const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
       await setCollectionLimitsExpectSuccess(alice, collection, {nestingRule: 'Owner'});
@@ -40,7 +42,7 @@
         api,
         alice,
         api.tx.unique.transferFrom(normalizeAccountId(targetAddress), normalizeAccountId(alice), collection, nestedToken, 1),
-      )).to.not.be.rejected;
+      ), 'while unnesting').to.not.be.rejected;
       expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: alice.address});
 
       // Nest and burn
@@ -48,13 +50,64 @@
       await expect(executeTransaction(
         api,
         alice,
-        api.tx.unique.burnFrom(collection, normalizeAccountId(alice.address), nestedToken, 1),
-      )).to.not.be.rejected;
-      await expect(getTokenOwner(api, collection, nestedToken)).to.be.rejected; // 'owner == null'
+        api.tx.unique.burnFrom(collection, normalizeAccountId(targetAddress), nestedToken, 1),
+      ), 'while burning').to.not.be.rejected;
+      await expect(getTokenOwner(api, collection, nestedToken)).to.be.rejected;
     });
   });
 
-  // todo refungible-fungible test just in case
+  it('Fungible: allows the owner to successfully unnest a token', async () => {
+    await usingApi(async api => {
+      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+      await setCollectionLimitsExpectSuccess(alice, collection, {nestingRule: 'Owner'});
+      const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
+      const targetAddress = {Ethereum: tokenIdToAddress(collection, targetToken)};
+
+      const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+      const nestedToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
+
+      // Nest and unnest
+      await transferExpectSuccess(collectionFT, nestedToken, alice, targetAddress, 1, 'Fungible');
+      await transferFromExpectSuccess(collectionFT, nestedToken, alice, targetAddress, alice, 1, 'Fungible');
+
+      // Nest and burn
+      await transferExpectSuccess(collectionFT, nestedToken, alice, targetAddress, 1, 'Fungible');
+      const balanceBefore = await getBalance(api, collectionFT, normalizeAccountId(targetAddress), nestedToken);
+      await expect(executeTransaction(
+        api,
+        alice,
+        api.tx.unique.burnFrom(collectionFT, normalizeAccountId(targetAddress), nestedToken, 1),
+      ), 'while burning').to.not.be.rejected;
+      const balanceAfter = await getBalance(api, collectionFT, normalizeAccountId(targetAddress), nestedToken);
+      expect(balanceAfter + BigInt(1)).to.be.equal(balanceBefore);
+    });
+  });
+
+  it('ReFungible: allows the owner to successfully unnest a token', async () => {
+    await usingApi(async api => {
+      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+      await setCollectionLimitsExpectSuccess(alice, collection, {nestingRule: 'Owner'});
+      const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
+      const targetAddress = {Ethereum: tokenIdToAddress(collection, targetToken)};
+
+      const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
+      const nestedToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
+
+      // Nest and unnest
+      await transferExpectSuccess(collectionRFT, nestedToken, alice, targetAddress, 1, 'ReFungible');
+      await transferFromExpectSuccess(collectionRFT, nestedToken, alice, targetAddress, alice, 1, 'ReFungible');
+
+      // Nest and burn
+      await transferExpectSuccess(collectionRFT, nestedToken, alice, targetAddress, 1, 'ReFungible');
+      await expect(executeTransaction(
+        api,
+        alice,
+        api.tx.unique.burnFrom(collectionRFT, normalizeAccountId(targetAddress), nestedToken, 1),
+      ), 'while burning').to.not.be.rejected;
+      const balance = await getBalance(api, collectionRFT, normalizeAccountId(targetAddress), nestedToken);
+      expect(balance).to.be.equal(0n);
+    });
+  });
 });
 
 describe('Negative Test: Unnesting', () => {
@@ -80,8 +133,7 @@
         api,
         bob,
         api.tx.unique.transferFrom(normalizeAccountId(targetAddress), normalizeAccountId(bob), collection, nestedToken, 1),
-      )).to.be.rejectedWith(/^common\.ApprovedValueTooLow$/);
-      //await transferFromExpectSuccess(collection, nestedToken, bob, targetAddress, {Substrate: bob.address});
+      ), 'while unnesting').to.be.rejectedWith(/^structure\.DepthLimit$/); // todo ApprovedValueTooLow?
       expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
 
       // Try to burn
@@ -89,31 +141,15 @@
         api,
         bob,
         api.tx.unique.burnFrom(collection, normalizeAccountId(bob.address), nestedToken, 1),
-      )).to.not.be.rejectedWith(/^common\.ApprovedValueTooLow$/);
+      ), 'while burning').to.not.be.rejectedWith(/^common\.ApprovedValueTooLow$/);
       expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
     });
   });
 
-  it('Disallows excessive token nesting', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionLimitsExpectSuccess(alice, collection, {nestingRule: 'Owner'});
-      const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
-
-      // Create a nested token matryoshka
-      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 createItemExpectFailure(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, nestedToken2)});
+  // todo another test for creating excessive depth matryoshka with Ethereum?
 
-      expect(await getTopmostTokenOwner(api, collection, nestedToken2)).to.be.deep.equal({Substrate: alice.address});
-    });
-  });
-
-  // todo another test for creating excessive depth matryoshka with Ethereum, move this one to nest ^
-
   // Recursive nesting
-  it('Prevents ouroboros creation', async () => {
+  it('Prevents Ouroboros creation', async () => {
     const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
     await setCollectionLimitsExpectSuccess(alice, collection, {nestingRule: 'Owner'});
     const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
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') {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(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  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}