git.delta.rocks / unique-network / refs/commits / 71f425f89b51

difftreelog

fix(tests) repair createMultipleItem + ..Ex, remove features made obsolete by properties

Fahrrader2022-05-30parent: #2dd1788.patch.diff
in: master

9 files changed

modifiedtests/src/contracts.test.tsdiffbeforeafterboth
--- a/tests/src/contracts.test.ts
+++ b/tests/src/contracts.test.ts
@@ -139,9 +139,9 @@
       await addToAllowListExpectSuccess(alice, collectionId, bob.address);
 
       const transferTx = contract.tx.createMultipleItems(value, gasLimit, bob.address, collectionId, [
-        {Nft: {const_data: '0x010203'}},
-        {Nft: {const_data: '0x010204'}},
-        {Nft: {const_data: '0x010205'}},
+        {NFT: {/*const_data: '0x010203'*/}},
+        {NFT: {/*const_data: '0x010204'*/}},
+        {NFT: {/*const_data: '0x010205'*/}},
       ]);
       const events = await submitTransactionAsync(alice, transferTx);
       const result = getGenericResult(events);
@@ -153,15 +153,15 @@
       expect(tokensAfter).to.be.deep.equal([
         {
           Owner: bob.address,
-          ConstData: '0x010203',
+          //ConstData: '0x010203',
         },
         {
           Owner: bob.address,
-          ConstData: '0x010204',
+          //ConstData: '0x010204',
         },
         {
           Owner: bob.address,
-          ConstData: '0x010205',
+          //ConstData: '0x010205',
         },
       ]);
     });
modifiedtests/src/createCollection.test.tsdiffbeforeafterboth
--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -63,17 +63,17 @@
       const bob = privateKey('//Bob');
       const tx = api.tx.unique.createCollectionEx({
         mode: {Fungible: 8},
-        access: 'AllowList',
+        //access: 'AllowList',
         name: [1],
         description: [2],
         tokenPrefix: '0x000000',
-        offchainSchema: '0x111111',
-        schemaVersion: 'Unique',
+        //offchainSchema: '0x111111',
+        //schemaVersion: 'Unique',
         pendingSponsor: bob.address,
         limits: {
           accountTokenOwnershipLimit: 3,
         },
-        constOnChainSchema: '0x333333',
+        //constOnChainSchema: '0x333333',
       });
       const events = await submitTransactionAsync(alice, tx);
       const result = getCreateCollectionResult(events);
@@ -81,15 +81,15 @@
       const collection = (await getDetailedCollectionInfo(api, result.collectionId))!;
       expect(collection.owner.toString()).to.equal(alice.address);
       expect(collection.mode.asFungible.toNumber()).to.equal(8);
-      expect(collection.access.isAllowList).to.be.true;
+      //expect(collection.access.isAllowList).to.be.true;
       expect(collection.name.map(v => v.toNumber())).to.deep.equal([1]);
       expect(collection.description.map(v => v.toNumber())).to.deep.equal([2]);
       expect(collection.tokenPrefix.toString()).to.equal('0x000000');
-      expect(collection.offchainSchema.toString()).to.equal('0x111111');
-      expect(collection.schemaVersion.isUnique).to.be.true;
+      //expect(collection.offchainSchema.toString()).to.equal('0x111111');
+      //expect(collection.schemaVersion.isUnique).to.be.true;
       expect(collection.sponsorship.asUnconfirmed.toString()).to.equal(bob.address);
       expect(collection.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.equal(3);
-      expect(collection.constOnChainSchema.toString()).to.equal('0x333333');
+      //expect(collection.constOnChainSchema.toString()).to.equal('0x333333');
     });
   });
 });
modifiedtests/src/createMultipleItems.test.tsdiffbeforeafterboth
--- a/tests/src/createMultipleItems.test.ts
+++ b/tests/src/createMultipleItems.test.ts
@@ -30,29 +30,34 @@
   getBalance,
   getTokenOwner,
   getLastTokenId,
-  getConstMetadata,
   getCreatedCollectionCount,
   createCollectionWithPropsExpectSuccess,
-  getCreateItemsResult,
   createMultipleItemsWithPropsExpectSuccess,
-  createMultipleItemsWithPropsExpectFailure,
+  getTokenProperties,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
 const expect = chai.expect;
 
 describe('Integration Test createMultipleItems(collection_id, owner, items_data):', () => {
-  it('Create  0x31, 0x32, 0x33 items in active NFT collection and verify tokens data in chain', async () => {
+  it('Create 0x31, 0x32, 0x33 items in active NFT collection and verify tokens data in chain', async () => {
     await usingApi(async (api: ApiPromise) => {
       const collectionId = await createCollectionExpectSuccess();
       const itemsListIndexBefore = await getLastTokenId(api, collectionId);
       expect(itemsListIndexBefore).to.be.equal(0);
+
       const alice = privateKey('//Alice');
-      const args = [{Nft: {const_data: '0x31'}},
-        {Nft: {const_data: '0x32'}},
-        {Nft: {const_data: '0x33'}}];
-      const createMultipleItemsTx = api.tx.unique
-        .createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
+      await submitTransactionAsync(
+        alice, 
+        api.tx.unique.setPropertyPermissions(collectionId, [{key: 'data', permission: {tokenOwner: true}}])
+      );
+      
+      const args = [
+        {NFT: {properties: [{key: 'data', value: '1'}]}},
+        {NFT: {properties: [{key: 'data', value: '2'}]}},
+        {NFT: {properties: [{key: 'data', value: '3'}]}}
+      ];
+      const createMultipleItemsTx = api.tx.unique.createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
       await submitTransactionAsync(alice, createMultipleItemsTx);
       const itemsListIndexAfter = await getLastTokenId(api, collectionId);
       expect(itemsListIndexAfter).to.be.equal(3);
@@ -61,13 +66,13 @@
       expect(await getTokenOwner(api, collectionId, 2)).to.be.deep.equal(normalizeAccountId(alice.address));
       expect(await getTokenOwner(api, collectionId, 3)).to.be.deep.equal(normalizeAccountId(alice.address));
 
-      expect(await getConstMetadata(api, collectionId, 1)).to.be.deep.equal([0x31]);
-      expect(await getConstMetadata(api, collectionId, 2)).to.be.deep.equal([0x32]);
-      expect(await getConstMetadata(api, collectionId, 3)).to.be.deep.equal([0x33]);
+      expect((await getTokenProperties(api, collectionId, 1, ['data']))[0].value).to.be.equal('1');
+      expect((await getTokenProperties(api, collectionId, 2, ['data']))[0].value).to.be.equal('2');
+      expect((await getTokenProperties(api, collectionId, 3, ['data']))[0].value).to.be.equal('3');
     });
   });
 
-  it('Create  0x01, 0x02, 0x03 items in active Fungible collection and verify tokens data in chain', async () => {
+  it('Create 0x01, 0x02, 0x03 items in active Fungible collection and verify tokens data in chain', async () => {
     await usingApi(async (api: ApiPromise) => {
       const collectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
       const itemsListIndexBefore = await getLastTokenId(api, collectionId);
@@ -87,16 +92,16 @@
     });
   });
 
-  it('Create  0x31, 0x32, 0x33 items in active ReFungible collection and verify tokens data in chain', async () => {
+  it('Create 0x31, 0x32, 0x33 items in active ReFungible collection and verify tokens data in chain', async () => {
     await usingApi(async (api: ApiPromise) => {
       const collectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
       const itemsListIndexBefore = await getLastTokenId(api, collectionId);
       expect(itemsListIndexBefore).to.be.equal(0);
       const alice = privateKey('//Alice');
       const args = [
-        {ReFungible: {const_data: [0x31], pieces: 1}},
-        {ReFungible: {const_data: [0x32], pieces: 1}},
-        {ReFungible: {const_data: [0x33], pieces: 1}},
+        {ReFungible: {pieces: 1}},
+        {ReFungible: {pieces: 2}},
+        {ReFungible: {pieces: 3}},
       ];
       const createMultipleItemsTx = api.tx.unique
         .createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
@@ -105,12 +110,8 @@
       expect(itemsListIndexAfter).to.be.equal(3);
 
       expect(await getBalance(api, collectionId, alice.address, 1)).to.be.equal(1n);
-      expect(await getBalance(api, collectionId, alice.address, 2)).to.be.equal(1n);
-      expect(await getBalance(api, collectionId, alice.address, 3)).to.be.equal(1n);
-
-      expect(await getConstMetadata(api, collectionId, 1)).to.be.deep.equal([0x31]);
-      expect(await getConstMetadata(api, collectionId, 2)).to.be.deep.equal([0x32]);
-      expect(await getConstMetadata(api, collectionId, 3)).to.be.deep.equal([0x33]);
+      expect(await getBalance(api, collectionId, alice.address, 2)).to.be.equal(2n);
+      expect(await getBalance(api, collectionId, alice.address, 3)).to.be.equal(3n);
     });
   });
 
@@ -123,8 +124,8 @@
         tokenLimit: 2,
       });
       const args = [
-        {NFT: {const_data: 'A'}},
-        {NFT: {const_data: 'B'}},
+        {NFT: {}},
+        {NFT: {}},
       ];
       const createMultipleItemsTx = api.tx.unique.createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
       const events = await submitTransactionAsync(alice, createMultipleItemsTx);
@@ -133,16 +134,17 @@
     });
   });
 
-  it('Create  0x31, 0x32, 0x33 items in active NFT with property Admin', async () => {
+  it('Create 0x31, 0x32, 0x33 items in active NFT with property Admin', async () => {
     await usingApi(async (api: ApiPromise) => {
       const collectionId = await createCollectionWithPropsExpectSuccess({propPerm: [{key: 'k', permission: {mutable: true, collectionAdmin: true, tokenOwner: false}}]});
       const itemsListIndexBefore = await getLastTokenId(api, collectionId);
       expect(itemsListIndexBefore).to.be.equal(0);
       const alice = privateKey('//Alice');
-      const bob = privateKey('//Bob');
-      const args = [{Nft: {const_data: '0x31', properties: [{key: 'k', value: 'v1'}]}},
-        {Nft: {const_data: '0x32', properties: [{key: 'k', value: 'v2'}]}},
-        {Nft: {const_data: '0x33', properties: [{key: 'k', value: 'v3'}]}}];
+      const args = [
+        {NFT: {properties: [{key: 'k', value: 'v1'}]}},
+        {NFT: {properties: [{key: 'k', value: 'v2'}]}},
+        {NFT: {properties: [{key: 'k', value: 'v3'}]}}
+      ];
 
       await createMultipleItemsWithPropsExpectSuccess(alice, collectionId, args);
       const itemsListIndexAfter = await getLastTokenId(api, collectionId);
@@ -152,13 +154,13 @@
       expect(await getTokenOwner(api, collectionId, 2)).to.be.deep.equal(normalizeAccountId(alice.address));
       expect(await getTokenOwner(api, collectionId, 3)).to.be.deep.equal(normalizeAccountId(alice.address));
 
-      expect(await getConstMetadata(api, collectionId, 1)).to.be.deep.equal([0x31]);
-      expect(await getConstMetadata(api, collectionId, 2)).to.be.deep.equal([0x32]);
-      expect(await getConstMetadata(api, collectionId, 3)).to.be.deep.equal([0x33]);
+      expect((await getTokenProperties(api, collectionId, 1, ['k']))[0].value).to.be.equal('v1');
+      expect((await getTokenProperties(api, collectionId, 2, ['k']))[0].value).to.be.equal('v2');
+      expect((await getTokenProperties(api, collectionId, 3, ['k']))[0].value).to.be.equal('v3');
     });
   });
 
-  it('Create  0x31, 0x32, 0x33 items in active NFT with property AdminConst', async () => {
+  it('Create 0x31, 0x32, 0x33 items in active NFT with property AdminConst', async () => {
     await usingApi(async (api: ApiPromise) => {
       const collectionId = await createCollectionWithPropsExpectSuccess({propPerm: [{key: 'k', permission: {mutable: false, collectionAdmin: true, tokenOwner: false}}]});
       const itemsListIndexBefore = await getLastTokenId(api, collectionId);
@@ -166,9 +168,11 @@
       const alice = privateKey('//Alice');
       const bob = privateKey('//Bob');
       await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
-      const args = [{Nft: {const_data: '0x31', properties: [{key: 'k', value: 'v1'}]}},
-        {Nft: {const_data: '0x32', properties: [{key: 'k', value: 'v2'}]}},
-        {Nft: {const_data: '0x33', properties: [{key: 'k', value: 'v3'}]}}];
+      const args = [
+        {NFT: {properties: [{key: 'k', value: 'v1'}]}},
+        {NFT: {properties: [{key: 'k', value: 'v2'}]}},
+        {NFT: {properties: [{key: 'k', value: 'v3'}]}}
+      ];
 
       await createMultipleItemsWithPropsExpectSuccess(alice, collectionId, args);
       const itemsListIndexAfter = await getLastTokenId(api, collectionId);
@@ -178,22 +182,25 @@
       expect(await getTokenOwner(api, collectionId, 2)).to.be.deep.equal(normalizeAccountId(alice.address));
       expect(await getTokenOwner(api, collectionId, 3)).to.be.deep.equal(normalizeAccountId(alice.address));
 
-      expect(await getConstMetadata(api, collectionId, 1)).to.be.deep.equal([0x31]);
-      expect(await getConstMetadata(api, collectionId, 2)).to.be.deep.equal([0x32]);
-      expect(await getConstMetadata(api, collectionId, 3)).to.be.deep.equal([0x33]);
+      expect((await getTokenProperties(api, collectionId, 1, ['k']))[0].value).to.be.equal('v1');
+      expect((await getTokenProperties(api, collectionId, 2, ['k']))[0].value).to.be.equal('v2');
+      expect((await getTokenProperties(api, collectionId, 3, ['k']))[0].value).to.be.equal('v3');
     });
   });
 
-  it('Create  0x31, 0x32, 0x33 items in active NFT with property itemOwnerOrAdmin', async () => {
+  it('Create 0x31, 0x32, 0x33 items in active NFT with property itemOwnerOrAdmin', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const collectionId = await createCollectionWithPropsExpectSuccess({propPerm: [{key: 'k', permission: {mutable: true, collectionAdmin: true, tokenOwner: true}}]});
+      const collectionId = await createCollectionWithPropsExpectSuccess(
+        {propPerm: [{key: 'k', permission: {mutable: true, collectionAdmin: true, tokenOwner: true}}]}
+      );
       const itemsListIndexBefore = await getLastTokenId(api, collectionId);
       expect(itemsListIndexBefore).to.be.equal(0);
       const alice = privateKey('//Alice');
-      const bob = privateKey('//Bob');
-      const args = [{Nft: {const_data: '0x31', properties: [{key: 'k', value: 'v1'}]}},
-        {Nft: {const_data: '0x32', properties: [{key: 'k', value: 'v2'}]}},
-        {Nft: {const_data: '0x33', properties: [{key: 'k', value: 'v3'}]}}];
+      const args = [
+        {NFT: {properties: [{key: 'k', value: 'v1'}]}},
+        {NFT: {properties: [{key: 'k', value: 'v2'}]}},
+        {NFT: {properties: [{key: 'k', value: 'v3'}]}}
+      ];
 
       await createMultipleItemsWithPropsExpectSuccess(alice, collectionId, args);
       const itemsListIndexAfter = await getLastTokenId(api, collectionId);
@@ -203,15 +210,14 @@
       expect(await getTokenOwner(api, collectionId, 2)).to.be.deep.equal(normalizeAccountId(alice.address));
       expect(await getTokenOwner(api, collectionId, 3)).to.be.deep.equal(normalizeAccountId(alice.address));
 
-      expect(await getConstMetadata(api, collectionId, 1)).to.be.deep.equal([0x31]);
-      expect(await getConstMetadata(api, collectionId, 2)).to.be.deep.equal([0x32]);
-      expect(await getConstMetadata(api, collectionId, 3)).to.be.deep.equal([0x33]);
+      expect((await getTokenProperties(api, collectionId, 1, ['k']))[0].value).to.be.equal('v1');
+      expect((await getTokenProperties(api, collectionId, 2, ['k']))[0].value).to.be.equal('v2');
+      expect((await getTokenProperties(api, collectionId, 3, ['k']))[0].value).to.be.equal('v3');
     });
   });
 });
 
 describe('Integration Test createMultipleItems(collection_id, owner, items_data) with collection admin permissions:', () => {
-
   let alice: IKeyringPair;
   let bob: IKeyringPair;
 
@@ -222,15 +228,19 @@
     });
   });
 
-  it('Create  0x31, 0x32, 0x33 items in active NFT collection and verify tokens data in chain', async () => {
+  it('Create 0x31, 0x32, 0x33 items in active NFT collection and verify tokens data in chain', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const collectionId = await createCollectionExpectSuccess();
+      const collectionId = await createCollectionWithPropsExpectSuccess(
+        {propPerm: [{key: 'data', permission: {mutable: true, collectionAdmin: true, tokenOwner: true}}]}
+      );
       const itemsListIndexBefore = await getLastTokenId(api, collectionId);
       expect(itemsListIndexBefore).to.be.equal(0);
       await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
-      const args = [{Nft: {const_data: '0x31'}},
-        {Nft: {const_data: '0x32'}},
-        {Nft: {const_data: '0x33'}}];
+      const args = [
+        {NFT: {properties: [{key: 'data', value: 'v1'}]}},
+        {NFT: {properties: [{key: 'data', value: 'v2'}]}},
+        {NFT: {properties: [{key: 'data', value: 'v3'}]}}
+      ];
       const createMultipleItemsTx = api.tx.unique
         .createMultipleItems(collectionId, normalizeAccountId(bob.address), args);
       await submitTransactionAsync(bob, createMultipleItemsTx);
@@ -241,13 +251,13 @@
       expect(await getTokenOwner(api, collectionId, 2)).to.be.deep.equal(normalizeAccountId(bob.address));
       expect(await getTokenOwner(api, collectionId, 3)).to.be.deep.equal(normalizeAccountId(bob.address));
 
-      expect(await getConstMetadata(api, collectionId, 1)).to.be.deep.equal([0x31]);
-      expect(await getConstMetadata(api, collectionId, 2)).to.be.deep.equal([0x32]);
-      expect(await getConstMetadata(api, collectionId, 3)).to.be.deep.equal([0x33]);
+      expect((await getTokenProperties(api, collectionId, 1, ['data']))[0].value).to.be.equal('v1');
+      expect((await getTokenProperties(api, collectionId, 2, ['data']))[0].value).to.be.equal('v2');
+      expect((await getTokenProperties(api, collectionId, 3, ['data']))[0].value).to.be.equal('v3');
     });
   });
 
-  it('Create  0x01, 0x02, 0x03 items in active Fungible collection and verify tokens data in chain', async () => {
+  it('Create 0x01, 0x02, 0x03 items in active Fungible collection and verify tokens data in chain', async () => {
     await usingApi(async (api: ApiPromise) => {
       const collectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
       const itemsListIndexBefore = await getLastTokenId(api, collectionId);
@@ -267,16 +277,16 @@
     });
   });
 
-  it('Create  0x31, 0x32, 0x33 items in active ReFungible collection and verify tokens data in chain', async () => {
+  it('Create 0x31, 0x32, 0x33 items in active ReFungible collection and verify tokens data in chain', async () => {
     await usingApi(async (api: ApiPromise) => {
       const collectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
       const itemsListIndexBefore = await getLastTokenId(api, collectionId);
       expect(itemsListIndexBefore).to.be.equal(0);
       await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
       const args = [
-        {ReFungible: {const_data: [0x31], pieces: 1}},
-        {ReFungible: {const_data: [0x32], pieces: 1}},
-        {ReFungible: {const_data: [0x33], pieces: 1}},
+        {ReFungible: {pieces: 1}},
+        {ReFungible: {pieces: 2}},
+        {ReFungible: {pieces: 3}},
       ];
       const createMultipleItemsTx = api.tx.unique
         .createMultipleItems(collectionId, normalizeAccountId(bob.address), args);
@@ -285,18 +295,13 @@
       expect(itemsListIndexAfter).to.be.equal(3);
 
       expect(await getBalance(api, collectionId, bob.address, 1)).to.be.equal(1n);
-      expect(await getBalance(api, collectionId, bob.address, 2)).to.be.equal(1n);
-      expect(await getBalance(api, collectionId, bob.address, 3)).to.be.equal(1n);
-
-      expect(await getConstMetadata(api, collectionId, 1)).to.be.deep.equal([0x31]);
-      expect(await getConstMetadata(api, collectionId, 2)).to.be.deep.equal([0x32]);
-      expect(await getConstMetadata(api, collectionId, 3)).to.be.deep.equal([0x33]);
+      expect(await getBalance(api, collectionId, bob.address, 2)).to.be.equal(2n);
+      expect(await getBalance(api, collectionId, bob.address, 3)).to.be.equal(3n);
     });
   });
 });
 
 describe('Negative Integration Test createMultipleItems(collection_id, owner, items_data):', () => {
-
   let alice: IKeyringPair;
   let bob: IKeyringPair;
 
@@ -312,12 +317,11 @@
       const collectionId = await createCollectionExpectSuccess();
       const itemsListIndexBefore = await getLastTokenId(api, collectionId);
       expect(itemsListIndexBefore).to.be.equal(0);
-      const args = [{Nft: {const_data: '0x31'}},
-        {Nft: {const_data: '0x32'}},
-        {Nft: {const_data: '0x33'}}];
-      const createMultipleItemsTx = api.tx.unique
-        .createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
-      await expect(submitTransactionAsync(bob, createMultipleItemsTx)).to.be.rejected;
+      const args = [{NFT: {}},
+        {NFT: {}},
+        {NFT: {}}];
+      const createMultipleItemsTx = api.tx.unique.createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
+      await expect(executeTransaction(api, bob, createMultipleItemsTx)).to.be.rejectedWith(/common\.PublicMintingNotAllowed/);
     });
   });
 
@@ -331,9 +335,8 @@
         {Fungible: {value: 2}},
         {Fungible: {value: 3}},
       ];
-      const createMultipleItemsTx = api.tx.unique
-        .createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
-      await expect(submitTransactionAsync(bob, createMultipleItemsTx)).to.be.rejected;
+      const createMultipleItemsTx = api.tx.unique.createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
+      await expect(executeTransaction(api, bob, createMultipleItemsTx)).to.be.rejectedWith(/common\.PublicMintingNotAllowed/);
     });
   });
 
@@ -343,37 +346,38 @@
       const itemsListIndexBefore = await getLastTokenId(api, collectionId);
       expect(itemsListIndexBefore).to.be.equal(0);
       const args = [
-        {ReFungible: {const_data: [0x31], pieces: 1}},
-        {ReFungible: {const_data: [0x32], pieces: 1}},
-        {ReFungible: {const_data: [0x33], pieces: 1}},
+        {ReFungible: {pieces: 1}},
+        {ReFungible: {pieces: 1}},
+        {ReFungible: {pieces: 1}},
       ];
-      const createMultipleItemsTx = api.tx.unique
-        .createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
-      await expect(submitTransactionAsync(bob, createMultipleItemsTx)).to.be.rejected;
+      const createMultipleItemsTx = api.tx.unique.createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
+      await expect(executeTransaction(api, bob, createMultipleItemsTx)).to.be.rejectedWith(/common\.PublicMintingNotAllowed/);
     });
   });
 
   it('Create token in not existing collection', async () => {
     await usingApi(async (api: ApiPromise) => {
       const collectionId = await getCreatedCollectionCount(api) + 1;
-      const createMultipleItemsTx = api.tx.unique
-        .createMultipleItems(collectionId, normalizeAccountId(alice.address), ['NFT', 'NFT', 'NFT']);
-      await expect(submitTransactionExpectFailAsync(alice, createMultipleItemsTx)).to.be.rejected;
+      const createMultipleItemsTx = api.tx.unique.createMultipleItems(
+        collectionId, normalizeAccountId(alice.address), ['NFT', 'NFT', 'NFT']
+      );
+      await expect(executeTransaction(api, alice, createMultipleItemsTx)).to.be.rejectedWith(/common\.CollectionNotFound/);
     });
   });
 
   it('Create NFT and Re-fungible tokens that has reached the maximum data limit', async () => {
     await usingApi(async (api: ApiPromise) => {
       // NFT
-      const collectionId = await createCollectionExpectSuccess();
+      const collectionId = await createCollectionWithPropsExpectSuccess({
+        propPerm: [{key: 'key', permission: {mutable: true, collectionAdmin: true, tokenOwner: true}}]
+      });
       const alice = privateKey('//Alice');
       const args = [
-        {NFT: {const_data: 'A'.repeat(2049)}},
-        {NFT: {const_data: 'B'.repeat(2049)}},
-        {NFT: {const_data: 'C'.repeat(2049)}},
+        {NFT: {properties: [{key: 'key', value: 'A'.repeat(32769)}]}},
+        {NFT: {properties: [{key: 'key', value: 'B'.repeat(32769)}]}},
+        {NFT: {properties: [{key: 'key', value: 'C'.repeat(32769)}]}},
       ];
-      const createMultipleItemsTx = api.tx.unique
-        .createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
+      const createMultipleItemsTx = api.tx.unique.createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
       await expect(submitTransactionExpectFailAsync(alice, createMultipleItemsTx)).to.be.rejected;
 
       // ReFungible
@@ -395,68 +399,61 @@
       const collectionId = await createCollectionExpectSuccess();
       const createMultipleItemsTx = api.tx.unique
         .createMultipleItems(collectionId, normalizeAccountId(alice.address), ['NFT', 'Fungible', 'ReFungible']);
-      await expect(submitTransactionExpectFailAsync(alice, createMultipleItemsTx)).to.be.rejected;
-      // garbage collection :-D
+      await expect(
+        executeTransaction(api, alice, createMultipleItemsTx)
+      ).to.be.rejectedWith(
+        /nonfungible\.NotNonfungibleDataUsedToMintFungibleCollectionToken/
+      );
+      // garbage collection :-D // lol
       await destroyCollectionExpectSuccess(collectionId);
     });
   });
 
   it('Create tokens with different data limits <> maximum data limit', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const collectionId = await createCollectionExpectSuccess();
+      const collectionId = await createCollectionWithPropsExpectSuccess({
+        propPerm: [{key: 'key', permission: {mutable: true, collectionAdmin: true, tokenOwner: true}}]
+      });
       const args = [
-        {NFT: {const_data: 'A'}},
-        {NFT: {const_data: 'B'.repeat(2049)}},
+        {NFT: {properties: [{key: 'key', value: 'A'}]}},
+        {NFT: {properties: [{key: 'key', value: 'B'.repeat(32769)}]}},
       ];
-      const createMultipleItemsTx = await api.tx.unique
-        .createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
+      const createMultipleItemsTx = api.tx.unique.createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
       await expect(submitTransactionExpectFailAsync(alice, createMultipleItemsTx)).to.be.rejected;
     });
   });
 
   it('Fails when minting tokens exceeds collectionLimits amount', async () => {
     await usingApi(async (api) => {
-
       const collectionId = await createCollectionExpectSuccess();
       await setCollectionLimitsExpectSuccess(alice, collectionId, {
         tokenLimit: 1,
       });
       const args = [
-        {NFT: {const_data: 'A'}},
-        {NFT: {const_data: 'B'}},
+        {NFT: {}},
+        {NFT: {}},
       ];
       const createMultipleItemsTx = api.tx.unique.createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
-      await expect(submitTransactionExpectFailAsync(alice, createMultipleItemsTx)).to.be.rejected;
-    });
-  });
-
-  it('No editing rights', async () => {
-    await usingApi(async (api: ApiPromise) => {
-      const collectionId = await createCollectionWithPropsExpectSuccess({properties: [{key: 'key1', value: 'v'}],
-        propPerm:   [{key: 'key1', permission: {mutable: false, collectionAdmin: false, tokenOwner: true}}]});
-      const itemsListIndexBefore = await getLastTokenId(api, collectionId);
-      expect(itemsListIndexBefore).to.be.equal(0);
-      await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
-      const args = [{Nft: {const_data: '0x31', properties: [{key: 'key1', value: 'v2'}]}},
-        {Nft: {const_data: '0x32'}},
-        {Nft: {const_data: '0x33'}}];
-
-      await createMultipleItemsWithPropsExpectFailure(bob, collectionId, args);
+      await expect(executeTransaction(api, alice, createMultipleItemsTx)).to.be.rejectedWith(/common\.CollectionTokenLimitExceeded/);
     });
   });
 
   it('User doesnt have editing rights', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const collectionId = await createCollectionWithPropsExpectSuccess({properties: [{key: 'key1', value: 'v'}],
-        propPerm:   [{key: 'key1', permission: {mutable: true, collectionAdmin: false, tokenOwner: false}}]});
+      const collectionId = await createCollectionWithPropsExpectSuccess({
+        propPerm: [{key: 'key1', permission: {mutable: true, collectionAdmin: false, tokenOwner: false}}]
+      });
       const itemsListIndexBefore = await getLastTokenId(api, collectionId);
       expect(itemsListIndexBefore).to.be.equal(0);
       await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
-      const args = [{Nft: {const_data: '0x31', properties: [{key: 'key1', value: 'v2'}]}},
-        {Nft: {const_data: '0x32'}},
-        {Nft: {const_data: '0x33'}}];
+      const args = [
+        {NFT: {properties: [{key: 'key1', value: 'v2'}]}},
+        {NFT: {}},
+        {NFT: {}}
+      ];
 
-      await createMultipleItemsWithPropsExpectFailure(bob, collectionId, args);
+      const tx = api.tx.unique.createMultipleItems(collectionId, normalizeAccountId(bob.address), args);
+      await expect(executeTransaction(api, bob, tx)).to.be.rejectedWith(/common\.NoPermission/);
     });
   });
 
@@ -466,18 +463,27 @@
       const itemsListIndexBefore = await getLastTokenId(api, collectionId);
       await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
       expect(itemsListIndexBefore).to.be.equal(0);
-      const args = [{Nft: {const_data: '0x31', properties: [{key: 'k', value: 'v'}]}},
-        {Nft: {const_data: '0x32'}},
-        {Nft: {const_data: '0x33'}}];
+      const args = [{NFT: {properties: [{key: 'k', value: 'v'}]}},
+        {NFT: {}},
+        {NFT: {}}];
 
-      await createMultipleItemsWithPropsExpectFailure(bob, collectionId, args);
+      const tx = api.tx.unique.createMultipleItems(collectionId, normalizeAccountId(bob.address), args);
+      await expect(executeTransaction(api, bob, tx)).to.be.rejectedWith(/common\.NoPermission/);
     });
   });
 
   it('Adding more than 64 prps', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const collectionId = await createCollectionWithPropsExpectSuccess({properties: [{key: 'key1', value: 'v'}],
-        propPerm:   [{key: 'key1', permission: {mutable: true, collectionAdmin: true, tokenOwner: false}}]});
+      const propPerms = [{key: 'key', permission: {mutable: true, collectionAdmin: true, tokenOwner: true}}];
+      for (let i = 0; i < 65; i++) {
+        propPerms.push({key: `key${i}`, permission: {mutable: true, collectionAdmin: true, tokenOwner: true}});
+      }
+
+      const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+
+      const tx1 = api.tx.unique.setPropertyPermissions(collectionId, propPerms);
+      await expect(executeTransaction(api, alice, tx1)).to.be.rejectedWith(/common\.PropertyLimitReached/);
+
       const itemsListIndexBefore = await getLastTokenId(api, collectionId);
       expect(itemsListIndexBefore).to.be.equal(0);
       await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
@@ -488,24 +494,31 @@
         prps.push({key: `key${i}`, value: `value${i}`});
       }
 
-      const args = [{Nft: {const_data: '0x31', properties: prps}},
-        {Nft: {const_data: '0x32', properties: prps}},
-        {Nft: {const_data: '0x33', properties: prps}}];
+      const args = [
+        {NFT: {properties: prps}},
+        {NFT: {properties: prps}},
+        {NFT: {properties: prps}}
+      ];
 
-      createMultipleItemsWithPropsExpectFailure(alice, collectionId, args);
+      // there are no permissions, but will fail anyway because of too much weight for a block
+      const tx2 = api.tx.unique.createMultipleItems(collectionId, normalizeAccountId(alice.address), args);;
+      await expect(submitTransactionExpectFailAsync(alice, tx2)).to.be.rejected;
     });
   });
 
   it('Trying to add bigger property than allowed', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const collectionId = await createCollectionWithPropsExpectSuccess({propPerm:   [{key: 'k', permission: {mutable: true, collectionAdmin: true, tokenOwner: true}}]});
+      const collectionId = await createCollectionWithPropsExpectSuccess({
+        propPerm: [{key: 'k', permission: {mutable: true, collectionAdmin: true, tokenOwner: true}}]
+      });
       const itemsListIndexBefore = await getLastTokenId(api, collectionId);
       expect(itemsListIndexBefore).to.be.equal(0);
-      const args = [{Nft: {const_data: '0x31', properties: [{key: 'k', value: 'vvvvvv'.repeat(5000)}, {key: 'k2', value: 'vvv'.repeat(5000)}]}},
-        {Nft: {const_data: '0x32', properties: [{key: 'k', value: 'vvvvvv'.repeat(5000)}, {key: 'k2', value: 'vvv'.repeat(5000)}]}},
-        {Nft: {const_data: '0x33', properties: [{key: 'k', value: 'vvvvvv'.repeat(5000)}, {key: 'k2', value: 'vvv'.repeat(5000)}]}}];
+      const args = [{NFT: {properties: [{key: 'k', value: 'vvvvvv'.repeat(5000)}, {key: 'k2', value: 'vvv'.repeat(5000)}]}},
+        {NFT: {properties: [{key: 'k', value: 'vvvvvv'.repeat(5000)}, {key: 'k2', value: 'vvv'.repeat(5000)}]}},
+        {NFT: {properties: [{key: 'k', value: 'vvvvvv'.repeat(5000)}, {key: 'k2', value: 'vvv'.repeat(5000)}]}}];
 
-      createMultipleItemsWithPropsExpectFailure(alice, collectionId, args);
+      const tx = api.tx.unique.createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
+      await expect(executeTransaction(api, alice, tx)).to.be.rejectedWith(/common\.NoPermission/);
     });
   });
 });
modifiedtests/src/createMultipleItemsEx.test.tsdiffbeforeafterboth
--- a/tests/src/createMultipleItemsEx.test.ts
+++ b/tests/src/createMultipleItemsEx.test.ts
@@ -29,13 +29,13 @@
       const data = [
         {
           owner: {substrate: alice.address},
-          constData: '0x0000',
+          // constData: '0x0000',
         }, {
           owner: {substrate: bob.address},
-          constData: '0x2222',
+          // constData: '0x2222',
         }, {
           owner: {substrate: charlie.address},
-          constData: '0x4444',
+          // constData: '0x4444',
         },
       ];
 
@@ -57,15 +57,15 @@
       const data = [
         {
           owner: {substrate: alice.address},
-          constData: '0x1111',
+          // constData: '0x1111',
           properties: [{key: 'k', value: 'v1'}],
         }, {
           owner: {substrate: bob.address},
-          constData: '0x2222',
+          // constData: '0x2222',
           properties: [{key: 'k', value: 'v2'}],
         }, {
           owner: {substrate: charlie.address},
-          constData: '0x4444',
+          // constData: '0x4444',
           properties: [{key: 'k', value: 'v3'}],
         },
       ];
@@ -88,15 +88,15 @@
       const data = [
         {
           owner: {substrate: alice.address},
-          constData: '0x0000',
+          // constData: '0x0000',
           properties: [{key: 'k', value: 'v1'}],
         }, {
           owner: {substrate: bob.address},
-          constData: '0x2222',
+          // constData: '0x2222',
           properties: [{key: 'k', value: 'v2'}],
         }, {
           owner: {substrate: charlie.address},
-          constData: '0x4444',
+          // constData: '0x4444',
           properties: [{key: 'k', value: 'v3'}],
         },
       ];
@@ -119,15 +119,15 @@
       const data = [
         {
           owner: {substrate: alice.address},
-          constData: '0x0000',
+          // constData: '0x0000',
           properties: [{key: 'k', value: 'v1'}],
         }, {
           owner: {substrate: bob.address},
-          constData: '0x2222',
+          // constData: '0x2222',
           properties: [{key: 'k', value: 'v2'}],
         }, {
           owner: {substrate: charlie.address},
-          constData: '0x4444',
+          // constData: '0x4444',
           properties: [{key: 'k', value: 'v3'}],
         },
       ];
@@ -154,10 +154,10 @@
           owner: {substrate: alice.address},
           properties: [{key: 'key1', value: 'v2'}],
         }, {
-          owner: {substrate: alice.address},
+          owner: {substrate: bob.address},
           properties: [{key: 'key1', value: 'v2'}],
         }, {
-          owner: {substrate: alice.address},
+          owner: {substrate: charlie.address},
           properties: [{key: 'key1', value: 'v2'}],
         },
       ];
@@ -165,7 +165,8 @@
       const tx = api.tx.unique.createMultipleItemsEx(collection, {NFT: data});
       // await executeTransaction(api, alice, tx);
 
-      await submitTransactionExpectFailAsync(alice, tx);
+      //await submitTransactionExpectFailAsync(alice, tx);
+      await expect(executeTransaction(api, alice, tx)).to.be.rejectedWith(/common\.NoPermission/);
     });
   });
 
@@ -193,7 +194,8 @@
       const tx = api.tx.unique.createMultipleItemsEx(collection, {NFT: data});
       // await executeTransaction(api, alice, tx);
 
-      await submitTransactionExpectFailAsync(alice, tx);
+      //await submitTransactionExpectFailAsync(alice, tx);
+      await expect(executeTransaction(api, alice, tx)).to.be.rejectedWith(/common\.NoPermission/);
     });
   });
 
@@ -219,41 +221,24 @@
 
       const tx = api.tx.unique.createMultipleItemsEx(collection, {NFT: data});
 
-      await submitTransactionExpectFailAsync(alice, tx);
+      await expect(executeTransaction(api, alice, tx)).to.be.rejectedWith(/common\.NoPermission/);
+      //await submitTransactionExpectFailAsync(alice, tx);
     });
   });
 
-  it('Adding more than 64 prps', async () => {
-    const prps = [{key: 'key', value: 'v'}];
-    const propPerm = [{key: 'key', permission: {mutable: true, collectionAdmin: true, tokenOwner: true}}];
+  it('Adding more than 64 properties', async () => {
+    const propPerms = [{key: 'key', permission: {mutable: true, collectionAdmin: true, tokenOwner: true}}];
 
     for (let i = 0; i < 65; i++) {
-      prps.push({key: `key${i}`, value: `value${i}`});
-      propPerm.push({key: `key${i}`, permission: {mutable: true, collectionAdmin: true, tokenOwner: true}});
+      propPerms.push({key: `key${i}`, permission: {mutable: true, collectionAdmin: true, tokenOwner: true}});
     }
 
-    const collection = await createCollectionWithPropsExpectSuccess({propPerm: propPerm});
     const alice = privateKey('//Alice');
-    const bob = privateKey('//Bob');
-    const charlie = privateKey('//Charlie');
-    await addCollectionAdminExpectSuccess(alice, collection, bob.address);
+    const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
     await usingApi(async (api) => {
-      const data = [
-        {
-          owner: {substrate: alice.address},
-          properties: prps,
-        }, {
-          owner: {substrate: alice.address},
-          properties: prps,
-        }, {
-          owner: {substrate: alice.address},
-          properties: prps,
-        },
-      ];
-
-      const tx = api.tx.unique.createMultipleItemsEx(collection, {NFT: data});
-
-      await submitTransactionExpectFailAsync(alice, tx);
+      await expect(
+        executeTransaction(api, alice, api.tx.unique.setPropertyPermissions(collection, propPerms))
+      ).to.be.rejectedWith(/common\.PropertyLimitReached/);
     });
   });
 
@@ -276,7 +261,8 @@
 
       const tx = api.tx.unique.createMultipleItemsEx(collection, {NFT: data});
 
-      await submitTransactionExpectFailAsync(alice, tx);
+      //await submitTransactionExpectFailAsync(alice, tx);
+      await expect(executeTransaction(api, alice, tx)).to.be.rejectedWith(/common\.NoPermission/);
     });
   });
 
@@ -289,13 +275,13 @@
       const data = [
         {
           owner: {substrate: alice.address},
-          constData: '0x0000',
+          // constData: '0x0000',
         }, {
           owner: {substrate: bob.address},
-          constData: '0x2222',
+          // constData: '0x2222',
         }, {
           owner: {substrate: charlie.address},
-          constData: '0x4444',
+          // constData: '0x4444',
         },
       ];
 
@@ -317,13 +303,13 @@
       const data = [
         {
           owner: {substrate: alice.address},
-          constData: '0x0000',
+          // constData: '0x0000',
         }, {
           owner: {substrate: bob.address},
-          constData: '0x2222',
+          // constData: '0x2222',
         }, {
           owner: {substrate: charlie.address},
-          constData: '0x4444',
+          // constData: '0x4444',
         },
       ];
 
modifiedtests/src/nesting/properties.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/properties.test.ts
+++ b/tests/src/nesting/properties.test.ts
@@ -792,7 +792,7 @@
         ]), 
       )).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);
     });
deletedtests/src/setConstOnChainSchema.test.tsdiffbeforeafterboth
--- a/tests/src/setConstOnChainSchema.test.ts
+++ /dev/null
@@ -1,119 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import {Keyring} from '@polkadot/api';
-import {IKeyringPair} from '@polkadot/types/types';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {
-  createCollectionExpectSuccess,
-  destroyCollectionExpectSuccess,
-  addCollectionAdminExpectSuccess,
-  queryCollectionExpectSuccess,
-  getCreatedCollectionCount,
-} from './util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-let alice: IKeyringPair;
-let bob: IKeyringPair;
-let schema: any;
-let largeSchema: any;
-
-before(async () => {
-  await usingApi(async () => {
-    const keyring = new Keyring({type: 'sr25519'});
-    alice = keyring.addFromUri('//Alice');
-    bob = keyring.addFromUri('//Bob');
-    schema = '0x31';
-    largeSchema = new Array(1024 * 1024 + 10).fill(0xff);
-  });
-});
-describe('Integration Test ext. setConstOnChainSchema()', () => {
-
-  it('Run extrinsic with parameters of the collection id, set the scheme', async () => {
-    await usingApi(async (api) => {
-      const collectionId = await createCollectionExpectSuccess();
-      const collection = await queryCollectionExpectSuccess(api, collectionId);
-      expect(collection.owner.toString()).to.be.eq(alice.address);
-      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);
-      await submitTransactionAsync(alice, setSchema);
-    });
-  });
-
-  it('Collection admin can set the scheme', async () => {
-    await usingApi(async (api) => {
-      const collectionId = await createCollectionExpectSuccess();
-      const collection = await queryCollectionExpectSuccess(api, collectionId);
-      expect(collection.owner.toString()).to.be.eq(alice.address);
-      await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
-      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);
-      await submitTransactionAsync(bob, setSchema);
-    });
-  });
-
-  it('Checking collection data using the ConstOnChainSchema parameter', async () => {
-    await usingApi(async (api) => {
-      const collectionId = await createCollectionExpectSuccess();
-      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);
-      await submitTransactionAsync(alice, setSchema);
-      const collection = await queryCollectionExpectSuccess(api, collectionId);
-      expect(collection.constOnChainSchema.toString()).to.be.eq(schema);
-    });
-  });
-});
-
-describe('Negative Integration Test ext. setConstOnChainSchema()', () => {
-
-  it('Set a non-existent collection', async () => {
-    await usingApi(async (api) => {
-      // tslint:disable-next-line: radix
-      const collectionId = await getCreatedCollectionCount(api) + 1;
-      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);
-      await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;
-    });
-  });
-
-  it('Set a previously deleted collection', async () => {
-    await usingApi(async (api) => {
-      const collectionId = await createCollectionExpectSuccess();
-      await destroyCollectionExpectSuccess(collectionId);
-      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);
-      await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;
-    });
-  });
-
-  it('Set invalid data in schema (size too large:> 1MB)', async () => {
-    await usingApi(async (api) => {
-      const collectionId = await createCollectionExpectSuccess();
-      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, largeSchema);
-      await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;
-    });
-  });
-
-  it('Execute method not on behalf of the collection owner', async () => {
-    await usingApi(async (api) => {
-      const collectionId = await createCollectionExpectSuccess();
-      const collection = await queryCollectionExpectSuccess(api, collectionId);
-      expect(collection.owner.toString()).to.be.eq(alice.address);
-      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);
-      await expect(submitTransactionExpectFailAsync(bob, setSchema)).to.be.rejected;
-    });
-  });
-
-});
deletedtests/src/setOffchainSchema.test.tsdiffbeforeafterboth
--- a/tests/src/setOffchainSchema.test.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-import {IKeyringPair} from '@polkadot/types/types';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import privateKey from './substrate/privateKey';
-import usingApi from './substrate/substrate-api';
-import {
-  createCollectionExpectSuccess,
-  destroyCollectionExpectSuccess,
-  findNotExistingCollection,
-  queryCollectionExpectSuccess,
-  setOffchainSchemaExpectFailure,
-  setOffchainSchemaExpectSuccess,
-  addCollectionAdminExpectSuccess,
-} from './util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-const DATA = [1, 2, 3, 4];
-
-describe('Integration Test setOffchainSchema', () => {
-  let alice: IKeyringPair;
-  let bob: IKeyringPair;
-
-  before(async () => {
-    await usingApi(async () => {
-      alice = privateKey('//Alice');
-      bob = privateKey('//Bob');
-    });
-  });
-
-  it('execute setOffchainSchema, verify data was set', async () => {
-    await usingApi(async api => {
-      const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setOffchainSchemaExpectSuccess(alice, collectionId, DATA);
-      const collection = await queryCollectionExpectSuccess(api, collectionId);
-
-      expect('0x' + Buffer.from(collection.offchainSchema).toString('hex')).to.be.equal('0x' + Buffer.from(DATA).toString('hex'));
-    });
-  });
-
-  it('execute setOffchainSchema (collection admin), verify data was set', async () => {
-    await usingApi(async api => {
-      const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
-      await setOffchainSchemaExpectSuccess(bob, collectionId, DATA);
-      const collection = await queryCollectionExpectSuccess(api, collectionId);
-
-      expect('0x' + Buffer.from(collection.offchainSchema).toString('hex')).to.be.equal('0x' + Buffer.from(DATA).toString('hex'));
-    });
-  });
-});
-
-describe('Negative Integration Test setOffchainSchema', () => {
-  let alice: IKeyringPair;
-  let bob: IKeyringPair;
-
-  let validCollectionId: number;
-
-  before(async () => {
-    await usingApi(async () => {
-      alice = privateKey('//Alice');
-      bob = privateKey('//Bob');
-
-      validCollectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-    });
-  });
-
-  it('fails on not existing collection id', async () => {
-    const nonExistingCollectionId = await usingApi(findNotExistingCollection);
-
-    await setOffchainSchemaExpectFailure(alice, nonExistingCollectionId, DATA);
-  });
-
-  it('fails on destroyed collection id', async () => {
-    const destroyedCollectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-    await destroyCollectionExpectSuccess(destroyedCollectionId);
-
-    await setOffchainSchemaExpectFailure(alice, destroyedCollectionId, DATA);
-  });
-
-  it('fails on too long data', async () => {
-    const tooLongData = new Array(8 * 1024 + 10).fill(0xff);
-
-    await setOffchainSchemaExpectFailure(alice, validCollectionId, tooLongData);
-  });
-
-  it('fails on execution by non-owner', async () => {
-    await setOffchainSchemaExpectFailure(bob, validCollectionId, DATA);
-  });
-});
deletedtests/src/setSchemaVersion.test.tsdiffbeforeafterboth
--- a/tests/src/setSchemaVersion.test.ts
+++ /dev/null
@@ -1,145 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-// https://unique-network.readthedocs.io/en/latest/jsapi.html#setschemaversion
-import {ApiPromise, Keyring} from '@polkadot/api';
-import {IKeyringPair} from '@polkadot/types/types';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import usingApi, {submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {
-  createCollectionExpectSuccess,
-  destroyCollectionExpectSuccess,
-  getCreatedCollectionCount,
-  getCreateItemResult,
-  getDetailedCollectionInfo,
-  addCollectionAdminExpectSuccess,
-} from './util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-let alice: IKeyringPair;
-let bob: IKeyringPair;
-let charlie: IKeyringPair;
-
-/*
-1. We create collection.
-2. Save just created collection id.
-3. Use this id for setSchemaVersion.
-*/
-describe('setSchemaVersion positive', () => {
-  let tx;
-  before(async () => {
-    await usingApi(async () => {
-      const keyring = new Keyring({type: 'sr25519'});
-      alice = keyring.addFromUri('//Alice');
-    });
-  });
-  it('execute setSchemaVersion with image url and unique ', async () => {
-    await usingApi(async (api: ApiPromise) => {
-      const collectionIdForTesting = await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
-      tx = api.tx.unique.setSchemaVersion(collectionIdForTesting, 'Unique');
-      const events = await submitTransactionAsync(alice, tx);
-      const result = getCreateItemResult(events);
-      const collectionInfo = await getDetailedCollectionInfo(api, collectionIdForTesting);
-      // tslint:disable-next-line:no-unused-expression
-      expect(result.success).to.be.true;
-      // tslint:disable-next-line:no-unused-expression
-      expect(collectionInfo).to.be.exist;
-      // tslint:disable-next-line:no-unused-expression
-      expect(collectionInfo ? collectionInfo.schemaVersion.toString() : '').to.be.equal('Unique');
-    });
-  });
-});
-
-describe('Collection admin setSchemaVersion positive', () => {
-  let tx;
-  let collectionIdForTesting: any;
-
-  before(async () => {
-    await usingApi(async () => {
-      const keyring = new Keyring({type: 'sr25519'});
-      alice = keyring.addFromUri('//Alice');
-      bob = keyring.addFromUri('//Bob');
-      collectionIdForTesting = await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
-      await addCollectionAdminExpectSuccess(alice, collectionIdForTesting, bob.address);
-    });
-  });
-  it('execute setSchemaVersion with image url and unique ', async () => {
-    await usingApi(async (api: ApiPromise) => {
-      tx = api.tx.unique.setSchemaVersion(collectionIdForTesting, 'Unique');
-      const events = await submitTransactionAsync(bob, tx);
-      const result = getCreateItemResult(events);
-      const collectionInfo = await getDetailedCollectionInfo(api, collectionIdForTesting);
-      // tslint:disable-next-line:no-unused-expression
-      expect(result.success).to.be.true;
-      // tslint:disable-next-line:no-unused-expression
-      expect(collectionInfo).to.be.exist;
-      // tslint:disable-next-line:no-unused-expression
-      expect(collectionInfo ? collectionInfo.schemaVersion.toString() : '').to.be.equal('Unique');
-    });
-  });
-
-  it('validate schema version with just entered data', async () => {
-    await usingApi(async (api: ApiPromise) => {
-      tx = api.tx.unique.setSchemaVersion(collectionIdForTesting, 'ImageURL');
-      const events = await submitTransactionAsync(bob, tx);
-      const result = getCreateItemResult(events);
-      const collectionInfo = await getDetailedCollectionInfo(api, collectionIdForTesting);
-      // tslint:disable-next-line:no-unused-expression
-      expect(result.success).to.be.true;
-      // tslint:disable-next-line:no-unused-expression
-      expect(collectionInfo).to.be.exist;
-      // tslint:disable-next-line:no-unused-expression
-      expect(collectionInfo ? collectionInfo.schemaVersion.toString() : '').to.be.equal('ImageURL');
-    });
-  });
-});
-
-describe('setSchemaVersion negative', () => {
-  let tx;
-  let collectionIdForTesting: any;
-  before(async () => {
-    await usingApi(async () => {
-      const keyring = new Keyring({type: 'sr25519'});
-      alice = keyring.addFromUri('//Alice');
-      charlie = keyring.addFromUri('//Charlie');
-      collectionIdForTesting = await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
-    });
-  });
-  it('execute setSchemaVersion for not exists collection', async () => {
-    await usingApi(async (api: ApiPromise) => {
-      const collectionCount = await getCreatedCollectionCount(api);
-      const nonExistedCollectionId = collectionCount + 1;
-      tx = api.tx.unique.setSchemaVersion(nonExistedCollectionId, 'ImageURL');
-      await expect(submitTransactionExpectFailAsync(alice, tx)).to.be.rejected;
-    });
-  });
-  it('execute setSchemaVersion for deleted collection', async () => {
-    await usingApi(async (api: ApiPromise) => {
-      await destroyCollectionExpectSuccess(collectionIdForTesting);
-      tx = api.tx.unique.setSchemaVersion(collectionIdForTesting, 'ImageURL');
-      await expect(submitTransactionExpectFailAsync(alice, tx)).to.be.rejected;
-    });
-  });
-  it('Regular user can`t execute setSchemaVersion with image url and unique ', async () => {
-    await usingApi(async (api: ApiPromise) => {
-      tx = api.tx.unique.setSchemaVersion(collectionIdForTesting, 'Unique');
-      await expect(submitTransactionAsync(charlie, tx)).to.be.rejected;
-    });
-  });
-});
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, UpDataStructsCreateItemData} 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}146147export function uniqueEventMessage(events: EventRecord[]): IGetMessage {148  let checkMsgUnqMethod = '';149  let checkMsgTrsMethod = '';150  let checkMsgSysMethod = '';151  events.forEach(({event: {method, section}}) => {152    if (section === 'common') {153      checkMsgUnqMethod = method;154    } else if (section === 'treasury') {155      checkMsgTrsMethod = method;156    } else if (section === 'system') {157      checkMsgSysMethod = method;158    } else { return null; }159  });160  const result: IGetMessage = {161    checkMsgUnqMethod,162    checkMsgTrsMethod,163    checkMsgSysMethod,164  };165  return result;166}167168export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {169  const event = events.find(r => check(r.event));170  if (!event) return;171  return event.event as T;172}173174export function getGenericResult(events: EventRecord[]): GenericResult {175  const result: GenericResult = {176    success: false,177  };178  events.forEach(({event: {method}}) => {179    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);180    if (method === 'ExtrinsicSuccess') {181      result.success = true;182    }183  });184  return result;185}186187188189export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {190  let success = false;191  let collectionId = 0;192  events.forEach(({event: {data, method, section}}) => {193    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);194    if (method == 'ExtrinsicSuccess') {195      success = true;196    } else if ((section == 'common') && (method == 'CollectionCreated')) {197      collectionId = parseInt(data[0].toString(), 10);198    }199  });200  const result: CreateCollectionResult = {201    success,202    collectionId,203  };204  return result;205}206207export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {208  let success = false;209  let collectionId = 0;210  let itemId = 0;211  let recipient;212213  const results : CreateItemResult[]  = [];214215  events.forEach(({event: {data, method, section}}) => {216    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);217    if (method == 'ExtrinsicSuccess') {218      success = true;219    } else if ((section == 'common') && (method == 'ItemCreated')) {220      collectionId = parseInt(data[0].toString(), 10);221      itemId = parseInt(data[1].toString(), 10);222      recipient = normalizeAccountId(data[2].toJSON() as any);223224      const itemRes: CreateItemResult = {225        success,226        collectionId,227        itemId,228        recipient,229      };230231      results.push(itemRes);232    }233  });234235  return results;236}237238export function getCreateItemResult(events: EventRecord[]): CreateItemResult {239  let success = false;240  let collectionId = 0;241  let itemId = 0;242  let recipient;243  events.forEach(({event: {data, method, section}}) => {244    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);245    if (method == 'ExtrinsicSuccess') {246      success = true;247    } else if ((section == 'common') && (method == 'ItemCreated')) {248      collectionId = parseInt(data[0].toString(), 10);249      itemId = parseInt(data[1].toString(), 10);250      recipient = normalizeAccountId(data[2].toJSON() as any);251    }252  });253  const result: CreateItemResult = {254    success,255    collectionId,256    itemId,257    recipient,258  };259  return result;260}261262export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {263  for (const {event} of events) {264    if (api.events.common.Transfer.is(event)) {265      const [collection, token, sender, recipient, value] = event.data;266      return {267        collectionId: collection.toNumber(),268        itemId: token.toNumber(),269        sender: normalizeAccountId(sender.toJSON() as any),270        recipient: normalizeAccountId(recipient.toJSON() as any),271        value: value.toBigInt(),272      };273    }274  }275  throw new Error('no transfer event');276}277278interface Nft {279  type: 'NFT';280}281282interface Fungible {283  type: 'Fungible';284  decimalPoints: number;285}286287interface ReFungible {288  type: 'ReFungible';289}290291type CollectionMode = Nft | Fungible | ReFungible;292293export type Property = {294  key: any,295  value: any,296};297298type Permission = {299  mutable: boolean;300  collectionAdmin: boolean;301  tokenOwner: boolean;302}303304type PropertyPermission = {305  key: any;306  permission: Permission;307}308309export type CreateCollectionParams = {310  mode: CollectionMode,311  name: string,312  description: string,313  tokenPrefix: string,314  schemaVersion: string,315  properties?: Array<Property>,316  propPerm?: Array<PropertyPermission>317};318319const defaultCreateCollectionParams: CreateCollectionParams = {320  description: 'description',321  mode: {type: 'NFT'},322  name: 'name',323  tokenPrefix: 'prefix',324  schemaVersion: 'ImageURL',325};326327export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {328  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};329330  let collectionId = 0;331  await usingApi(async (api) => {332    // Get number of collections before the transaction333    const collectionCountBefore = await getCreatedCollectionCount(api);334335    // Run the CreateCollection transaction336    const alicePrivateKey = privateKey('//Alice');337338    let modeprm = {};339    if (mode.type === 'NFT') {340      modeprm = {nft: null};341    } else if (mode.type === 'Fungible') {342      modeprm = {fungible: mode.decimalPoints};343    } else if (mode.type === 'ReFungible') {344      modeprm = {refungible: null};345    }346347    const tx = api.tx.unique.createCollectionEx({348      name: strToUTF16(name),349      description: strToUTF16(description),350      tokenPrefix: strToUTF16(tokenPrefix),351      mode: modeprm as any352    });353    const events = await submitTransactionAsync(alicePrivateKey, tx);354    const result = getCreateCollectionResult(events);355356    // Get number of collections after the transaction357    const collectionCountAfter = await getCreatedCollectionCount(api);358359    // Get the collection360    const collection = await queryCollectionExpectSuccess(api, result.collectionId);361362    // What to expect363    // tslint:disable-next-line:no-unused-expression364    expect(result.success).to.be.true;365    expect(result.collectionId).to.be.equal(collectionCountAfter);366    // tslint:disable-next-line:no-unused-expression367    expect(collection).to.be.not.null;368    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');369    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));370    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);371    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);372    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);373374    collectionId = result.collectionId;375  });376377  return collectionId;378}379380export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {381  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};382383  let collectionId = 0;384  await usingApi(async (api) => {385    // Get number of collections before the transaction386    const collectionCountBefore = await getCreatedCollectionCount(api);387388    // Run the CreateCollection transaction389    const alicePrivateKey = privateKey('//Alice');390391    let modeprm = {};392    if (mode.type === 'NFT') {393      modeprm = {nft: null};394    } else if (mode.type === 'Fungible') {395      modeprm = {fungible: mode.decimalPoints};396    } else if (mode.type === 'ReFungible') {397      modeprm = {refungible: null};398    }399400    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});401    const events = await submitTransactionAsync(alicePrivateKey, tx);402    const result = getCreateCollectionResult(events);403404    // Get number of collections after the transaction405    const collectionCountAfter = await getCreatedCollectionCount(api);406407    // Get the collection408    const collection = await queryCollectionExpectSuccess(api, result.collectionId);409410    // What to expect411    // tslint:disable-next-line:no-unused-expression412    expect(result.success).to.be.true;413    expect(result.collectionId).to.be.equal(collectionCountAfter);414    // tslint:disable-next-line:no-unused-expression415    expect(collection).to.be.not.null;416    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');417    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));418    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);419    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);420    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);421422423    collectionId = result.collectionId;424  });425426  return collectionId;427}428429export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {430  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};431432  await usingApi(async (api) => {433    // Get number of collections before the transaction434    const collectionCountBefore = await getCreatedCollectionCount(api);435436    // Run the CreateCollection transaction437    const alicePrivateKey = privateKey('//Alice');438439    let modeprm = {};440    if (mode.type === 'NFT') {441      modeprm = {nft: null};442    } else if (mode.type === 'Fungible') {443      modeprm = {fungible: mode.decimalPoints};444    } else if (mode.type === 'ReFungible') {445      modeprm = {refungible: null};446    }447448    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});449    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;450451452    // Get number of collections after the transaction453    const collectionCountAfter = await getCreatedCollectionCount(api);454455    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');456  });457}458459export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {460  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};461462  let modeprm = {};463  if (mode.type === 'NFT') {464    modeprm = {nft: null};465  } else if (mode.type === 'Fungible') {466    modeprm = {fungible: mode.decimalPoints};467  } else if (mode.type === 'ReFungible') {468    modeprm = {refungible: null};469  }470471  await usingApi(async (api) => {472    // Get number of collections before the transaction473    const collectionCountBefore = await getCreatedCollectionCount(api);474475    // Run the CreateCollection transaction476    const alicePrivateKey = privateKey('//Alice');477    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});478    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;479480    // Get number of collections after the transaction481    const collectionCountAfter = await getCreatedCollectionCount(api);482483    // What to expect484    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');485  });486}487488export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {489  let bal = 0n;490  let unused;491  do {492    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;493    const keyring = new Keyring({type: 'sr25519'});494    unused = keyring.addFromUri(`//${randomSeed}`);495    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();496  } while (bal !== 0n);497  return unused;498}499500export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {501  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();502}503504export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {505  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));506}507508export async function findNotExistingCollection(api: ApiPromise): Promise<number> {509  const totalNumber = await getCreatedCollectionCount(api);510  const newCollection: number = totalNumber + 1;511  return newCollection;512}513514function getDestroyResult(events: EventRecord[]): boolean {515  let success = false;516  events.forEach(({event: {method}}) => {517    if (method == 'ExtrinsicSuccess') {518      success = true;519    }520  });521  return success;522}523524export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {525  await usingApi(async (api) => {526    // Run the DestroyCollection transaction527    const alicePrivateKey = privateKey(senderSeed);528    const tx = api.tx.unique.destroyCollection(collectionId);529    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;530  });531}532533export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {534  await usingApi(async (api) => {535    // Run the DestroyCollection transaction536    const alicePrivateKey = privateKey(senderSeed);537    const tx = api.tx.unique.destroyCollection(collectionId);538    const events = await submitTransactionAsync(alicePrivateKey, tx);539    const result = getDestroyResult(events);540    expect(result).to.be.true;541542    // What to expect543    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;544  });545}546547export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {548  await usingApi(async (api) => {549    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);550    const events = await submitTransactionAsync(sender, tx);551    const result = getGenericResult(events);552553    expect(result.success).to.be.true;554  });555}556557export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: {mintMode?: boolean, access?: 'Normal' | 'AllowList', nesting?: 'Disabled' | 'Owner' | {OwnerRestricted: number[]}}) => {558  await usingApi(async(api) => {559    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);560    const events = await submitTransactionAsync(sender, tx);561    const result = getGenericResult(events);562563    expect(result.success).to.be.true;564  });565}566567export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {568  await usingApi(async (api) => {569    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);570    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;571    const result = getGenericResult(events);572573    expect(result.success).to.be.false;574  });575}576577export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {578  await usingApi(async (api) => {579580    // Run the transaction581    const senderPrivateKey = privateKey(sender);582    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);583    const events = await submitTransactionAsync(senderPrivateKey, tx);584    const result = getGenericResult(events);585586    // Get the collection587    const collection = await queryCollectionExpectSuccess(api, collectionId);588589    // What to expect590    expect(result.success).to.be.true;591    expect(collection.sponsorship.toJSON()).to.deep.equal({592      unconfirmed: sponsor,593    });594  });595}596597export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {598  await usingApi(async (api) => {599600    // Run the transaction601    const alicePrivateKey = privateKey(sender);602    const tx = api.tx.unique.removeCollectionSponsor(collectionId);603    const events = await submitTransactionAsync(alicePrivateKey, tx);604    const result = getGenericResult(events);605606    // Get the collection607    const collection = await queryCollectionExpectSuccess(api, collectionId);608609    // What to expect610    expect(result.success).to.be.true;611    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});612  });613}614615export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {616  await usingApi(async (api) => {617618    // Run the transaction619    const alicePrivateKey = privateKey(senderSeed);620    const tx = api.tx.unique.removeCollectionSponsor(collectionId);621    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;622  });623}624625export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {626  await usingApi(async (api) => {627628    // Run the transaction629    const alicePrivateKey = privateKey(senderSeed);630    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);631    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;632  });633}634635export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {636  await usingApi(async (api) => {637638    // Run the transaction639    const sender = privateKey(senderSeed);640    const tx = api.tx.unique.confirmSponsorship(collectionId);641    const events = await submitTransactionAsync(sender, tx);642    const result = getGenericResult(events);643644    // Get the collection645    const collection = await queryCollectionExpectSuccess(api, collectionId);646647    // What to expect648    expect(result.success).to.be.true;649    expect(collection.sponsorship.toJSON()).to.be.deep.equal({650      confirmed: sender.address,651    });652  });653}654655656export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {657  await usingApi(async (api) => {658659    // Run the transaction660    const sender = privateKey(senderSeed);661    const tx = api.tx.unique.confirmSponsorship(collectionId);662    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;663  });664}665666export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {667  await usingApi(async (api) => {668    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);669    const events = await submitTransactionAsync(sender, tx);670    const result = getGenericResult(events);671672    expect(result.success).to.be.true;673  });674}675676export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {677  await usingApi(async (api) => {678    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);679    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;680    const result = getGenericResult(events);681682    expect(result.success).to.be.false;683  });684}685686export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {687688  await usingApi(async (api) => {689690    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);691    const events = await submitTransactionAsync(sender, tx);692    const result = getGenericResult(events);693694    expect(result.success).to.be.true;695  });696}697698export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {699700  await usingApi(async (api) => {701702    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);703    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;704    const result = getGenericResult(events);705706    expect(result.success).to.be.false;707  });708}709710export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {711  await usingApi(async (api) => {712    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);713    const events = await submitTransactionAsync(sender, tx);714    const result = getGenericResult(events);715716    expect(result.success).to.be.true;717  });718}719720export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {721  await usingApi(async (api) => {722    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);723    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;724    const result = getGenericResult(events);725726    expect(result.success).to.be.false;727  });728}729730export async function getNextSponsored(731  api: ApiPromise,732  collectionId: number,733  account: string | CrossAccountId,734  tokenId: number,735): Promise<number> {736  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));737}738739export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {740  await usingApi(async (api) => {741    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);742    const events = await submitTransactionAsync(sender, tx);743    const result = getGenericResult(events);744745    expect(result.success).to.be.true;746  });747}748749export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {750  let allowlisted = false;751  await usingApi(async (api) => {752    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;753  });754  return allowlisted;755}756757export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {758  await usingApi(async (api) => {759    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());760    const events = await submitTransactionAsync(sender, tx);761    const result = getGenericResult(events);762763    expect(result.success).to.be.true;764  });765}766767export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {768  await usingApi(async (api) => {769    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());770    const events = await submitTransactionAsync(sender, tx);771    const result = getGenericResult(events);772773    expect(result.success).to.be.true;774  });775}776777export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {778  await usingApi(async (api) => {779    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());780    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;781    const result = getGenericResult(events);782783    expect(result.success).to.be.false;784  });785}786787export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {788  await usingApi(async (api) => {789    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));790    const events = await submitTransactionAsync(sender, tx);791    const result = getGenericResult(events);792793    expect(result.success).to.be.true;794  });795}796797export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {798  await usingApi(async (api) => {799    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));800    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;801  });802}803804export interface CreateFungibleData {805  readonly Value: bigint;806}807808export interface CreateReFungibleData { }809export interface CreateNftData { }810811export type CreateItemData = {812  NFT: CreateNftData;813} | {814  Fungible: CreateFungibleData;815} | {816  ReFungible: CreateReFungibleData;817};818819export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {820  await usingApi(async (api) => {821    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);822    // if burning token by admin - use adminButnItemExpectSuccess823    expect(balanceBefore >= BigInt(value)).to.be.true;824825    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);826    const events = await submitTransactionAsync(sender, tx);827    const result = getGenericResult(events);828    expect(result.success).to.be.true;829830    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);831    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);832  });833}834835export async function836approveExpectSuccess(837  collectionId: number,838  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,839) {840  await usingApi(async (api: ApiPromise) => {841    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);842    const events = await submitTransactionAsync(owner, approveUniqueTx);843    const result = getGenericResult(events);844    expect(result.success).to.be.true;845846    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));847  });848}849850export async function adminApproveFromExpectSuccess(851  collectionId: number,852  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,853) {854  await usingApi(async (api: ApiPromise) => {855    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);856    const events = await submitTransactionAsync(admin, approveUniqueTx);857    const result = getGenericResult(events);858    expect(result.success).to.be.true;859860    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));861  });862}863864export async function865transferFromExpectSuccess(866  collectionId: number,867  tokenId: number,868  accountApproved: IKeyringPair,869  accountFrom: IKeyringPair | CrossAccountId,870  accountTo: IKeyringPair | CrossAccountId,871  value: number | bigint = 1,872  type = 'NFT',873) {874  await usingApi(async (api: ApiPromise) => {875    const from = normalizeAccountId(accountFrom);876    const to = normalizeAccountId(accountTo);877    let balanceBefore = 0n;878    if (type === 'Fungible' || type === 'ReFungible') {879      balanceBefore = await getBalance(api, collectionId, to, tokenId);880    }881    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);882    const events = await submitTransactionAsync(accountApproved, transferFromTx);883    const result = getCreateItemResult(events);884    // tslint:disable-next-line:no-unused-expression885    expect(result.success).to.be.true;886    if (type === 'NFT') {887      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);888    }889    if (type === 'Fungible') {890      const balanceAfter = await getBalance(api, collectionId, to, tokenId);891      if (JSON.stringify(to) !== JSON.stringify(from)) {892        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));893      } else {894        expect(balanceAfter).to.be.equal(balanceBefore);895      }896    }897    if (type === 'ReFungible') {898      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));899    }900  });901}902903export async function904transferFromExpectFail(905  collectionId: number,906  tokenId: number,907  accountApproved: IKeyringPair,908  accountFrom: IKeyringPair,909  accountTo: IKeyringPair,910  value: number | bigint = 1,911) {912  await usingApi(async (api: ApiPromise) => {913    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);914    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;915    const result = getCreateCollectionResult(events);916    // tslint:disable-next-line:no-unused-expression917    expect(result.success).to.be.false;918  });919}920921/* eslint no-async-promise-executor: "off" */922async function getBlockNumber(api: ApiPromise): Promise<number> {923  return new Promise<number>(async (resolve) => {924    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {925      unsubscribe();926      resolve(head.number.toNumber());927    });928  });929}930931export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {932  await usingApi(async (api) => {933    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));934    const events = await submitTransactionAsync(sender, changeAdminTx);935    const result = getCreateCollectionResult(events);936    expect(result.success).to.be.true;937  });938}939940export async function941getFreeBalance(account: IKeyringPair): Promise<bigint> {942  let balance = 0n;943  await usingApi(async (api) => {944    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());945  });946947  return balance;948}949950export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {951  const tx = api.tx.balances.transfer(target, amount);952  const events = await submitTransactionAsync(source, tx);953  const result = getGenericResult(events);954  expect(result.success).to.be.true;955}956957export async function958scheduleTransferExpectSuccess(959  collectionId: number,960  tokenId: number,961  sender: IKeyringPair,962  recipient: IKeyringPair,963  value: number | bigint = 1,964  blockSchedule: number,965) {966  await usingApi(async (api: ApiPromise) => {967    const blockNumber: number | undefined = await getBlockNumber(api);968    const expectedBlockNumber = blockNumber + blockSchedule;969970    expect(blockNumber).to.be.greaterThan(0);971    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);972    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);973974    await submitTransactionAsync(sender, scheduleTx);975976    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();977978    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));979980    // sleep for 4 blocks981    await waitNewBlocks(blockSchedule + 1);982983    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();984985    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));986    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);987  });988}989990991export async function992transferExpectSuccess(993  collectionId: number,994  tokenId: number,995  sender: IKeyringPair,996  recipient: IKeyringPair | CrossAccountId,997  value: number | bigint = 1,998  type = 'NFT',999) {1000  await usingApi(async (api: ApiPromise) => {1001    const from = normalizeAccountId(sender);1002    const to = normalizeAccountId(recipient);10031004    let balanceBefore = 0n;1005    if (type === 'Fungible') {1006      balanceBefore = await getBalance(api, collectionId, to, tokenId);1007    }1008    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1009    const events = await executeTransaction(api, sender, transferTx);10101011    const result = getTransferResult(api, events);1012    expect(result.collectionId).to.be.equal(collectionId);1013    expect(result.itemId).to.be.equal(tokenId);1014    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1015    expect(result.recipient).to.be.deep.equal(to);1016    expect(result.value).to.be.equal(BigInt(value));10171018    if (type === 'NFT') {1019      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1020    }1021    if (type === 'Fungible') {1022      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1023      if (JSON.stringify(to) !== JSON.stringify(from)) {1024        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1025      } else {1026        expect(balanceAfter).to.be.equal(balanceBefore);1027      }1028    }1029    if (type === 'ReFungible') {1030      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1031    }1032  });1033}10341035export async function1036transferExpectFailure(1037  collectionId: number,1038  tokenId: number,1039  sender: IKeyringPair,1040  recipient: IKeyringPair | CrossAccountId,1041  value: number | bigint = 1,1042) {1043  await usingApi(async (api: ApiPromise) => {1044    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1045    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1046    const result = getGenericResult(events);1047    // if (events && Array.isArray(events)) {1048    //   const result = getCreateCollectionResult(events);1049    // tslint:disable-next-line:no-unused-expression1050    expect(result.success).to.be.false;1051    //}1052  });1053}10541055export async function1056approveExpectFail(1057  collectionId: number,1058  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1059) {1060  await usingApi(async (api: ApiPromise) => {1061    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1062    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1063    const result = getCreateCollectionResult(events);1064    // tslint:disable-next-line:no-unused-expression1065    expect(result.success).to.be.false;1066  });1067}10681069export async function getBalance(1070  api: ApiPromise,1071  collectionId: number,1072  owner: string | CrossAccountId,1073  token: number,1074): Promise<bigint> {1075  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1076}1077export async function getTokenOwner(1078  api: ApiPromise,1079  collectionId: number,1080  token: number,1081): Promise<CrossAccountId> {1082  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1083  if (owner == null) throw new Error('owner == null');1084  return normalizeAccountId(owner);1085}1086export async function getTopmostTokenOwner(1087  api: ApiPromise,1088  collectionId: number,1089  token: number,1090): Promise<CrossAccountId> {1091  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1092  if (owner == null) throw new Error('owner == null');1093  return normalizeAccountId(owner);1094}1095export async function isTokenExists(1096  api: ApiPromise,1097  collectionId: number,1098  token: number,1099): Promise<boolean> {1100  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1101}1102export async function getLastTokenId(1103  api: ApiPromise,1104  collectionId: number,1105): Promise<number> {1106  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1107}1108export async function getAdminList(1109  api: ApiPromise,1110  collectionId: number,1111): Promise<string[]> {1112  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1113}1114export async function getConstMetadata(1115  api: ApiPromise,1116  collectionId: number,1117  tokenId: number,1118): Promise<number[]> {1119  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1120}11211122export async function createFungibleItemExpectSuccess(1123  sender: IKeyringPair,1124  collectionId: number,1125  data: CreateFungibleData,1126  owner: CrossAccountId | string = sender.address,1127) {1128  return await usingApi(async (api) => {1129    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11301131    const events = await submitTransactionAsync(sender, tx);1132    const result = getCreateItemResult(events);11331134    expect(result.success).to.be.true;1135    return result.itemId;1136  });1137}11381139export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1140  await usingApi(async (api) => {1141    const to = normalizeAccountId(owner);1142    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);11431144    const events = await submitTransactionAsync(sender, tx);1145    const result = getCreateItemsResult(events);11461147    for (const res of result) {1148      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1149    }1150  });1151}11521153export async function createMultipleItemsWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1154  await usingApi(async (api) => {1155    const to = normalizeAccountId(owner);1156    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);11571158    const events = await expect(await submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1159    const result = getCreateItemsResult(events);11601161    expect(result).to.be.equal(false);1162  });1163}11641165export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1166  await usingApi(async (api) => {1167    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);11681169    const events = await submitTransactionAsync(sender, tx);1170    const result = getCreateItemsResult(events);11711172    for (const res of result) {1173      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1174    }1175  });1176}11771178export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1179  let newItemId = 0;1180  await usingApi(async (api) => {1181    const to = normalizeAccountId(owner);1182    const itemCountBefore = await getLastTokenId(api, collectionId);1183    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11841185    let tx;1186    if (createMode === 'Fungible') {1187      const createData = {fungible: {value: 10}};1188      tx = api.tx.unique.createItem(collectionId, to, createData as any);1189    } else if (createMode === 'ReFungible') {1190      const createData = {refungible: {const_data: [], pieces: 100}};1191      tx = api.tx.unique.createItem(collectionId, to, createData as any);1192    } else {1193      const data = api.createType('UpDataStructsCreateItemData', {NFT: {constData: 'test', properties: props}});1194      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1195    }11961197    const events = await submitTransactionAsync(sender, tx);1198    const result = getCreateItemResult(events);11991200    const itemCountAfter = await getLastTokenId(api, collectionId);1201    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12021203    if (createMode === 'NFT') {1204      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1205    }12061207    // What to expect1208    // tslint:disable-next-line:no-unused-expression1209    expect(result.success).to.be.true;1210    if (createMode === 'Fungible') {1211      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1212    } else {1213      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1214    }1215    expect(collectionId).to.be.equal(result.collectionId);1216    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1217    expect(to).to.be.deep.equal(result.recipient);1218    newItemId = result.itemId;1219  });1220  return newItemId;1221}12221223export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1224  await usingApi(async (api) => {12251226    let tx;1227    if (createMode === 'NFT') {1228      const data = api.createType('UpDataStructsCreateItemData', {NFT: {constData: 'test', properties: props}});1229      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1230    } else {1231      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1232    }123312341235    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1236    const result = getCreateItemResult(events);12371238    expect(result.success).to.be.false;1239  });1240}12411242export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1243  let newItemId = 0;1244  await usingApi(async (api) => {1245    const to = normalizeAccountId(owner);1246    const itemCountBefore = await getLastTokenId(api, collectionId);1247    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);12481249    let tx;1250    if (createMode === 'Fungible') {1251      const createData = {fungible: {value: 10}};1252      tx = api.tx.unique.createItem(collectionId, to, createData as any);1253    } else if (createMode === 'ReFungible') {1254      const createData = {refungible: {const_data: [], pieces: 100}};1255      tx = api.tx.unique.createItem(collectionId, to, createData as any);1256    } else {1257      const createData = {nft: {const_data: []}};1258      tx = api.tx.unique.createItem(collectionId, to, createData as any);1259    }12601261    const events = await submitTransactionAsync(sender, tx);1262    const result = getCreateItemResult(events);12631264    const itemCountAfter = await getLastTokenId(api, collectionId);1265    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12661267    // What to expect1268    // tslint:disable-next-line:no-unused-expression1269    expect(result.success).to.be.true;1270    if (createMode === 'Fungible') {1271      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1272    } else {1273      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1274    }1275    expect(collectionId).to.be.equal(result.collectionId);1276    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1277    expect(to).to.be.deep.equal(result.recipient);1278    newItemId = result.itemId;1279  });1280  return newItemId;1281}12821283export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1284  await usingApi(async (api) => {1285    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);12861287    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1288    const result = getCreateItemResult(events);12891290    expect(result.success).to.be.false;1291  });1292}12931294export async function setPublicAccessModeExpectSuccess(1295  sender: IKeyringPair, collectionId: number,1296  accessMode: 'Normal' | 'AllowList',1297) {1298  await usingApi(async (api) => {12991300    // Run the transaction1301    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1302    const events = await submitTransactionAsync(sender, tx);1303    const result = getGenericResult(events);13041305    // Get the collection1306    const collection = await queryCollectionExpectSuccess(api, collectionId);13071308    // What to expect1309    // tslint:disable-next-line:no-unused-expression1310    expect(result.success).to.be.true;1311    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1312  });1313}13141315export async function setPublicAccessModeExpectFail(1316  sender: IKeyringPair, collectionId: number,1317  accessMode: 'Normal' | 'AllowList',1318) {1319  await usingApi(async (api) => {13201321    // Run the transaction1322    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1323    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1324    const result = getGenericResult(events);13251326    // What to expect1327    // tslint:disable-next-line:no-unused-expression1328    expect(result.success).to.be.false;1329  });1330}13311332export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1333  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1334}13351336export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1337  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1338}13391340export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1341  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1342}13431344export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1345  await usingApi(async (api) => {13461347    // Run the transaction1348    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1349    const events = await submitTransactionAsync(sender, tx);1350    const result = getGenericResult(events);1351    expect(result.success).to.be.true;13521353    // Get the collection1354    const collection = await queryCollectionExpectSuccess(api, collectionId);13551356    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1357  });1358}13591360export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1361  await setMintPermissionExpectSuccess(sender, collectionId, true);1362}13631364export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1365  await usingApi(async (api) => {1366    // Run the transaction1367    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1368    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1369    const result = getCreateCollectionResult(events);1370    // tslint:disable-next-line:no-unused-expression1371    expect(result.success).to.be.false;1372  });1373}13741375export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1376  await usingApi(async (api) => {1377    // Run the transaction1378    const tx = api.tx.unique.setChainLimits(limits);1379    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1380    const result = getCreateCollectionResult(events);1381    // tslint:disable-next-line:no-unused-expression1382    expect(result.success).to.be.false;1383  });1384}13851386export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1387  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1388}13891390export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1391  await usingApi(async (api) => {1392    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;13931394    // Run the transaction1395    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1396    const events = await submitTransactionAsync(sender, tx);1397    const result = getGenericResult(events);1398    expect(result.success).to.be.true;13991400    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1401  });1402}14031404export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1405  await usingApi(async (api) => {14061407    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;14081409    // Run the transaction1410    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1411    const events = await submitTransactionAsync(sender, tx);1412    const result = getGenericResult(events);1413    expect(result.success).to.be.true;14141415    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1416  });1417}14181419export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1420  await usingApi(async (api) => {14211422    // Run the transaction1423    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1424    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1425    const result = getGenericResult(events);14261427    // What to expect1428    // tslint:disable-next-line:no-unused-expression1429    expect(result.success).to.be.false;1430  });1431}14321433export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1434  await usingApi(async (api) => {1435    // Run the transaction1436    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1437    const events = await submitTransactionAsync(sender, tx);1438    const result = getGenericResult(events);14391440    // What to expect1441    // tslint:disable-next-line:no-unused-expression1442    expect(result.success).to.be.true;1443  });1444}14451446export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1447  await usingApi(async (api) => {1448    // Run the transaction1449    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1450    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1451    const result = getGenericResult(events);14521453    // What to expect1454    // tslint:disable-next-line:no-unused-expression1455    expect(result.success).to.be.false;1456  });1457}14581459export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1460  : Promise<UpDataStructsRpcCollection | null> => {1461  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1462};14631464export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1465  // set global object - collectionsCount1466  return (await api.rpc.unique.collectionStats()).created.toNumber();1467};14681469export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1470  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1471}14721473export async function waitNewBlocks(blocksCount = 1): Promise<void> {1474  await usingApi(async (api) => {1475    const promise = new Promise<void>(async (resolve) => {1476      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1477        if (blocksCount > 0) {1478          blocksCount--;1479        } else {1480          unsubscribe();1481          resolve();1482        }1483      });1484    });1485    return promise;1486  });1487}
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, UpDataStructsCreateItemData, UpDataStructsProperty} 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}145146export function uniqueEventMessage(events: EventRecord[]): IGetMessage {147  let checkMsgUnqMethod = '';148  let checkMsgTrsMethod = '';149  let checkMsgSysMethod = '';150  events.forEach(({event: {method, section}}) => {151    if (section === 'common') {152      checkMsgUnqMethod = method;153    } else if (section === 'treasury') {154      checkMsgTrsMethod = method;155    } else if (section === 'system') {156      checkMsgSysMethod = method;157    } else { return null; }158  });159  const result: IGetMessage = {160    checkMsgUnqMethod,161    checkMsgTrsMethod,162    checkMsgSysMethod,163  };164  return result;165}166167export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {168  const event = events.find(r => check(r.event));169  if (!event) return;170  return event.event as T;171}172173export function getGenericResult(events: EventRecord[]): GenericResult {174  const result: GenericResult = {175    success: false,176  };177  events.forEach(({event: {method}}) => {178    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);179    if (method === 'ExtrinsicSuccess') {180      result.success = true;181    }182  });183  return result;184}185186187188export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {189  let success = false;190  let collectionId = 0;191  events.forEach(({event: {data, method, section}}) => {192    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);193    if (method == 'ExtrinsicSuccess') {194      success = true;195    } else if ((section == 'common') && (method == 'CollectionCreated')) {196      collectionId = parseInt(data[0].toString(), 10);197    }198  });199  const result: CreateCollectionResult = {200    success,201    collectionId,202  };203  return result;204}205206export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {207  let success = false;208  let collectionId = 0;209  let itemId = 0;210  let recipient;211212  const results : CreateItemResult[]  = [];213214  events.forEach(({event: {data, method, section}}) => {215    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);216    if (method == 'ExtrinsicSuccess') {217      success = true;218    } else if ((section == 'common') && (method == 'ItemCreated')) {219      collectionId = parseInt(data[0].toString(), 10);220      itemId = parseInt(data[1].toString(), 10);221      recipient = normalizeAccountId(data[2].toJSON() as any);222223      const itemRes: CreateItemResult = {224        success,225        collectionId,226        itemId,227        recipient,228      };229230      results.push(itemRes);231    }232  });233234  return results;235}236237export function getCreateItemResult(events: EventRecord[]): CreateItemResult {238  let success = false;239  let collectionId = 0;240  let itemId = 0;241  let recipient;242  events.forEach(({event: {data, method, section}}) => {243    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);244    if (method == 'ExtrinsicSuccess') {245      success = true;246    } else if ((section == 'common') && (method == 'ItemCreated')) {247      collectionId = parseInt(data[0].toString(), 10);248      itemId = parseInt(data[1].toString(), 10);249      recipient = normalizeAccountId(data[2].toJSON() as any);250    }251  });252  const result: CreateItemResult = {253    success,254    collectionId,255    itemId,256    recipient,257  };258  return result;259}260261export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {262  for (const {event} of events) {263    if (api.events.common.Transfer.is(event)) {264      const [collection, token, sender, recipient, value] = event.data;265      return {266        collectionId: collection.toNumber(),267        itemId: token.toNumber(),268        sender: normalizeAccountId(sender.toJSON() as any),269        recipient: normalizeAccountId(recipient.toJSON() as any),270        value: value.toBigInt(),271      };272    }273  }274  throw new Error('no transfer event');275}276277interface Nft {278  type: 'NFT';279}280281interface Fungible {282  type: 'Fungible';283  decimalPoints: number;284}285286interface ReFungible {287  type: 'ReFungible';288}289290type CollectionMode = Nft | Fungible | ReFungible;291292export type Property = {293  key: any,294  value: any,295};296297type Permission = {298  mutable: boolean;299  collectionAdmin: boolean;300  tokenOwner: boolean;301}302303type PropertyPermission = {304  key: any;305  permission: Permission;306}307308export type CreateCollectionParams = {309  mode: CollectionMode,310  name: string,311  description: string,312  tokenPrefix: string,313  schemaVersion: string,314  properties?: Array<Property>,315  propPerm?: Array<PropertyPermission>316};317318const defaultCreateCollectionParams: CreateCollectionParams = {319  description: 'description',320  mode: {type: 'NFT'},321  name: 'name',322  tokenPrefix: 'prefix',323  schemaVersion: 'ImageURL',324};325326export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {327  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};328329  let collectionId = 0;330  await usingApi(async (api) => {331    // Get number of collections before the transaction332    const collectionCountBefore = await getCreatedCollectionCount(api);333334    // Run the CreateCollection transaction335    const alicePrivateKey = privateKey('//Alice');336337    let modeprm = {};338    if (mode.type === 'NFT') {339      modeprm = {nft: null};340    } else if (mode.type === 'Fungible') {341      modeprm = {fungible: mode.decimalPoints};342    } else if (mode.type === 'ReFungible') {343      modeprm = {refungible: null};344    }345346    const tx = api.tx.unique.createCollectionEx({347      name: strToUTF16(name),348      description: strToUTF16(description),349      tokenPrefix: strToUTF16(tokenPrefix),350      mode: modeprm as any351    });352    const events = await submitTransactionAsync(alicePrivateKey, tx);353    const result = getCreateCollectionResult(events);354355    // Get number of collections after the transaction356    const collectionCountAfter = await getCreatedCollectionCount(api);357358    // Get the collection359    const collection = await queryCollectionExpectSuccess(api, result.collectionId);360361    // What to expect362    // tslint:disable-next-line:no-unused-expression363    expect(result.success).to.be.true;364    expect(result.collectionId).to.be.equal(collectionCountAfter);365    // tslint:disable-next-line:no-unused-expression366    expect(collection).to.be.not.null;367    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');368    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));369    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);370    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);371    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);372373    collectionId = result.collectionId;374  });375376  return collectionId;377}378379export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {380  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};381382  let collectionId = 0;383  await usingApi(async (api) => {384    // Get number of collections before the transaction385    const collectionCountBefore = await getCreatedCollectionCount(api);386387    // Run the CreateCollection transaction388    const alicePrivateKey = privateKey('//Alice');389390    let modeprm = {};391    if (mode.type === 'NFT') {392      modeprm = {nft: null};393    } else if (mode.type === 'Fungible') {394      modeprm = {fungible: mode.decimalPoints};395    } else if (mode.type === 'ReFungible') {396      modeprm = {refungible: null};397    }398399    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});400    const events = await submitTransactionAsync(alicePrivateKey, tx);401    const result = getCreateCollectionResult(events);402403    // Get number of collections after the transaction404    const collectionCountAfter = await getCreatedCollectionCount(api);405406    // Get the collection407    const collection = await queryCollectionExpectSuccess(api, result.collectionId);408409    // What to expect410    // tslint:disable-next-line:no-unused-expression411    expect(result.success).to.be.true;412    expect(result.collectionId).to.be.equal(collectionCountAfter);413    // tslint:disable-next-line:no-unused-expression414    expect(collection).to.be.not.null;415    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');416    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));417    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);418    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);419    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);420421422    collectionId = result.collectionId;423  });424425  return collectionId;426}427428export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {429  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};430431  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 const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: {mintMode?: boolean, access?: 'Normal' | 'AllowList', nesting?: 'Disabled' | 'Owner' | {OwnerRestricted: number[]}}) => {557  await usingApi(async(api) => {558    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);559    const events = await submitTransactionAsync(sender, tx);560    const result = getGenericResult(events);561562    expect(result.success).to.be.true;563  });564}565566export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {567  await usingApi(async (api) => {568    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);569    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;570    const result = getGenericResult(events);571572    expect(result.success).to.be.false;573  });574}575576export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {577  await usingApi(async (api) => {578579    // Run the transaction580    const senderPrivateKey = privateKey(sender);581    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);582    const events = await submitTransactionAsync(senderPrivateKey, tx);583    const result = getGenericResult(events);584585    // Get the collection586    const collection = await queryCollectionExpectSuccess(api, collectionId);587588    // What to expect589    expect(result.success).to.be.true;590    expect(collection.sponsorship.toJSON()).to.deep.equal({591      unconfirmed: sponsor,592    });593  });594}595596export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {597  await usingApi(async (api) => {598599    // Run the transaction600    const alicePrivateKey = privateKey(sender);601    const tx = api.tx.unique.removeCollectionSponsor(collectionId);602    const events = await submitTransactionAsync(alicePrivateKey, tx);603    const result = getGenericResult(events);604605    // Get the collection606    const collection = await queryCollectionExpectSuccess(api, collectionId);607608    // What to expect609    expect(result.success).to.be.true;610    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});611  });612}613614export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {615  await usingApi(async (api) => {616617    // Run the transaction618    const alicePrivateKey = privateKey(senderSeed);619    const tx = api.tx.unique.removeCollectionSponsor(collectionId);620    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;621  });622}623624export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {625  await usingApi(async (api) => {626627    // Run the transaction628    const alicePrivateKey = privateKey(senderSeed);629    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);630    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;631  });632}633634export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {635  await usingApi(async (api) => {636637    // Run the transaction638    const sender = privateKey(senderSeed);639    const tx = api.tx.unique.confirmSponsorship(collectionId);640    const events = await submitTransactionAsync(sender, tx);641    const result = getGenericResult(events);642643    // Get the collection644    const collection = await queryCollectionExpectSuccess(api, collectionId);645646    // What to expect647    expect(result.success).to.be.true;648    expect(collection.sponsorship.toJSON()).to.be.deep.equal({649      confirmed: sender.address,650    });651  });652}653654655export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {656  await usingApi(async (api) => {657658    // Run the transaction659    const sender = privateKey(senderSeed);660    const tx = api.tx.unique.confirmSponsorship(collectionId);661    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;662  });663}664665export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {666  await usingApi(async (api) => {667    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);668    const events = await submitTransactionAsync(sender, tx);669    const result = getGenericResult(events);670671    expect(result.success).to.be.true;672  });673}674675export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {676  await usingApi(async (api) => {677    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);678    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;679    const result = getGenericResult(events);680681    expect(result.success).to.be.false;682  });683}684685export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {686687  await usingApi(async (api) => {688689    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);690    const events = await submitTransactionAsync(sender, tx);691    const result = getGenericResult(events);692693    expect(result.success).to.be.true;694  });695}696697export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {698699  await usingApi(async (api) => {700701    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);702    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;703    const result = getGenericResult(events);704705    expect(result.success).to.be.false;706  });707}708709export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {710  await usingApi(async (api) => {711    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);712    const events = await submitTransactionAsync(sender, tx);713    const result = getGenericResult(events);714715    expect(result.success).to.be.true;716  });717}718719export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {720  await usingApi(async (api) => {721    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);722    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;723    const result = getGenericResult(events);724725    expect(result.success).to.be.false;726  });727}728729export async function getNextSponsored(730  api: ApiPromise,731  collectionId: number,732  account: string | CrossAccountId,733  tokenId: number,734): Promise<number> {735  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));736}737738export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {739  await usingApi(async (api) => {740    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);741    const events = await submitTransactionAsync(sender, tx);742    const result = getGenericResult(events);743744    expect(result.success).to.be.true;745  });746}747748export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {749  let allowlisted = false;750  await usingApi(async (api) => {751    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;752  });753  return allowlisted;754}755756export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {757  await usingApi(async (api) => {758    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());759    const events = await submitTransactionAsync(sender, tx);760    const result = getGenericResult(events);761762    expect(result.success).to.be.true;763  });764}765766export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {767  await usingApi(async (api) => {768    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());769    const events = await submitTransactionAsync(sender, tx);770    const result = getGenericResult(events);771772    expect(result.success).to.be.true;773  });774}775776export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {777  await usingApi(async (api) => {778    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());779    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;780    const result = getGenericResult(events);781782    expect(result.success).to.be.false;783  });784}785786/*export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {787  await usingApi(async (api) => {788    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));789    const events = await submitTransactionAsync(sender, tx);790    const result = getGenericResult(events);791792    expect(result.success).to.be.true;793  });794}795796export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {797  await usingApi(async (api) => {798    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));799    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;800  });801}*/802803export interface CreateFungibleData {804  readonly Value: bigint;805}806807export interface CreateReFungibleData { }808export interface CreateNftData { }809810export type CreateItemData = {811  NFT: CreateNftData;812} | {813  Fungible: CreateFungibleData;814} | {815  ReFungible: CreateReFungibleData;816};817818export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {819  await usingApi(async (api) => {820    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);821    // if burning token by admin - use adminButnItemExpectSuccess822    expect(balanceBefore >= BigInt(value)).to.be.true;823824    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);825    const events = await submitTransactionAsync(sender, tx);826    const result = getGenericResult(events);827    expect(result.success).to.be.true;828829    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);830    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);831  });832}833834export async function835approveExpectSuccess(836  collectionId: number,837  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,838) {839  await usingApi(async (api: ApiPromise) => {840    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);841    const events = await submitTransactionAsync(owner, approveUniqueTx);842    const result = getGenericResult(events);843    expect(result.success).to.be.true;844845    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));846  });847}848849export async function adminApproveFromExpectSuccess(850  collectionId: number,851  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,852) {853  await usingApi(async (api: ApiPromise) => {854    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);855    const events = await submitTransactionAsync(admin, approveUniqueTx);856    const result = getGenericResult(events);857    expect(result.success).to.be.true;858859    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));860  });861}862863export async function864transferFromExpectSuccess(865  collectionId: number,866  tokenId: number,867  accountApproved: IKeyringPair,868  accountFrom: IKeyringPair | CrossAccountId,869  accountTo: IKeyringPair | CrossAccountId,870  value: number | bigint = 1,871  type = 'NFT',872) {873  await usingApi(async (api: ApiPromise) => {874    const from = normalizeAccountId(accountFrom);875    const to = normalizeAccountId(accountTo);876    let balanceBefore = 0n;877    if (type === 'Fungible' || type === 'ReFungible') {878      balanceBefore = await getBalance(api, collectionId, to, tokenId);879    }880    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);881    const events = await submitTransactionAsync(accountApproved, transferFromTx);882    const result = getCreateItemResult(events);883    // tslint:disable-next-line:no-unused-expression884    expect(result.success).to.be.true;885    if (type === 'NFT') {886      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);887    }888    if (type === 'Fungible') {889      const balanceAfter = await getBalance(api, collectionId, to, tokenId);890      if (JSON.stringify(to) !== JSON.stringify(from)) {891        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));892      } else {893        expect(balanceAfter).to.be.equal(balanceBefore);894      }895    }896    if (type === 'ReFungible') {897      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));898    }899  });900}901902export async function903transferFromExpectFail(904  collectionId: number,905  tokenId: number,906  accountApproved: IKeyringPair,907  accountFrom: IKeyringPair,908  accountTo: IKeyringPair,909  value: number | bigint = 1,910) {911  await usingApi(async (api: ApiPromise) => {912    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);913    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;914    const result = getCreateCollectionResult(events);915    // tslint:disable-next-line:no-unused-expression916    expect(result.success).to.be.false;917  });918}919920/* eslint no-async-promise-executor: "off" */921async function getBlockNumber(api: ApiPromise): Promise<number> {922  return new Promise<number>(async (resolve) => {923    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {924      unsubscribe();925      resolve(head.number.toNumber());926    });927  });928}929930export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {931  await usingApi(async (api) => {932    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));933    const events = await submitTransactionAsync(sender, changeAdminTx);934    const result = getCreateCollectionResult(events);935    expect(result.success).to.be.true;936  });937}938939export async function940getFreeBalance(account: IKeyringPair): Promise<bigint> {941  let balance = 0n;942  await usingApi(async (api) => {943    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());944  });945946  return balance;947}948949export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {950  const tx = api.tx.balances.transfer(target, amount);951  const events = await submitTransactionAsync(source, tx);952  const result = getGenericResult(events);953  expect(result.success).to.be.true;954}955956export async function957scheduleTransferExpectSuccess(958  collectionId: number,959  tokenId: number,960  sender: IKeyringPair,961  recipient: IKeyringPair,962  value: number | bigint = 1,963  blockSchedule: number,964) {965  await usingApi(async (api: ApiPromise) => {966    const blockNumber: number | undefined = await getBlockNumber(api);967    const expectedBlockNumber = blockNumber + blockSchedule;968969    expect(blockNumber).to.be.greaterThan(0);970    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);971    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);972973    await submitTransactionAsync(sender, scheduleTx);974975    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();976977    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));978979    // sleep for 4 blocks980    await waitNewBlocks(blockSchedule + 1);981982    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();983984    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));985    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);986  });987}988989990export async function991transferExpectSuccess(992  collectionId: number,993  tokenId: number,994  sender: IKeyringPair,995  recipient: IKeyringPair | CrossAccountId,996  value: number | bigint = 1,997  type = 'NFT',998) {999  await usingApi(async (api: ApiPromise) => {1000    const from = normalizeAccountId(sender);1001    const to = normalizeAccountId(recipient);10021003    let balanceBefore = 0n;1004    if (type === 'Fungible') {1005      balanceBefore = await getBalance(api, collectionId, to, tokenId);1006    }1007    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1008    const events = await executeTransaction(api, sender, transferTx);10091010    const result = getTransferResult(api, events);1011    expect(result.collectionId).to.be.equal(collectionId);1012    expect(result.itemId).to.be.equal(tokenId);1013    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1014    expect(result.recipient).to.be.deep.equal(to);1015    expect(result.value).to.be.equal(BigInt(value));10161017    if (type === 'NFT') {1018      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1019    }1020    if (type === 'Fungible') {1021      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1022      if (JSON.stringify(to) !== JSON.stringify(from)) {1023        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1024      } else {1025        expect(balanceAfter).to.be.equal(balanceBefore);1026      }1027    }1028    if (type === 'ReFungible') {1029      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1030    }1031  });1032}10331034export async function1035transferExpectFailure(1036  collectionId: number,1037  tokenId: number,1038  sender: IKeyringPair,1039  recipient: IKeyringPair | CrossAccountId,1040  value: number | bigint = 1,1041) {1042  await usingApi(async (api: ApiPromise) => {1043    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1044    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1045    const result = getGenericResult(events);1046    // if (events && Array.isArray(events)) {1047    //   const result = getCreateCollectionResult(events);1048    // tslint:disable-next-line:no-unused-expression1049    expect(result.success).to.be.false;1050    //}1051  });1052}10531054export async function1055approveExpectFail(1056  collectionId: number,1057  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1058) {1059  await usingApi(async (api: ApiPromise) => {1060    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1061    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1062    const result = getCreateCollectionResult(events);1063    // tslint:disable-next-line:no-unused-expression1064    expect(result.success).to.be.false;1065  });1066}10671068export async function getBalance(1069  api: ApiPromise,1070  collectionId: number,1071  owner: string | CrossAccountId,1072  token: number,1073): Promise<bigint> {1074  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1075}1076export async function getTokenOwner(1077  api: ApiPromise,1078  collectionId: number,1079  token: number,1080): Promise<CrossAccountId> {1081  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1082  if (owner == null) throw new Error('owner == null');1083  return normalizeAccountId(owner);1084}1085export async function getTopmostTokenOwner(1086  api: ApiPromise,1087  collectionId: number,1088  token: number,1089): Promise<CrossAccountId> {1090  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1091  if (owner == null) throw new Error('owner == null');1092  return normalizeAccountId(owner);1093}1094export async function isTokenExists(1095  api: ApiPromise,1096  collectionId: number,1097  token: number,1098): Promise<boolean> {1099  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1100}1101export async function getLastTokenId(1102  api: ApiPromise,1103  collectionId: number,1104): Promise<number> {1105  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1106}1107export async function getAdminList(1108  api: ApiPromise,1109  collectionId: number,1110): Promise<string[]> {1111  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1112}1113/*export async function getConstMetadata(1114  api: ApiPromise,1115  collectionId: number,1116  tokenId: number,1117): Promise<number[]> {1118  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1119}*/1120export async function getTokenProperties(1121  api: ApiPromise,1122  collectionId: number,1123  tokenId: number,1124  propertyKeys: string[],1125): Promise<UpDataStructsProperty[]> {1126  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1127}11281129export async function createFungibleItemExpectSuccess(1130  sender: IKeyringPair,1131  collectionId: number,1132  data: CreateFungibleData,1133  owner: CrossAccountId | string = sender.address,1134) {1135  return await usingApi(async (api) => {1136    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11371138    const events = await submitTransactionAsync(sender, tx);1139    const result = getCreateItemResult(events);11401141    expect(result.success).to.be.true;1142    return result.itemId;1143  });1144}11451146export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1147  await usingApi(async (api) => {1148    const to = normalizeAccountId(owner);1149    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);11501151    const events = await submitTransactionAsync(sender, tx);1152    const result = getCreateItemsResult(events);11531154    for (const res of result) {1155      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1156    }1157  });1158}11591160export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1161  await usingApi(async (api) => {1162    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);11631164    const events = await submitTransactionAsync(sender, tx);1165    const result = getCreateItemsResult(events);11661167    for (const res of result) {1168      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1169    }1170  });1171}11721173export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1174  let newItemId = 0;1175  await usingApi(async (api) => {1176    const to = normalizeAccountId(owner);1177    const itemCountBefore = await getLastTokenId(api, collectionId);1178    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11791180    let tx;1181    if (createMode === 'Fungible') {1182      const createData = {fungible: {value: 10}};1183      tx = api.tx.unique.createItem(collectionId, to, createData as any);1184    } else if (createMode === 'ReFungible') {1185      const createData = {refungible: {pieces: 100}};1186      tx = api.tx.unique.createItem(collectionId, to, createData as any);1187    } else {1188      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1189      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1190    }11911192    const events = await submitTransactionAsync(sender, tx);1193    const result = getCreateItemResult(events);11941195    const itemCountAfter = await getLastTokenId(api, collectionId);1196    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11971198    if (createMode === 'NFT') {1199      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1200    }12011202    // What to expect1203    // tslint:disable-next-line:no-unused-expression1204    expect(result.success).to.be.true;1205    if (createMode === 'Fungible') {1206      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1207    } else {1208      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1209    }1210    expect(collectionId).to.be.equal(result.collectionId);1211    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1212    expect(to).to.be.deep.equal(result.recipient);1213    newItemId = result.itemId;1214  });1215  return newItemId;1216}12171218export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1219  await usingApi(async (api) => {12201221    let tx;1222    if (createMode === 'NFT') {1223      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1224      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1225    } else {1226      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1227    }122812291230    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1231    const result = getCreateItemResult(events);12321233    expect(result.success).to.be.false;1234  });1235}12361237export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1238  let newItemId = 0;1239  await usingApi(async (api) => {1240    const to = normalizeAccountId(owner);1241    const itemCountBefore = await getLastTokenId(api, collectionId);1242    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);12431244    let tx;1245    if (createMode === 'Fungible') {1246      const createData = {fungible: {value: 10}};1247      tx = api.tx.unique.createItem(collectionId, to, createData as any);1248    } else if (createMode === 'ReFungible') {1249      const createData = {refungible: {pieces: 100}};1250      tx = api.tx.unique.createItem(collectionId, to, createData as any);1251    } else {1252      const createData = {nft: {}};1253      tx = api.tx.unique.createItem(collectionId, to, createData as any);1254    }12551256    const events = await submitTransactionAsync(sender, tx);1257    const result = getCreateItemResult(events);12581259    const itemCountAfter = await getLastTokenId(api, collectionId);1260    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12611262    // What to expect1263    // tslint:disable-next-line:no-unused-expression1264    expect(result.success).to.be.true;1265    if (createMode === 'Fungible') {1266      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1267    } else {1268      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1269    }1270    expect(collectionId).to.be.equal(result.collectionId);1271    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1272    expect(to).to.be.deep.equal(result.recipient);1273    newItemId = result.itemId;1274  });1275  return newItemId;1276}12771278export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1279  await usingApi(async (api) => {1280    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);12811282    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1283    const result = getCreateItemResult(events);12841285    expect(result.success).to.be.false;1286  });1287}12881289export async function setPublicAccessModeExpectSuccess(1290  sender: IKeyringPair, collectionId: number,1291  accessMode: 'Normal' | 'AllowList',1292) {1293  await usingApi(async (api) => {12941295    // Run the transaction1296    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1297    const events = await submitTransactionAsync(sender, tx);1298    const result = getGenericResult(events);12991300    // Get the collection1301    const collection = await queryCollectionExpectSuccess(api, collectionId);13021303    // What to expect1304    // tslint:disable-next-line:no-unused-expression1305    expect(result.success).to.be.true;1306    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1307  });1308}13091310export async function setPublicAccessModeExpectFail(1311  sender: IKeyringPair, collectionId: number,1312  accessMode: 'Normal' | 'AllowList',1313) {1314  await usingApi(async (api) => {13151316    // Run the transaction1317    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1318    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1319    const result = getGenericResult(events);13201321    // What to expect1322    // tslint:disable-next-line:no-unused-expression1323    expect(result.success).to.be.false;1324  });1325}13261327export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1328  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1329}13301331export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1332  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1333}13341335export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1336  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1337}13381339export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1340  await usingApi(async (api) => {13411342    // Run the transaction1343    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1344    const events = await submitTransactionAsync(sender, tx);1345    const result = getGenericResult(events);1346    expect(result.success).to.be.true;13471348    // Get the collection1349    const collection = await queryCollectionExpectSuccess(api, collectionId);13501351    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1352  });1353}13541355export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1356  await setMintPermissionExpectSuccess(sender, collectionId, true);1357}13581359export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1360  await usingApi(async (api) => {1361    // Run the transaction1362    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1363    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1364    const result = getCreateCollectionResult(events);1365    // tslint:disable-next-line:no-unused-expression1366    expect(result.success).to.be.false;1367  });1368}13691370export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1371  await usingApi(async (api) => {1372    // Run the transaction1373    const tx = api.tx.unique.setChainLimits(limits);1374    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1375    const result = getCreateCollectionResult(events);1376    // tslint:disable-next-line:no-unused-expression1377    expect(result.success).to.be.false;1378  });1379}13801381export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1382  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1383}13841385export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1386  await usingApi(async (api) => {1387    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;13881389    // Run the transaction1390    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1391    const events = await submitTransactionAsync(sender, tx);1392    const result = getGenericResult(events);1393    expect(result.success).to.be.true;13941395    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1396  });1397}13981399export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1400  await usingApi(async (api) => {14011402    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;14031404    // Run the transaction1405    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1406    const events = await submitTransactionAsync(sender, tx);1407    const result = getGenericResult(events);1408    expect(result.success).to.be.true;14091410    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1411  });1412}14131414export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1415  await usingApi(async (api) => {14161417    // Run the transaction1418    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1419    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1420    const result = getGenericResult(events);14211422    // What to expect1423    // tslint:disable-next-line:no-unused-expression1424    expect(result.success).to.be.false;1425  });1426}14271428export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1429  await usingApi(async (api) => {1430    // Run the transaction1431    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1432    const events = await submitTransactionAsync(sender, tx);1433    const result = getGenericResult(events);14341435    // What to expect1436    // tslint:disable-next-line:no-unused-expression1437    expect(result.success).to.be.true;1438  });1439}14401441export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1442  await usingApi(async (api) => {1443    // Run the transaction1444    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1445    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1446    const result = getGenericResult(events);14471448    // What to expect1449    // tslint:disable-next-line:no-unused-expression1450    expect(result.success).to.be.false;1451  });1452}14531454export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1455  : Promise<UpDataStructsRpcCollection | null> => {1456  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1457};14581459export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1460  // set global object - collectionsCount1461  return (await api.rpc.unique.collectionStats()).created.toNumber();1462};14631464export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1465  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1466}14671468export async function waitNewBlocks(blocksCount = 1): Promise<void> {1469  await usingApi(async (api) => {1470    const promise = new Promise<void>(async (resolve) => {1471      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1472        if (blocksCount > 0) {1473          blocksCount--;1474        } else {1475          unsubscribe();1476          resolve();1477        }1478      });1479    });1480    return promise;1481  });1482}