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

difftreelog

CORE-160. Collection admin integration tests

str-mv2021-07-29parent: #cd2e9c1.patch.diff
in: master

23 files changed

modifiedtests/src/addToWhiteList.test.tsdiffbeforeafterboth
--- a/tests/src/addToWhiteList.test.ts
+++ b/tests/src/addToWhiteList.test.ts
@@ -16,6 +16,7 @@
   enablePublicMintingExpectSuccess,
   enableWhiteListExpectSuccess,
   normalizeAccountId,
+  addCollectionAdminExpectSuccess,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
@@ -23,6 +24,7 @@
 
 let Alice: IKeyringPair;
 let Bob: IKeyringPair;
+let Charlie: IKeyringPair;
 
 describe('Integration Test ext. addToWhiteList()', () => {
 
@@ -85,3 +87,32 @@
   });
 
 });
+
+describe('Integration Test ext. addToWhiteList() with collection admin permissions:', () => {
+
+  before(async () => {
+    await usingApi(async () => {
+      Alice = privateKey('//Alice');
+      Bob = privateKey('//Bob');
+      Charlie = privateKey('//Charlie');
+    });
+  });
+
+  it('Execute the extrinsic with parameters: Collection ID and address to add to the white list', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    await addCollectionAdminExpectSuccess(Alice, collectionId, Bob);
+    await addToWhiteListExpectSuccess(Bob, collectionId, Charlie.address);
+  });
+
+  it('Whitelisted minting: list restrictions', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    await addCollectionAdminExpectSuccess(Alice, collectionId, Bob);
+    await addToWhiteListExpectSuccess(Bob, collectionId, Charlie.address);
+
+    // allowed only for collection owner
+    await enableWhiteListExpectSuccess(Alice, collectionId);
+    await enablePublicMintingExpectSuccess(Alice, collectionId);
+
+    await createItemExpectSuccess(Charlie, collectionId, 'NFT', Charlie.address);
+  });
+});
\ No newline at end of file
modifiedtests/src/approve.test.tsdiffbeforeafterboth
--- a/tests/src/approve.test.ts
+++ b/tests/src/approve.test.ts
@@ -16,6 +16,7 @@
   destroyCollectionExpectSuccess,
   setCollectionLimitsExpectSuccess,
   transferExpectSuccess,
+  addCollectionAdminExpectSuccess,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
@@ -177,3 +178,25 @@
     await approveExpectFail(collectionId, itemId, Alice, Charlie);
   });
 });
+
+describe('Integration Test approve(spender, collection_id, item_id, amount) with collection admin permissions:', () => {
+  let Alice: IKeyringPair;
+  let Bob: IKeyringPair;
+  let Charlie: IKeyringPair;
+
+  before(async () => {
+    await usingApi(async () => {
+      Alice = privateKey('//Alice');
+      Bob = privateKey('//Bob');
+      Charlie = privateKey('//Charlie');
+    });
+  });
+
+  it('can be called by collection admin on non-owned item', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    const itemId = await createItemExpectSuccess(Alice, collectionId, 'NFT', Alice.address);
+
+    await addCollectionAdminExpectSuccess(Alice, collectionId, Bob);
+    await approveExpectSuccess(collectionId, itemId, Bob, Charlie);
+  });
+});
modifiedtests/src/burnItem.test.tsdiffbeforeafterboth
--- a/tests/src/burnItem.test.ts
+++ b/tests/src/burnItem.test.ts
@@ -12,6 +12,7 @@
   getGenericResult,
   destroyCollectionExpectSuccess,
   normalizeAccountId,
+  addCollectionAdminExpectSuccess,
 } from './util/helpers';
 
 import chai from 'chai';
@@ -48,8 +49,8 @@
       // tslint:disable-next-line:no-unused-expression
       expect(item).to.be.null;
     });
-
   });
+
   it('Burn item in Fungible collection', async () => {
     const createMode = 'Fungible';
     const collectionId = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0 }});
@@ -70,8 +71,8 @@
       expect(balance).to.be.not.null;
       expect(balance.Value).to.be.equal(9);
     });
+  });
 
-  });
   it('Burn item in ReFungible collection', async () => {
     const createMode = 'ReFungible';
     const collectionId = await createCollectionExpectSuccess({mode: {type: createMode }});
@@ -89,7 +90,6 @@
       expect(result.success).to.be.true;
       expect(balance).to.be.null;
     });
-
   });
 
   it('Burn owned portion of item in ReFungible collection', async () => {
@@ -136,6 +136,36 @@
 
 });
 
+describe('integration test: ext. burnItem() with admin permissions:', () => {
+  before(async () => {
+    await usingApi(async () => {
+      const keyring = new Keyring({ type: 'sr25519' });
+      alice = keyring.addFromUri('//Alice');
+      bob = keyring.addFromUri('//Bob');
+    });
+  });
+
+  it('Burn item in NFT collection', async () => {
+    const createMode = 'NFT';
+    const collectionId = await createCollectionExpectSuccess({mode: {type: createMode}});
+    const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);
+    await addCollectionAdminExpectSuccess(alice, collectionId, bob);
+
+    await usingApi(async (api) => {
+      const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);
+      const events = await submitTransactionAsync(bob, tx);
+      const result = getGenericResult(events);
+      // Get the item
+      const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();
+      // What to expect
+      // tslint:disable-next-line:no-unused-expression
+      expect(result.success).to.be.true;
+      // tslint:disable-next-line:no-unused-expression
+      expect(item).to.be.null;
+    });
+  });
+});
+
 describe('Negative integration test: ext. burnItem():', () => {
   before(async () => {
     await usingApi(async () => {
modifiedtests/src/change-collection-owner.test.tsdiffbeforeafterboth
--- a/tests/src/change-collection-owner.test.ts
+++ b/tests/src/change-collection-owner.test.ts
@@ -7,7 +7,7 @@
 import chaiAsPromised from 'chai-as-promised';
 import privateKey from './substrate/privateKey';
 import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';
-import { createCollectionExpectSuccess } from './util/helpers';
+import { createCollectionExpectSuccess, addCollectionAdminExpectSuccess } from './util/helpers';
 
 chai.use(chaiAsPromised);
 const expect = chai.expect;
@@ -48,6 +48,26 @@
       await createCollectionExpectSuccess();
     });
   });
+
+  it('Collection admin can\'t change owner.', async () => {
+    await usingApi(async api => {
+      const collectionId = await createCollectionExpectSuccess();
+      const alice = privateKey('//Alice');
+      const bob = privateKey('//Bob');
+
+      await addCollectionAdminExpectSuccess(alice, collectionId, bob);
+
+      const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
+      await expect(submitTransactionExpectFailAsync(bob, changeOwnerTx)).to.be.rejected;
+
+      const collectionAfterOwnerChange: any = (await api.query.nft.collectionById(collectionId)).toJSON();
+      expect(collectionAfterOwnerChange.Owner).to.be.deep.eq(alice.address);
+
+      // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
+      await createCollectionExpectSuccess();
+    });
+  });
+
   it('Can\'t change owner of a non-existing collection.', async () => {
     await usingApi(async api => {
       const collectionId = (1<<32) - 1;
modifiedtests/src/confirmSponsorship.test.tsdiffbeforeafterboth
--- a/tests/src/confirmSponsorship.test.ts
+++ b/tests/src/confirmSponsorship.test.ts
@@ -19,6 +19,7 @@
   enablePublicMintingExpectSuccess,
   addToWhiteListExpectSuccess,
   normalizeAccountId,
+  addCollectionAdminExpectSuccess,
 } from './util/helpers';
 import { Keyring } from '@polkadot/api';
 import { IKeyringPair } from '@polkadot/types/types';
@@ -365,6 +366,13 @@
     await confirmSponsorshipExpectFailure(collectionId, '//Alice');
   });
 
+  it('(!negative test!) Confirm sponsorship by collection admin', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+    await addCollectionAdminExpectSuccess(alice, collectionId, charlie);
+    await confirmSponsorshipExpectFailure(collectionId, '//Charlie');
+  });
+
   it('(!negative test!) Confirm sponsorship without sponsor being set with setCollectionSponsor', async () => {
     const collectionId = await createCollectionExpectSuccess();
     await confirmSponsorshipExpectFailure(collectionId, '//Bob');
modifiedtests/src/createItem.test.tsdiffbeforeafterboth
--- a/tests/src/createItem.test.ts
+++ b/tests/src/createItem.test.ts
@@ -4,20 +4,25 @@
 //
 
 import { default as usingApi } from './substrate/substrate-api';
+import chai from 'chai';
 import { Keyring } from '@polkadot/api';
 import { IKeyringPair } from '@polkadot/types/types';
 import { 
   createCollectionExpectSuccess, 
   createItemExpectSuccess,
+  addCollectionAdminExpectSuccess,
 } from './util/helpers';
 
+const expect = chai.expect;
 let alice: IKeyringPair;
+let bob: IKeyringPair;
 
 describe('integration test: ext. createItem():', () => {
   before(async () => {
     await usingApi(async () => {
       const keyring = new Keyring({ type: 'sr25519' });
       alice = keyring.addFromUri('//Alice');
+      bob = keyring.addFromUri('//Bob');
     });
   });
 
@@ -36,4 +41,48 @@
     const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode}});
     await createItemExpectSuccess(alice, newCollectionID, createMode);
   });
+  it('Create new item in NFT collection with collection admin permissions', async () => {
+    const createMode = 'NFT';
+    const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode}});
+    await addCollectionAdminExpectSuccess(alice, newCollectionID, bob);
+    await createItemExpectSuccess(bob, newCollectionID, createMode);
+  });
+  it('Create new item in Fungible collection with collection admin permissions', async () => {
+    const createMode = 'Fungible';
+    const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0}});
+    await addCollectionAdminExpectSuccess(alice, newCollectionID, bob);
+    await createItemExpectSuccess(bob, newCollectionID, createMode);
+  });
+  it('Create new item in ReFungible collection with collection admin permissions', async () => {
+    const createMode = 'ReFungible';
+    const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode}});
+    await addCollectionAdminExpectSuccess(alice, newCollectionID, bob);
+    await createItemExpectSuccess(bob, newCollectionID, createMode);
+  });
+});
+
+describe('Negative integration test: ext. createItem():', () => {
+  before(async () => {
+    await usingApi(async () => {
+      const keyring = new Keyring({ type: 'sr25519' });
+      alice = keyring.addFromUri('//Alice');
+      bob = keyring.addFromUri('//Bob');
+    });
+  });
+
+  it('Regular user cannot create new item in NFT collection', async () => {
+    const createMode = 'NFT';
+    const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode}});
+    await expect(createItemExpectSuccess(bob, newCollectionID, createMode)).to.be.rejected;
+  });
+  it('Regular user cannot create new item in Fungible collection', async () => {
+    const createMode = 'Fungible';
+    const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0}});
+    await expect(createItemExpectSuccess(bob, newCollectionID, createMode)).to.be.rejected;
+  });
+  it('Regular user cannot create new item in ReFungible collection', async () => {
+    const createMode = 'ReFungible';
+    const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode}});
+    await expect(createItemExpectSuccess(bob, newCollectionID, createMode)).to.be.rejected;
+  });
 });
modifiedtests/src/createMultipleItems.test.tsdiffbeforeafterboth
--- a/tests/src/createMultipleItems.test.ts
+++ b/tests/src/createMultipleItems.test.ts
@@ -3,6 +3,7 @@
 // file 'LICENSE', which is part of this source code package.
 //
 import { ApiPromise } from '@polkadot/api';
+import { IKeyringPair } from '@polkadot/types/types';
 import BN from 'bn.js';
 import chai from 'chai';
 import chaiAsPromised from 'chai-as-promised';
@@ -12,9 +13,11 @@
   createCollectionExpectSuccess,
   destroyCollectionExpectSuccess,
   getGenericResult,
+  IFungibleTokenDataType,
   IReFungibleTokenDataType,
   normalizeAccountId,
   setCollectionLimitsExpectSuccess,
+  addCollectionAdminExpectSuccess,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
@@ -57,6 +60,26 @@
     });
   });
 
+  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 api.query.nft.itemListIndex(collectionId) as unknown as BN;
+      expect(itemsListIndexBefore.toNumber()).to.be.equal(0);
+      const Alice = privateKey('//Alice');
+      const args = [
+        {fungible: { value: 1 }},
+        {fungible: { value: 2 }},
+        {fungible: { value: 3 }},
+      ];
+      const createMultipleItemsTx = api.tx.nft
+        .createMultipleItems(collectionId, normalizeAccountId(Alice.address), args);
+      await submitTransactionAsync(Alice, createMultipleItemsTx);
+      const token1Data = (await api.query.nft.fungibleItemList(collectionId, Alice.address) as any).toJSON() as unknown as IFungibleTokenDataType;
+
+      expect(token1Data.Value).to.be.equal(6); // 1 + 2 + 3
+    });
+  });
+
   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'}});
@@ -116,11 +139,167 @@
   });
 });
 
+describe('Integration Test createMultipleItems(collection_id, owner, items_data) with collection admin permissions:', () => {
+
+  let Alice: IKeyringPair;
+  let Bob: IKeyringPair;
+
+  before(async () => {
+    await usingApi(async () => {
+      Alice = privateKey('//Alice');
+      Bob = privateKey('//Bob');
+    });
+  });
+
+  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 api.query.nft.itemListIndex(collectionId) as unknown as BN;
+      expect(itemsListIndexBefore.toNumber()).to.be.equal(0);
+      await addCollectionAdminExpectSuccess(Alice, collectionId, Bob); 
+      const args = [{ nft: ['0x31', '0x31'] }, { nft: ['0x32', '0x32'] }, { nft: ['0x33', '0x33'] }];
+      const createMultipleItemsTx = api.tx.nft
+        .createMultipleItems(collectionId, normalizeAccountId(Bob.address), args);
+      await submitTransactionAsync(Bob, createMultipleItemsTx);
+      const itemsListIndexAfter = await api.query.nft.itemListIndex(collectionId) as unknown as BN;
+      expect(itemsListIndexAfter.toNumber()).to.be.equal(3);
+      const token1Data = (await api.query.nft.nftItemList(collectionId, 1)).toJSON() as unknown as ITokenDataType;
+      const token2Data = (await api.query.nft.nftItemList(collectionId, 2)).toJSON() as unknown as ITokenDataType;
+      const token3Data = (await api.query.nft.nftItemList(collectionId, 3)).toJSON() as unknown as ITokenDataType;
+
+      expect(token1Data.Owner).to.be.deep.equal(normalizeAccountId(Bob.address));
+      expect(token2Data.Owner).to.be.deep.equal(normalizeAccountId(Bob.address));
+      expect(token3Data.Owner).to.be.deep.equal(normalizeAccountId(Bob.address));
+
+      expect(token1Data.ConstData.toString()).to.be.equal('0x31');
+      expect(token2Data.ConstData.toString()).to.be.equal('0x32');
+      expect(token3Data.ConstData.toString()).to.be.equal('0x33');
+
+      expect(token1Data.VariableData.toString()).to.be.equal('0x31');
+      expect(token2Data.VariableData.toString()).to.be.equal('0x32');
+      expect(token3Data.VariableData.toString()).to.be.equal('0x33');
+    });
+  });
+
+  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 api.query.nft.itemListIndex(collectionId) as unknown as BN;
+      expect(itemsListIndexBefore.toNumber()).to.be.equal(0);
+      await addCollectionAdminExpectSuccess(Alice, collectionId, Bob); 
+      const args = [
+        {fungible: { value: 1 }},
+        {fungible: { value: 2 }},
+        {fungible: { value: 3 }},
+      ];
+      const createMultipleItemsTx = api.tx.nft
+        .createMultipleItems(collectionId, normalizeAccountId(Bob.address), args);
+      await submitTransactionAsync(Bob, createMultipleItemsTx);
+      const token1Data = (await api.query.nft.fungibleItemList(collectionId, Bob.address) as any).toJSON() as unknown as IFungibleTokenDataType;
+
+      expect(token1Data.Value).to.be.equal(6); // 1 + 2 + 3
+    });
+  });
+
+  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 api.query.nft.itemListIndex(collectionId) as unknown as BN;
+      expect(itemsListIndexBefore.toNumber()).to.be.equal(0);
+      await addCollectionAdminExpectSuccess(Alice, collectionId, Bob); 
+      const args = [
+        {refungible: {const_data: [0x31], variable_data: [0x31], pieces: 1}},
+        {refungible: {const_data: [0x32], variable_data: [0x32], pieces: 1}},
+        {refungible: {const_data: [0x33], variable_data: [0x33], pieces: 1}},
+      ];
+      const createMultipleItemsTx = api.tx.nft
+        .createMultipleItems(collectionId, normalizeAccountId(Bob.address), args);
+      await submitTransactionAsync(Bob, createMultipleItemsTx);
+      const itemsListIndexAfter = await api.query.nft.itemListIndex(collectionId) as unknown as BN;
+      expect(itemsListIndexAfter.toNumber()).to.be.equal(3);
+      const token1Data = (await api.query.nft.reFungibleItemList(collectionId, 1) as any).toJSON() as unknown as IReFungibleTokenDataType;
+      const token2Data = (await api.query.nft.reFungibleItemList(collectionId, 2) as any).toJSON() as unknown as IReFungibleTokenDataType;
+      const token3Data = (await api.query.nft.reFungibleItemList(collectionId, 3) as any).toJSON() as unknown as IReFungibleTokenDataType;
+
+      expect(token1Data.Owner[0].Owner).to.be.deep.equal(normalizeAccountId(Bob.address));
+      expect(token1Data.Owner[0].Fraction).to.be.equal(1);
+
+      expect(token2Data.Owner[0].Owner).to.be.deep.equal(normalizeAccountId(Bob.address));
+      expect(token2Data.Owner[0].Fraction).to.be.equal(1);
+
+      expect(token3Data.Owner[0].Owner).to.be.deep.equal(normalizeAccountId(Bob.address));
+      expect(token3Data.Owner[0].Fraction).to.be.equal(1);
+
+      expect(token1Data.ConstData.toString()).to.be.equal('0x31');
+      expect(token2Data.ConstData.toString()).to.be.equal('0x32');
+      expect(token3Data.ConstData.toString()).to.be.equal('0x33');
+
+      expect(token1Data.VariableData.toString()).to.be.equal('0x31');
+      expect(token2Data.VariableData.toString()).to.be.equal('0x32');
+      expect(token3Data.VariableData.toString()).to.be.equal('0x33');
+    });
+  });
+});
+
 describe('Negative Integration Test createMultipleItems(collection_id, owner, items_data):', () => {
+
+  let Alice: IKeyringPair;
+  let Bob: IKeyringPair;
+
+  before(async () => {
+    await usingApi(async () => {
+      Alice = privateKey('//Alice');
+      Bob = privateKey('//Bob');
+    });
+  });
+
+  it('Regular user cannot create items in active NFT collection', async () => {
+    await usingApi(async (api: ApiPromise) => {
+      const collectionId = await createCollectionExpectSuccess();
+      const itemsListIndexBefore = await api.query.nft.itemListIndex(collectionId) as unknown as BN;
+      expect(itemsListIndexBefore.toNumber()).to.be.equal(0);
+      const args = [{ nft: ['0x31', '0x31'] }, { nft: ['0x32', '0x32'] }, { nft: ['0x33', '0x33'] }];
+      const createMultipleItemsTx = api.tx.nft
+        .createMultipleItems(collectionId, normalizeAccountId(Alice.address), args);
+      await expect(submitTransactionAsync(Bob, createMultipleItemsTx)).to.be.rejected;
+    });
+  });
+
+  it('Regular user cannot create items in active Fungible collection', async () => {
+    await usingApi(async (api: ApiPromise) => {
+      const collectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+      const itemsListIndexBefore = await api.query.nft.itemListIndex(collectionId) as unknown as BN;
+      expect(itemsListIndexBefore.toNumber()).to.be.equal(0);
+      const args = [
+        {fungible: { value: 1 }},
+        {fungible: { value: 2 }},
+        {fungible: { value: 3 }},
+      ];
+      const createMultipleItemsTx = api.tx.nft
+        .createMultipleItems(collectionId, normalizeAccountId(Alice.address), args);
+      await expect(submitTransactionAsync(Bob, createMultipleItemsTx)).to.be.rejected;
+    });
+  });
+
+  it('Regular user cannot create items in active ReFungible collection', async () => {
+    await usingApi(async (api: ApiPromise) => {
+      const collectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
+      const itemsListIndexBefore = await api.query.nft.itemListIndex(collectionId) as unknown as BN;
+      expect(itemsListIndexBefore.toNumber()).to.be.equal(0);
+      const args = [
+        {refungible: {const_data: [0x31], variable_data: [0x31], pieces: 1}},
+        {refungible: {const_data: [0x32], variable_data: [0x32], pieces: 1}},
+        {refungible: {const_data: [0x33], variable_data: [0x33], pieces: 1}},
+      ];
+      const createMultipleItemsTx = api.tx.nft
+        .createMultipleItems(collectionId, normalizeAccountId(Alice.address), args);
+      await expect(submitTransactionAsync(Bob, createMultipleItemsTx)).to.be.rejected;
+    });
+  });
+
   it('Create token with not existing type', async () => {
     await usingApi(async (api: ApiPromise) => {
       const collectionId = await createCollectionExpectSuccess();
-      const Alice = privateKey('//Alice');
       try {
         const args = [{ invalid: null }, { invalid: null }, { invalid: null }];
         const createMultipleItemsTx = await api.tx.nft
@@ -136,7 +315,6 @@
   it('Create token in not existing collection', async () => {
     await usingApi(async (api: ApiPromise) => {
       const collectionId = parseInt((await api.query.nft.createdCollectionCount()).toString()) + 1;
-      const Alice = privateKey('//Alice');
       const createMultipleItemsTx = api.tx.nft
         .createMultipleItems(collectionId, normalizeAccountId(Alice.address), ['NFT', 'NFT', 'NFT']);
       await expect(submitTransactionExpectFailAsync(Alice, createMultipleItemsTx)).to.be.rejected;
@@ -174,7 +352,6 @@
   it('Create tokens with different types', async () => {
     await usingApi(async (api: ApiPromise) => {
       const collectionId = await createCollectionExpectSuccess();
-      const Alice = privateKey('//Alice');
       const createMultipleItemsTx = api.tx.nft
         .createMultipleItems(collectionId, normalizeAccountId(Alice.address), ['NFT', 'Fungible', 'ReFungible']);
       await expect(submitTransactionExpectFailAsync(Alice, createMultipleItemsTx)).to.be.rejected;
@@ -186,7 +363,6 @@
   it('Create tokens with different data limits <> maximum data limit', async () => {
     await usingApi(async (api: ApiPromise) => {
       const collectionId = await createCollectionExpectSuccess();
-      const Alice = privateKey('//Alice');
       const args = [
         { nft: ['A', 'A'] },
         { nft: ['B', 'B'.repeat(2049)] },
@@ -200,18 +376,17 @@
 
   it('Fails when minting tokens exceeds collectionLimits amount', async () => {
     await usingApi(async (api) => {
-      const alice = privateKey('//Alice');
 
       const collectionId = await createCollectionExpectSuccess();
-      await setCollectionLimitsExpectSuccess(alice, collectionId, {
+      await setCollectionLimitsExpectSuccess(Alice, collectionId, {
         TokenLimit: 1,
       });
       const args = [
         { nft: ['A', 'A'] },
         { nft: ['B', 'B'] },
       ];
-      const createMultipleItemsTx = api.tx.nft.createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
-      await expect(submitTransactionExpectFailAsync(alice, createMultipleItemsTx)).to.be.rejected;
+      const createMultipleItemsTx = api.tx.nft.createMultipleItems(collectionId, normalizeAccountId(Alice.address), args);
+      await expect(submitTransactionExpectFailAsync(Alice, createMultipleItemsTx)).to.be.rejected;
     });
   });
 });
modifiedtests/src/destroyCollection.test.tsdiffbeforeafterboth
--- a/tests/src/destroyCollection.test.ts
+++ b/tests/src/destroyCollection.test.ts
@@ -8,7 +8,12 @@
 import chaiAsPromised from 'chai-as-promised';
 import privateKey from './substrate/privateKey';
 import { default as usingApi } from './substrate/substrate-api';
-import { createCollectionExpectSuccess, destroyCollectionExpectSuccess, destroyCollectionExpectFailure, setCollectionLimitsExpectSuccess } from './util/helpers';
+import { createCollectionExpectSuccess, 
+  destroyCollectionExpectSuccess, 
+  destroyCollectionExpectFailure, 
+  setCollectionLimitsExpectSuccess,
+  addCollectionAdminExpectSuccess,
+} from './util/helpers';
 
 chai.use(chaiAsPromised);
 
@@ -29,10 +34,12 @@
 
 describe('(!negative test!) integration test: ext. destroyCollection():', () => {
   let alice: IKeyringPair;
+  let bob: IKeyringPair;
 
   before(async () => {
     await usingApi(async () => {
       alice = privateKey('//Alice');
+      bob = privateKey('//Bob');
     });
   });
 
@@ -53,6 +60,11 @@
     await destroyCollectionExpectFailure(collectionId, '//Bob');
     await destroyCollectionExpectSuccess(collectionId, '//Alice');
   });
+  it('(!negative test!) Destroy a collection using collection admin account', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    await addCollectionAdminExpectSuccess(alice, collectionId, bob);
+    await destroyCollectionExpectFailure(collectionId, '//Bob');
+  });
   it('fails when OwnerCanDestroy == false', async () => {
     const collectionId = await createCollectionExpectSuccess();
     await setCollectionLimitsExpectSuccess(alice, collectionId, { OwnerCanDestroy: false });
modifiedtests/src/removeCollectionAdmin.test.tsdiffbeforeafterboth
--- a/tests/src/removeCollectionAdmin.test.ts
+++ b/tests/src/removeCollectionAdmin.test.ts
@@ -83,4 +83,22 @@
       await createCollectionExpectSuccess();
     });
   });
+
+  it('Regular user Can\'t remove collection admin', async () => {
+    await usingApi(async (api: ApiPromise) => {
+      const collectionId = await createCollectionExpectSuccess();
+      const Alice = privateKey('//Alice');
+      const Bob = privateKey('//Bob');
+      const Charlie = privateKey('//Charlie');
+
+      const addAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(Bob.address));
+      await submitTransactionAsync(Alice, addAdminTx);
+
+      const changeOwnerTx = api.tx.nft.removeCollectionAdmin(collectionId, normalizeAccountId(Bob.address));
+      await expect(submitTransactionExpectFailAsync(Charlie, changeOwnerTx)).to.be.rejected;
+
+      // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
+      await createCollectionExpectSuccess();
+    });
+  });
 });
modifiedtests/src/removeCollectionSponsor.test.tsdiffbeforeafterboth
--- a/tests/src/removeCollectionSponsor.test.ts
+++ b/tests/src/removeCollectionSponsor.test.ts
@@ -17,6 +17,7 @@
   removeCollectionSponsorExpectSuccess,
   removeCollectionSponsorExpectFailure,
   normalizeAccountId,
+  addCollectionAdminExpectSuccess,
 } from './util/helpers';
 import { Keyring } from '@polkadot/api';
 import { IKeyringPair } from '@polkadot/types/types';
@@ -104,6 +105,13 @@
     await removeCollectionSponsorExpectFailure(collectionId);
   });
 
+  it('(!negative test!) Remove sponsor for a collection with collection admin permissions', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+    await addCollectionAdminExpectSuccess(alice, collectionId, bob);
+    await removeCollectionSponsorExpectFailure(collectionId, '//Bob');
+  });
+
   it('(!negative test!) Remove sponsor in a destroyed collection', async () => {
     const collectionId = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
modifiedtests/src/removeFromWhiteList.test.tsdiffbeforeafterboth
--- a/tests/src/removeFromWhiteList.test.ts
+++ b/tests/src/removeFromWhiteList.test.ts
@@ -17,6 +17,7 @@
   removeFromWhiteListExpectFailure,
   disableWhiteListExpectSuccess,
   normalizeAccountId,
+  addCollectionAdminExpectSuccess,
 } from './util/helpers';
 import { IKeyringPair } from '@polkadot/types/types';
 import privateKey from './substrate/privateKey';
@@ -88,3 +89,39 @@
     });
   });
 });
+
+describe('Integration Test removeFromWhiteList with collection admin permissions', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+  let charlie: IKeyringPair;
+
+  before(async () => {
+    await usingApi(async () => {
+      alice = privateKey('//Alice');
+      bob = privateKey('//Bob');
+      charlie = privateKey('//Charlie');
+    });
+  });
+
+  it('ensure address is not in whitelist after removal', async () => {
+    await usingApi(async () => {
+      const collectionId = await createCollectionExpectSuccess({ mode: { type: 'NFT' } });
+      await enableWhiteListExpectSuccess(alice, collectionId);
+      await addCollectionAdminExpectSuccess(alice, collectionId, bob);
+      await addToWhiteListExpectSuccess(alice, collectionId, charlie.address);
+      await removeFromWhiteListExpectSuccess(bob, collectionId, normalizeAccountId(charlie.address));
+      expect(await isWhitelisted(collectionId, charlie.address)).to.be.false;
+    });
+  });
+
+  it('Collection admin allowed to remove from whitelist with unset whitelist status', async () => {
+    await usingApi(async () => {
+      const collectionWithoutWhitelistId = await createCollectionExpectSuccess();
+      await enableWhiteListExpectSuccess(alice, collectionWithoutWhitelistId);
+      await addCollectionAdminExpectSuccess(alice, collectionWithoutWhitelistId, bob);
+      await addToWhiteListExpectSuccess(alice, collectionWithoutWhitelistId, charlie.address);
+      await disableWhiteListExpectSuccess(alice, collectionWithoutWhitelistId);
+      await removeFromWhiteListExpectSuccess(bob, collectionWithoutWhitelistId, normalizeAccountId(charlie.address));
+    });
+  });
+});
\ No newline at end of file
addedtests/src/setChainLimits.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/setChainLimits.test.ts
@@ -0,0 +1,56 @@
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+import { IKeyringPair } from '@polkadot/types/types';
+import privateKey from './substrate/privateKey';
+import usingApi from './substrate/substrate-api';
+import {
+  createCollectionExpectSuccess,
+  addCollectionAdminExpectSuccess,
+  setChainLimitsExpectFailure,
+  IChainLimits,
+} from './util/helpers';
+
+describe.only('Negative Integration Test setChainLimits', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+  let dave: IKeyringPair;
+  let limits: IChainLimits;
+
+  before(async () => {
+    await usingApi(async () => {
+      alice = privateKey('//Alice');
+      bob = privateKey('//Bob');
+      dave = privateKey('//Dave');
+      limits = {
+        CollectionNumbersLimit : 1,
+        AccountTokenOwnershipLimit: 1,
+        CollectionsAdminsLimit: 1,
+        CustomDataLimit: 1,
+        NftSponsorTransferTimeout: 1,
+        FungibleSponsorTransferTimeout: 1,
+        RefungibleSponsorTransferTimeout: 1,
+        OffchainSchemaLimit: 1,
+        VariableOnChainSchemaLimit: 1,
+        ConstOnChainSchemaLimit: 1,
+      };
+    });
+  });
+
+  it('Collection owner cannot set chain limits', async () => {
+    await createCollectionExpectSuccess({ mode: { type: 'NFT' } });
+    await setChainLimitsExpectFailure(alice, limits);
+  });
+
+  it('Collection admin cannot set chain limits', async () => {
+    const collectionId = await createCollectionExpectSuccess({ mode: { type: 'NFT' } });
+    await addCollectionAdminExpectSuccess(alice, collectionId, bob);
+    await setChainLimitsExpectFailure(bob, limits);
+  });
+  
+  it('Regular user cannot set chain limits', async () => {
+    await setChainLimitsExpectFailure(dave, limits);
+  });
+});
modifiedtests/src/setCollectionLimits.test.tsdiffbeforeafterboth
--- a/tests/src/setCollectionLimits.test.ts
+++ b/tests/src/setCollectionLimits.test.ts
@@ -16,6 +16,7 @@
   getDetailedCollectionInfo,
   setCollectionLimitsExpectFailure,
   setCollectionLimitsExpectSuccess,
+  addCollectionAdminExpectSuccess,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
@@ -150,6 +151,21 @@
       await expect(submitTransactionExpectFailAsync(bob, tx)).to.be.rejected;
     });
   });
+  it('execute setCollectionLimits from admin collection', async () => {
+    await addCollectionAdminExpectSuccess(alice, collectionIdForTesting, bob);
+    await usingApi(async (api: ApiPromise) => {
+      tx = api.tx.nft.setCollectionLimits(
+        collectionIdForTesting,
+        {
+          accountTokenOwnershipLimit,
+          sponsoredDataSize,
+          sponsoredMintSize,
+          tokenLimit,
+        },
+      );
+      await expect(submitTransactionExpectFailAsync(bob, tx)).to.be.rejected;
+    });
+  });
   it('execute setCollectionLimits with incorrect limits', async () => {
     await usingApi(async (api: ApiPromise) => {
       tx = api.tx.nft.setCollectionLimits(
modifiedtests/src/setCollectionSponsor.test.tsdiffbeforeafterboth
--- a/tests/src/setCollectionSponsor.test.ts
+++ b/tests/src/setCollectionSponsor.test.ts
@@ -6,19 +6,27 @@
 import chai from 'chai';
 import chaiAsPromised from 'chai-as-promised';
 import { default as usingApi } from './substrate/substrate-api';
-import { createCollectionExpectSuccess, setCollectionSponsorExpectSuccess, destroyCollectionExpectSuccess, setCollectionSponsorExpectFailure } from './util/helpers';
+import { createCollectionExpectSuccess, 
+  setCollectionSponsorExpectSuccess, 
+  destroyCollectionExpectSuccess, 
+  setCollectionSponsorExpectFailure,
+  addCollectionAdminExpectSuccess,
+} from './util/helpers';
 import { Keyring } from '@polkadot/api';
 import { IKeyringPair } from '@polkadot/types/types';
 
 chai.use(chaiAsPromised);
 
+let alice: IKeyringPair;
 let bob: IKeyringPair;
+let charlie: IKeyringPair;
 
 describe('integration test: ext. setCollectionSponsor():', () => {
 
   before(async () => {
     await usingApi(async () => {
       const keyring = new Keyring({ type: 'sr25519' });
+      alice = keyring.addFromUri('//Alice');
       bob = keyring.addFromUri('//Bob');
     });
   });
@@ -55,7 +63,9 @@
   before(async () => {
     await usingApi(async () => {
       const keyring = new Keyring({ type: 'sr25519' });
+      alice = keyring.addFromUri('//Alice');
       bob = keyring.addFromUri('//Bob');
+      charlie = keyring.addFromUri('//Charlie');
     });
   });
 
@@ -77,4 +87,9 @@
     await destroyCollectionExpectSuccess(collectionId);
     await setCollectionSponsorExpectFailure(collectionId, bob.address);
   });
+  it('(!negative test!) Collection admin add sponsor', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    await addCollectionAdminExpectSuccess(alice, collectionId, bob);
+    await setCollectionSponsorExpectFailure(collectionId, charlie.address, '//Bob');
+  });
 });
modifiedtests/src/setConstOnChainSchema.test.tsdiffbeforeafterboth
--- a/tests/src/setConstOnChainSchema.test.ts
+++ b/tests/src/setConstOnChainSchema.test.ts
@@ -11,6 +11,7 @@
 import {
   createCollectionExpectSuccess,
   destroyCollectionExpectSuccess,
+  addCollectionAdminExpectSuccess,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
@@ -43,6 +44,17 @@
     });
   });
 
+  it('Collection admin can set the scheme', async () => {
+    await usingApi(async (api) => {
+      const collectionId = await createCollectionExpectSuccess();
+      const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();
+      expect(collection.Owner).to.be.eq(Alice.address);
+      await addCollectionAdminExpectSuccess(Alice, collectionId, Bob);
+      const setShema = api.tx.nft.setConstOnChainSchema(collectionId, Shema);
+      await submitTransactionAsync(Bob, setShema);
+    });
+  });
+
   it('Checking collection data using the ConstOnChainSchema parameter', async () => {
     await usingApi(async (api) => {
       const collectionId = await createCollectionExpectSuccess();
modifiedtests/src/setMintPermission.test.tsdiffbeforeafterboth
--- a/tests/src/setMintPermission.test.ts
+++ b/tests/src/setMintPermission.test.ts
@@ -16,6 +16,7 @@
   findNotExistingCollection,
   setMintPermissionExpectFailure,
   setMintPermissionExpectSuccess,
+  addCollectionAdminExpectSuccess,
 } from './util/helpers';
 
 describe('Integration Test setMintPermission', () => {
@@ -91,6 +92,14 @@
     await setMintPermissionExpectFailure(bob, collectionId, true);
   });
 
+  it('Collection admin fails on set', async () => {
+    await usingApi(async () => {
+      const collectionId = await createCollectionExpectSuccess({ mode: { type: 'NFT' } });
+      await addCollectionAdminExpectSuccess(alice, collectionId, bob);
+      await setMintPermissionExpectFailure(bob, collectionId, true);
+    });
+  });
+
   it('ensure non-white-listed non-privileged address can\'t mint tokens', async () => {
     await usingApi(async () => {
       const collectionId = await createCollectionExpectSuccess({ mode: { type: 'NFT' } });
modifiedtests/src/setOffchainSchema.test.tsdiffbeforeafterboth
--- a/tests/src/setOffchainSchema.test.ts
+++ b/tests/src/setOffchainSchema.test.ts
@@ -15,6 +15,7 @@
   queryCollectionExpectSuccess,
   setOffchainSchemaExpectFailure,
   setOffchainSchemaExpectSuccess,
+  addCollectionAdminExpectSuccess,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
@@ -24,10 +25,12 @@
 
 describe('Integration Test setOffchainSchema', () => {
   let alice: IKeyringPair;
+  let bob: IKeyringPair;
 
   before(async () => {
     await usingApi(async () => {
       alice = privateKey('//Alice');
+      bob = privateKey('//Bob');
     });
   });
 
@@ -38,6 +41,15 @@
 
     expect(collection.OffchainSchema).to.be.equal('0x' + Buffer.from(DATA).toString('hex'));
   });
+
+  it('execute setOffchainSchema (collection admin), verify data was set', async () => {
+    const collectionId = await createCollectionExpectSuccess({ mode: { type: 'NFT' } });
+    await addCollectionAdminExpectSuccess(alice, collectionId, bob);
+    await setOffchainSchemaExpectSuccess(bob, collectionId, DATA);
+    const collection = await queryCollectionExpectSuccess(collectionId);
+
+    expect(collection.OffchainSchema).to.be.equal('0x' + Buffer.from(DATA).toString('hex'));
+  });
 });
 
 describe('Negative Integration Test setOffchainSchema', () => {
modifiedtests/src/setPublicAccessMode.test.tsdiffbeforeafterboth
--- a/tests/src/setPublicAccessMode.test.ts
+++ b/tests/src/setPublicAccessMode.test.ts
@@ -18,6 +18,7 @@
   enablePublicMintingExpectSuccess,
   enableWhiteListExpectSuccess,
   normalizeAccountId,
+  addCollectionAdminExpectSuccess,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
@@ -92,3 +93,21 @@
     });
   });
 });
+
+describe('Negative Integration Test ext. collection admin setPublicAccessMode(): ', () => {
+  before(async () => {
+    await usingApi(async () => {
+      Alice = privateKey('//Alice');
+      Bob = privateKey('//Bob');
+    });
+  });
+  it('Set the collection that has been deleted', async () => {
+    await usingApi(async (api: ApiPromise) => {
+      // tslint:disable-next-line: no-bitwise
+      const collectionId = await createCollectionExpectSuccess();
+      await addCollectionAdminExpectSuccess(Alice, collectionId, Bob);
+      const tx = api.tx.nft.setPublicAccessMode(collectionId, 'WhiteList');
+      await expect(submitTransactionExpectFailAsync(Bob, tx)).to.be.rejected;
+    });
+  });
+});
modifiedtests/src/setSchemaVersion.test.tsdiffbeforeafterboth
--- a/tests/src/setSchemaVersion.test.ts
+++ b/tests/src/setSchemaVersion.test.ts
@@ -16,12 +16,14 @@
   getCreatedCollectionCount,
   getCreateItemResult,
   getDetailedCollectionInfo,
+  addCollectionAdminExpectSuccess,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
 const expect = chai.expect;
 
 let alice: IKeyringPair;
+let bob: IKeyringPair;
 let collectionIdForTesting: number;
 
 /*
@@ -66,11 +68,37 @@
       expect(collectionInfo ? collectionInfo.SchemaVersion.toString() : '').to.be.equal('Unique');
     });
   });
+});
+
+describe('Collection admin setSchemaVersion positive', () => {
+  let tx;
+  before(async () => {
+    await usingApi(async () => {
+      const keyring = new Keyring({ type: 'sr25519' });
+      alice = keyring.addFromUri('//Alice');
+      bob = keyring.addFromUri('//Bob');
+      await addCollectionAdminExpectSuccess(alice, collectionIdForTesting, bob);
+    });
+  });
+  it('execute setSchemaVersion with image url and unique ', async () => {
+    await usingApi(async (api: ApiPromise) => {
+      tx = api.tx.nft.setSchemaVersion(collectionIdForTesting, 'Unique');
+      const events = await submitTransactionAsync(bob, tx);
+      const result = getCreateItemResult(events);
+      const collectionInfo = await getDetailedCollectionInfo(api, collectionIdForTesting) as ICollectionInterface;
+      // 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.nft.setSchemaVersion(collectionIdForTesting, 'ImageURL');
-      const events = await submitTransactionAsync(alice, tx);
+      const events = await submitTransactionAsync(bob, tx);
       const result = getCreateItemResult(events);
       const collectionInfo = await getDetailedCollectionInfo(api, collectionIdForTesting) as ICollectionInterface;
       // tslint:disable-next-line:no-unused-expression
modifiedtests/src/setVariableMetaData.test.tsdiffbeforeafterboth
--- a/tests/src/setVariableMetaData.test.ts
+++ b/tests/src/setVariableMetaData.test.ts
@@ -16,6 +16,7 @@
   findNotExistingCollection,
   setVariableMetaDataExpectFailure,
   setVariableMetaDataExpectSuccess,
+  addCollectionAdminExpectSuccess,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
@@ -48,6 +49,36 @@
   });
 });
 
+describe('Integration Test collection admin setVariableMetaData', () => {
+  const data = [1, 2, 254, 255];
+
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+  let collectionId: number;
+  let tokenId: number;
+  before(async () => {
+    await usingApi(async () => {
+      alice = privateKey('//Alice');
+      bob = privateKey('//Bob');
+      collectionId = await createCollectionExpectSuccess({ mode: { type: 'NFT' } });
+      tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
+      await addCollectionAdminExpectSuccess(alice, collectionId, bob);
+    });
+  });
+
+  it('execute setVariableMetaData', async () => {
+    await setVariableMetaDataExpectSuccess(bob, collectionId, tokenId, data);
+  });
+
+  it('verify data was set', async () => {
+    await usingApi(async api => {
+      const item: any = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap();
+
+      expect(Array.from(item.VariableData)).to.deep.equal(Array.from(data));
+    });
+  });
+});
+
 describe('Negative Integration Test setVariableMetaData', () => {
   const data = [1];
 
modifiedtests/src/setVariableOnChainSchema.test.tsdiffbeforeafterboth
--- a/tests/src/setVariableOnChainSchema.test.ts
+++ b/tests/src/setVariableOnChainSchema.test.ts
@@ -11,6 +11,7 @@
 import {
   createCollectionExpectSuccess,
   destroyCollectionExpectSuccess,
+  addCollectionAdminExpectSuccess,
 } from './util/helpers';
 
 chai.use(chaiAsPromised);
@@ -55,6 +56,32 @@
   });
 });
 
+describe('Integration Test ext. collection admin setVariableOnChainSchema()', () => {
+
+  it('Run extrinsic with parameters of the collection id, set the scheme', async () => {
+    await usingApi(async (api) => {
+      const collectionId = await createCollectionExpectSuccess();
+      const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();
+      expect(collection.Owner).to.be.eq(Alice.address);
+      await addCollectionAdminExpectSuccess(Alice, collectionId, Bob);
+      const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, Schema);
+      await submitTransactionAsync(Bob, setSchema);
+    });
+  });
+
+  it('Checking collection data using the setVariableOnChainSchema parameter', async () => {
+    await usingApi(async (api) => {
+      const collectionId = await createCollectionExpectSuccess();
+      await addCollectionAdminExpectSuccess(Alice, collectionId, Bob);
+      const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, Schema);
+      await submitTransactionAsync(Bob, setSchema);
+      const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();
+      expect(collection.VariableOnChainSchema.toString()).to.be.eq(Schema);
+
+    });
+  });
+});
+
 describe('Negative Integration Test ext. setVariableOnChainSchema()', () => {
 
   it('Set a non-existent collection', async () => {
modifiedtests/src/transfer.test.tsdiffbeforeafterboth
--- a/tests/src/transfer.test.ts
+++ b/tests/src/transfer.test.ts
@@ -18,6 +18,7 @@
   getCreateItemResult,
   transferExpectFailure,
   transferExpectSuccess,
+  addCollectionAdminExpectSuccess,
 } from './util/helpers';
 
 let Alice: IKeyringPair;
@@ -89,6 +90,35 @@
       );
     });
   });
+
+  it('Collection admin can transfer owned token', async () => {
+    await usingApi(async () => {
+      const Alice = privateKey('//Alice');
+      const Bob = privateKey('//Bob');
+      // nft
+      const nftCollectionId = await createCollectionExpectSuccess();
+      await addCollectionAdminExpectSuccess(Alice, nftCollectionId, Bob);
+      const newNftTokenId = await createItemExpectSuccess(Bob, nftCollectionId, 'NFT', Bob.address);
+      await transferExpectSuccess(nftCollectionId, newNftTokenId, Bob, Alice, 1, 'NFT');
+      // fungible
+      const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+      await addCollectionAdminExpectSuccess(Alice, fungibleCollectionId, Bob);
+      const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible', Bob.address);
+      await transferExpectSuccess(fungibleCollectionId, newFungibleTokenId, Bob, Alice, 1, 'Fungible');
+      // reFungible
+      const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
+      await addCollectionAdminExpectSuccess(Alice, reFungibleCollectionId, Bob);
+      const newReFungibleTokenId = await createItemExpectSuccess(Bob, reFungibleCollectionId, 'ReFungible', Bob.address);
+      await transferExpectSuccess(
+        reFungibleCollectionId,
+        newReFungibleTokenId,
+        Bob,
+        Alice,
+        100,
+        'ReFungible',
+      );
+    });
+  });
 });
 
 describe('Negative Integration Test Transfer(recipient, collection_id, item_id, value)', () => {
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
before · tests/src/util/helpers.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import { ApiPromise, Keyring } from '@polkadot/api';7import type { AccountId, EventRecord } from '@polkadot/types/interfaces';8import { IKeyringPair } from '@polkadot/types/types';9import { evmToAddress } from '@polkadot/util-crypto';10import { BigNumber } from 'bignumber.js';11import BN from 'bn.js';12import chai from 'chai';13import chaiAsPromised from 'chai-as-promised';14import { alicesPublicKey } from '../accounts';15import privateKey from '../substrate/privateKey';16import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';17import { ICollectionInterface } from '../types';18import { hexToStr, strToUTF16, utf16ToStr } from './util';1920chai.use(chaiAsPromised);21const expect = chai.expect;2223export type CrossAccountId = {24  substrate: string,25} | {26  ethereum: string,27};28export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {29  if (typeof input === 'string')30    return { substrate: input };31  if ('address' in input) {32    return { substrate: input.address };33  }34  if ('ethereum' in input) {35    input.ethereum = input.ethereum.toLowerCase();36    return input;37  }38  if ('substrate' in input) {39    return input;40  }4142  // AccountId43  return {substrate: input.toString()};44}45export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {46  input = normalizeAccountId(input);47  if ('substrate' in input) {48    return input.substrate;49  } else {50    return evmToAddress(input.ethereum);51  }52}5354export const U128_MAX = (1n << 128n) - 1n;5556type GenericResult = {57  success: boolean,58};5960interface CreateCollectionResult {61  success: boolean;62  collectionId: number;63}6465interface CreateItemResult {66  success: boolean;67  collectionId: number;68  itemId: number;69  recipient?: CrossAccountId;70}7172interface TransferResult {73  success: boolean;74  collectionId: number;75  itemId: number;76  sender?: CrossAccountId;77  recipient?: CrossAccountId;78  value: bigint;79}8081interface IReFungibleOwner {82  Fraction: BN;83  Owner: number[];84}8586interface ITokenDataType {87  Owner: IKeyringPair;88  ConstData: number[];89  VariableData: number[];90}9192interface IGetMessage {93  checkMsgNftMethod: string;94  checkMsgTrsMethod: string;95  checkMsgSysMethod: string;96}9798export interface IReFungibleTokenDataType {99  Owner: IReFungibleOwner[];100  ConstData: number[];101  VariableData: number[];102}103104export function nftEventMessage(events: EventRecord[]): IGetMessage {105  let checkMsgNftMethod = '';106  let checkMsgTrsMethod = '';107  let checkMsgSysMethod = '';108  events.forEach(({ event: { method, section } }) => {109    if (section === 'nft') {110      checkMsgNftMethod = method;111    } else if (section === 'treasury') {112      checkMsgTrsMethod = method;113    } else if (section === 'system') {114      checkMsgSysMethod = method;115    } else { return null; }116  });117  const result: IGetMessage = {118    checkMsgNftMethod,119    checkMsgTrsMethod,120    checkMsgSysMethod,121  };122  return result;123}124125export function getGenericResult(events: EventRecord[]): GenericResult {126  const result: GenericResult = {127    success: false,128  };129  events.forEach(({ event: { method } }) => {130    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);131    if (method === 'ExtrinsicSuccess') {132      result.success = true;133    }134  });135  return result;136}137138139140export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {141  let success = false;142  let collectionId = 0;143  events.forEach(({ event: { data, method, section } }) => {144    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);145    if (method == 'ExtrinsicSuccess') {146      success = true;147    } else if ((section == 'nft') && (method == 'CollectionCreated')) {148      collectionId = parseInt(data[0].toString());149    }150  });151  const result: CreateCollectionResult = {152    success,153    collectionId,154  };155  return result;156}157158export function getCreateItemResult(events: EventRecord[]): CreateItemResult {159  let success = false;160  let collectionId = 0;161  let itemId = 0;162  let recipient;163  events.forEach(({ event: { data, method, section } }) => {164    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);165    if (method == 'ExtrinsicSuccess') {166      success = true;167    } else if ((section == 'nft') && (method == 'ItemCreated')) {168      collectionId = parseInt(data[0].toString());169      itemId = parseInt(data[1].toString());170      recipient = data[2].toJSON();171    }172  });173  const result: CreateItemResult = {174    success,175    collectionId,176    itemId,177    recipient,178  };179  return result;180}181182export function getTransferResult(events: EventRecord[]): TransferResult {183  const result: TransferResult = {184    success: false,185    collectionId: 0,186    itemId: 0,187    value: 0n,188  };189190  events.forEach(({ event: { data, method, section } }) => {191    if (method === 'ExtrinsicSuccess') {192      result.success = true;193    } else if (section === 'nft' && method === 'Transfer') {194      result.collectionId = +data[0].toString();195      result.itemId = +data[1].toString();196      result.sender = data[2].toJSON() as CrossAccountId;197      result.recipient = data[3].toJSON() as CrossAccountId;198      result.value = BigInt(data[4].toString());199    }200  });201202  return result;203}204205interface Invalid {206  type: 'Invalid';207}208209interface Nft {210  type: 'NFT';211}212213interface Fungible {214  type: 'Fungible';215  decimalPoints: number;216}217218interface ReFungible {219  type: 'ReFungible';220}221222type CollectionMode = Nft | Fungible | ReFungible | Invalid;223224export type CreateCollectionParams = {225  mode: CollectionMode,226  name: string,227  description: string,228  tokenPrefix: string,229};230231const defaultCreateCollectionParams: CreateCollectionParams = {232  description: 'description',233  mode: { type: 'NFT' },234  name: 'name',235  tokenPrefix: 'prefix',236};237238export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {239  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };240241  let collectionId = 0;242  await usingApi(async (api) => {243    // Get number of collections before the transaction244    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);245246    // Run the CreateCollection transaction247    const alicePrivateKey = privateKey('//Alice');248249    let modeprm = {};250    if (mode.type === 'NFT') {251      modeprm = { nft: null };252    } else if (mode.type === 'Fungible') {253      modeprm = { fungible: mode.decimalPoints };254    } else if (mode.type === 'ReFungible') {255      modeprm = { refungible: null };256    } else if (mode.type === 'Invalid') {257      modeprm = { invalid: null };258    }259260    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);261    const events = await submitTransactionAsync(alicePrivateKey, tx);262    const result = getCreateCollectionResult(events);263264    // Get number of collections after the transaction265    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);266267    // Get the collection268    const collection: any = (await api.query.nft.collectionById(result.collectionId) as any).toJSON();269270    // What to expect271    // tslint:disable-next-line:no-unused-expression272    expect(result.success).to.be.true;273    expect(result.collectionId).to.be.equal(BcollectionCount);274    // tslint:disable-next-line:no-unused-expression275    expect(collection).to.be.not.null;276    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');277    expect(collection.Owner).to.be.equal(toSubstrateAddress(alicesPublicKey));278    expect(utf16ToStr(collection.Name)).to.be.equal(name);279    expect(utf16ToStr(collection.Description)).to.be.equal(description);280    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);281282    collectionId = result.collectionId;283  });284285  return collectionId;286}287288export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {289  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };290291  let modeprm = {};292  if (mode.type === 'NFT') {293    modeprm = { nft: null };294  } else if (mode.type === 'Fungible') {295    modeprm = { fungible: mode.decimalPoints };296  } else if (mode.type === 'ReFungible') {297    modeprm = { refungible: null };298  } else if (mode.type === 'Invalid') {299    modeprm = { invalid: null };300  }301302  await usingApi(async (api) => {303    // Get number of collections before the transaction304    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());305306    // Run the CreateCollection transaction307    const alicePrivateKey = privateKey('//Alice');308    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);309    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;310    const result = getCreateCollectionResult(events);311312    // Get number of collections after the transaction313    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());314315    // What to expect316    // tslint:disable-next-line:no-unused-expression317    expect(result.success).to.be.false;318    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');319  });320}321322export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {323  let bal = new BigNumber(0);324  let unused;325  do {326    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;327    const keyring = new Keyring({ type: 'sr25519' });328    unused = keyring.addFromUri(`//${randomSeed}`);329    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());330  } while (bal.toFixed() != '0');331  return unused;332}333334export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {335  return await usingApi(async (api) => {336    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;337    return BigInt(bn.toString());338  });339}340341export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {342  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));343}344345export async function findNotExistingCollection(api: ApiPromise): Promise<number> {346  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;347  const newCollection: number = totalNumber + 1;348  return newCollection;349}350351function getDestroyResult(events: EventRecord[]): boolean {352  let success = false;353  events.forEach(({ event: { method } }) => {354    if (method == 'ExtrinsicSuccess') {355      success = true;356    }357  });358  return success;359}360361export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {362  await usingApi(async (api) => {363    // Run the DestroyCollection transaction364    const alicePrivateKey = privateKey(senderSeed);365    const tx = api.tx.nft.destroyCollection(collectionId);366    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;367  });368}369370export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {371  await usingApi(async (api) => {372    // Run the DestroyCollection transaction373    const alicePrivateKey = privateKey(senderSeed);374    const tx = api.tx.nft.destroyCollection(collectionId);375    const events = await submitTransactionAsync(alicePrivateKey, tx);376    const result = getDestroyResult(events);377378    // Get the collection379    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();380381    // What to expect382    expect(result).to.be.true;383    expect(collection).to.be.null;384  });385}386387export async function queryCollectionLimits(collectionId: number) {388  return await usingApi(async (api) => {389    return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;390  });391}392393export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {394  await usingApi(async (api) => {395    const oldLimits = await queryCollectionLimits(collectionId);396    const newLimits = { ...oldLimits as any, ...limits };397    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);398    const events = await submitTransactionAsync(sender, tx);399    const result = getGenericResult(events);400401    expect(result.success).to.be.true;402  });403}404405export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {406  await usingApi(async (api) => {407    const oldLimits = await queryCollectionLimits(collectionId);408    const newLimits = { ...oldLimits as any, ...limits };409    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);410    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;411    const result = getGenericResult(events);412413    expect(result.success).to.be.false;414  });415}416417export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {418  await usingApi(async (api) => {419420    // Run the transaction421    const alicePrivateKey = privateKey('//Alice');422    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);423    const events = await submitTransactionAsync(alicePrivateKey, tx);424    const result = getGenericResult(events);425426    // Get the collection427    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();428429    // What to expect430    expect(result.success).to.be.true;431    expect(collection.Sponsorship).to.deep.equal({432      unconfirmed: sponsor,433    });434  });435}436437export async function removeCollectionSponsorExpectSuccess(collectionId: number) {438  await usingApi(async (api) => {439440    // Run the transaction441    const alicePrivateKey = privateKey('//Alice');442    const tx = api.tx.nft.removeCollectionSponsor(collectionId);443    const events = await submitTransactionAsync(alicePrivateKey, tx);444    const result = getGenericResult(events);445446    // Get the collection447    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();448449    // What to expect450    expect(result.success).to.be.true;451    expect(collection.Sponsorship).to.be.deep.equal({ disabled: null });452  });453}454455export async function removeCollectionSponsorExpectFailure(collectionId: number) {456  await usingApi(async (api) => {457458    // Run the transaction459    const alicePrivateKey = privateKey('//Alice');460    const tx = api.tx.nft.removeCollectionSponsor(collectionId);461    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;462  });463}464465export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {466  await usingApi(async (api) => {467468    // Run the transaction469    const alicePrivateKey = privateKey(senderSeed);470    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);471    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;472  });473}474475export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {476  await usingApi(async (api) => {477478    // Run the transaction479    const sender = privateKey(senderSeed);480    const tx = api.tx.nft.confirmSponsorship(collectionId);481    const events = await submitTransactionAsync(sender, tx);482    const result = getGenericResult(events);483484    // Get the collection485    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();486487    // What to expect488    expect(result.success).to.be.true;489    expect(collection.Sponsorship).to.be.deep.equal({490      confirmed: sender.address,491    });492  });493}494495496export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {497  await usingApi(async (api) => {498499    // Run the transaction500    const sender = privateKey(senderSeed);501    const tx = api.tx.nft.confirmSponsorship(collectionId);502    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;503  });504}505506export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {507  await usingApi(async (api) => {508    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);509    const events = await submitTransactionAsync(sender, tx);510    const result = getGenericResult(events);511512    expect(result.success).to.be.true;513  });514}515516export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {517  await usingApi(async (api) => {518    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);519    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;520    const result = getGenericResult(events);521522    expect(result.success).to.be.false;523  });524}525526export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {527528  await usingApi(async (api) => {529530    const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);531    const events = await submitTransactionAsync(sender, tx);532    const result = getGenericResult(events);533534    expect(result.success).to.be.true;535  }); 536}537538export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {539540  await usingApi(async (api) => {541542    const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);543    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;544    const result = getGenericResult(events);545546    expect(result.success).to.be.false;547  }); 548}549550export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {551  await usingApi(async (api) => {552    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);553    const events = await submitTransactionAsync(sender, tx);554    const result = getGenericResult(events);555556    expect(result.success).to.be.true;557  });558}559560export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {561  await usingApi(async (api) => {562    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);563    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;564    const result = getGenericResult(events);565566    expect(result.success).to.be.false;567  });568}569570export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {571  await usingApi(async (api) => {572    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, value);573    const events = await submitTransactionAsync(sender, tx);574    const result = getGenericResult(events);575576    expect(result.success).to.be.true;577  });578}579580export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {581  let whitelisted = false;582  await usingApi(async (api) => {583    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;584  });585  return whitelisted;586}587588export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {589  await usingApi(async (api) => {590    const tx = api.tx.nft.addToContractWhiteList(contractAddress.toString(), user.toString());591    const events = await submitTransactionAsync(sender, tx);592    const result = getGenericResult(events);593594    expect(result.success).to.be.true;595  });596}597598export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {599  await usingApi(async (api) => {600    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());601    const events = await submitTransactionAsync(sender, tx);602    const result = getGenericResult(events);603604    expect(result.success).to.be.true;605  });606}607608export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {609  await usingApi(async (api) => {610    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());611    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;612    const result = getGenericResult(events);613614    expect(result.success).to.be.false;615  });616}617618export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {619  await usingApi(async (api) => {620    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));621    const events = await submitTransactionAsync(sender, tx);622    const result = getGenericResult(events);623624    expect(result.success).to.be.true;625  });626}627628export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {629  await usingApi(async (api) => {630    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));631    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;632  });633}634635export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {636  await usingApi(async (api) => {637    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));638    const events = await submitTransactionAsync(sender, tx);639    const result = getGenericResult(events);640641    expect(result.success).to.be.true;642  });643}644645export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {646  await usingApi(async (api) => {647    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));648    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;649  });650}651652export interface CreateFungibleData {653  readonly Value: bigint;654}655656export interface CreateReFungibleData { }657export interface CreateNftData { }658659export type CreateItemData = {660  NFT: CreateNftData;661} | {662  Fungible: CreateFungibleData;663} | {664  ReFungible: CreateReFungibleData;665};666667export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {668  await usingApi(async (api) => {669    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);670    const events = await submitTransactionAsync(owner, tx);671    const result = getGenericResult(events);672    // Get the item673    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();674    // What to expect675    // tslint:disable-next-line:no-unused-expression676    expect(result.success).to.be.true;677    // tslint:disable-next-line:no-unused-expression678    expect(item).to.be.null;679  });680}681682export async function683approveExpectSuccess(684  collectionId: number,685  tokenId: number, owner: IKeyringPair, approved: IKeyringPair | CrossAccountId | string, amount: number | bigint = 1,686) {687  await usingApi(async (api: ApiPromise) => {688    approved = normalizeAccountId(approved);689    const allowanceBefore =690      await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;691    const approveNftTx = api.tx.nft.approve(approved, collectionId, tokenId, amount);692    const events = await submitTransactionAsync(owner, approveNftTx);693    const result = getCreateItemResult(events);694    // tslint:disable-next-line:no-unused-expression695    expect(result.success).to.be.true;696    const allowanceAfter =697      await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;698    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());699  });700}701702export async function703transferFromExpectSuccess(704  collectionId: number,705  tokenId: number,706  accountApproved: IKeyringPair,707  accountFrom: IKeyringPair | CrossAccountId,708  accountTo: IKeyringPair | CrossAccountId,709  value: number | bigint = 1,710  type = 'NFT',711) {712  await usingApi(async (api: ApiPromise) => {713    const to = normalizeAccountId(accountTo);714    let balanceBefore = new BN(0);715    if (type === 'Fungible') {716      balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;717    }718    const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);719    const events = await submitTransactionAsync(accountApproved, transferFromTx);720    const result = getCreateItemResult(events);721    // tslint:disable-next-line:no-unused-expression722    expect(result.success).to.be.true;723    if (type === 'NFT') {724      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).toJSON() as ITokenDataType;725      expect(nftItemData.Owner).to.be.deep.equal(to);726    }727    if (type === 'Fungible') {728      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;729      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());730    }731    if (type === 'ReFungible') {732      const nftItemData =733        (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).toJSON() as IReFungibleTokenDataType;734      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(normalizeAccountId(to));735      expect(nftItemData.Owner[0].Fraction).to.be.equal(value);736    }737  });738}739740export async function741transferFromExpectFail(742  collectionId: number,743  tokenId: number,744  accountApproved: IKeyringPair,745  accountFrom: IKeyringPair,746  accountTo: IKeyringPair,747  value: number | bigint = 1,748) {749  await usingApi(async (api: ApiPromise) => {750    const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);751    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;752    const result = getCreateCollectionResult(events);753    // tslint:disable-next-line:no-unused-expression754    expect(result.success).to.be.false;755  });756}757758/* eslint no-async-promise-executor: "off" */759async function getBlockNumber(api: ApiPromise): Promise<number> {760  return new Promise<number>(async (resolve) => {761    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {762      unsubscribe();763      resolve(head.number.toNumber());764    });765  });766}767768export async function769scheduleTransferExpectSuccess(770  collectionId: number,771  tokenId: number,772  sender: IKeyringPair,773  recipient: IKeyringPair,774  value: number | bigint = 1,775  blockTimeMs: number,776  blockSchedule: number,777) {778  await usingApi(async (api: ApiPromise) => {779    const blockNumber: number | undefined = await getBlockNumber(api);780    const expectedBlockNumber = blockNumber + blockSchedule;781782    expect(blockNumber).to.be.greaterThan(0);783    const transferTx = await api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value); 784    const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);785786    await submitTransactionAsync(sender, scheduleTx);787788    const recipientBalanceBefore = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());789790    const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as any as ITokenDataType;791    expect(toSubstrateAddress(nftItemDataBefore.Owner)).to.be.equal(sender.address);792793    // sleep for 4 blocks794    await new Promise(resolve => setTimeout(resolve, blockTimeMs * (blockSchedule + 1)));795796    const recipientBalanceAfter = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());797798    const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;799    expect(toSubstrateAddress(nftItemData.Owner)).to.be.equal(recipient.address);800    expect(recipientBalanceAfter.toNumber()).to.be.equal(recipientBalanceBefore.toNumber());801  });802}803804805export async function806transferExpectSuccess(807  collectionId: number,808  tokenId: number,809  sender: IKeyringPair,810  recipient: IKeyringPair | CrossAccountId,811  value: number | bigint = 1,812  type = 'NFT',813) {814  await usingApi(async (api: ApiPromise) => {815    const to = normalizeAccountId(recipient);816817    let balanceBefore = new BN(0);818    if (type === 'Fungible') {819      balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;820    }821    const transferTx = api.tx.nft.transfer(to, collectionId, tokenId, value);822    const events = await submitTransactionAsync(sender, transferTx);823    const result = getTransferResult(events);824    // tslint:disable-next-line:no-unused-expression825    expect(result.success).to.be.true;826    expect(result.collectionId).to.be.equal(collectionId);827    expect(result.itemId).to.be.equal(tokenId);828    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));829    expect(result.recipient).to.be.deep.equal(to);830    expect(result.value.toString()).to.be.equal(value.toString());831    if (type === 'NFT') {832      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;833      expect(nftItemData.Owner).to.be.deep.equal(to);834    }835    if (type === 'Fungible') {836      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;837      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());838    }839    if (type === 'ReFungible') {840      const nftItemData =841        (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;842      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(to);843      expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());844    }845  });846}847848export async function849transferExpectFailure(850  collectionId: number,851  tokenId: number,852  sender: IKeyringPair,853  recipient: IKeyringPair,854  value: number | bigint = 1,855) {856  await usingApi(async (api: ApiPromise) => {857    const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);858    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;859    if (events && Array.isArray(events)) {860      const result = getCreateCollectionResult(events);861      // tslint:disable-next-line:no-unused-expression862      expect(result.success).to.be.false;863    }864  });865}866867export async function868approveExpectFail(869  collectionId: number,870  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,871) {872  await usingApi(async (api: ApiPromise) => {873    const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);874    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;875    const result = getCreateCollectionResult(events);876    // tslint:disable-next-line:no-unused-expression877    expect(result.success).to.be.false;878  });879}880881export async function getFungibleBalance(882  collectionId: number,883  owner: string,884) {885  return await usingApi(async (api) => {886    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as { Value: string };887    return BigInt(response.Value);888  });889}890891export async function createFungibleItemExpectSuccess(892  sender: IKeyringPair,893  collectionId: number,894  data: CreateFungibleData,895  owner: CrossAccountId | string = sender.address,896) {897  return await usingApi(async (api) => {898    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), { Fungible: data });899900    const events = await submitTransactionAsync(sender, tx);901    const result = getCreateItemResult(events);902903    expect(result.success).to.be.true;904    return result.itemId;905  });906}907908export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {909  let newItemId = 0;910  await usingApi(async (api) => {911    const to = normalizeAccountId(owner);912    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);913    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();914    const AItemBalance = new BigNumber(Aitem.Value);915916    let tx;917    if (createMode === 'Fungible') {918      const createData = { fungible: { value: 10 } };919      tx = api.tx.nft.createItem(collectionId, to, createData);920    } else if (createMode === 'ReFungible') {921      const createData = { refungible: { const_data: [], variable_data: [], pieces: 100 } };922      tx = api.tx.nft.createItem(collectionId, to, createData);923    } else {924      const createData = { nft: { const_data: [], variable_data: [] } };925      tx = api.tx.nft.createItem(collectionId, to, createData);926    }927928    const events = await submitTransactionAsync(sender, tx);929    const result = getCreateItemResult(events);930931    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);932    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();933    const BItemBalance = new BigNumber(Bitem.Value);934935    // What to expect936    // tslint:disable-next-line:no-unused-expression937    expect(result.success).to.be.true;938    if (createMode === 'Fungible') {939      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);940    } else {941      expect(BItemCount).to.be.equal(AItemCount + 1);942    }943    expect(collectionId).to.be.equal(result.collectionId);944    expect(BItemCount.toString()).to.be.equal(result.itemId.toString());945    expect(to).to.be.deep.equal(result.recipient);946    newItemId = result.itemId;947  });948  return newItemId;949}950951export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {952  await usingApi(async (api) => {953    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createMode);954    955    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;956    const result = getCreateItemResult(events);957958    expect(result.success).to.be.false;959  });960}961962export async function setPublicAccessModeExpectSuccess(963  sender: IKeyringPair, collectionId: number,964  accessMode: 'Normal' | 'WhiteList',965) {966  await usingApi(async (api) => {967968    // Run the transaction969    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);970    const events = await submitTransactionAsync(sender, tx);971    const result = getGenericResult(events);972973    // Get the collection974    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();975976    // What to expect977    // tslint:disable-next-line:no-unused-expression978    expect(result.success).to.be.true;979    expect(collection.Access).to.be.equal(accessMode);980  });981}982983export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {984  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');985}986987export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {988  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');989}990991export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {992  await usingApi(async (api) => {993994    // Run the transaction995    const tx = api.tx.nft.setMintPermission(collectionId, enabled);996    const events = await submitTransactionAsync(sender, tx);997    const result = getGenericResult(events);998999    // Get the collection1000    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();10011002    // What to expect1003    // tslint:disable-next-line:no-unused-expression1004    expect(result.success).to.be.true;1005    expect(collection.MintMode).to.be.equal(enabled);1006  });1007}10081009export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1010  await setMintPermissionExpectSuccess(sender, collectionId, true);1011}10121013export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1014  await usingApi(async (api) => {1015    // Run the transaction1016    const tx = api.tx.nft.setMintPermission(collectionId, enabled);1017    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1018    const result = getCreateCollectionResult(events);1019    // tslint:disable-next-line:no-unused-expression1020    expect(result.success).to.be.false;1021  });1022}10231024export async function isWhitelisted(collectionId: number, address: string) {1025  let whitelisted = false;1026  await usingApi(async (api) => {1027    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;1028  });1029  return whitelisted;1030}10311032export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1033  await usingApi(async (api) => {10341035    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();10361037    // Run the transaction1038    const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));1039    const events = await submitTransactionAsync(sender, tx);1040    const result = getGenericResult(events);10411042    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();10431044    // What to expect1045    // tslint:disable-next-line:no-unused-expression1046    expect(result.success).to.be.true;1047    // tslint:disable-next-line: no-unused-expression1048    expect(whiteListedBefore).to.be.false;1049    // tslint:disable-next-line: no-unused-expression1050    expect(whiteListedAfter).to.be.true;1051  });1052}10531054export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1055  await usingApi(async (api) => {1056    // Run the transaction1057    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));1058    const events = await submitTransactionAsync(sender, tx);1059    const result = getGenericResult(events);10601061    // What to expect1062    // tslint:disable-next-line:no-unused-expression1063    expect(result.success).to.be.true;1064  });1065}10661067export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1068  await usingApi(async (api) => {1069    // Run the transaction1070    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));1071    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1072    const result = getGenericResult(events);10731074    // What to expect1075    // tslint:disable-next-line:no-unused-expression1076    expect(result.success).to.be.false;1077  });1078}10791080export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1081  : Promise<ICollectionInterface | null> => {1082  return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1083};10841085export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1086  // set global object - collectionsCount1087  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();1088};10891090export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {1091  return await usingApi(async (api) => {1092    return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1093  });1094}
after · tests/src/util/helpers.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import { ApiPromise, Keyring } from '@polkadot/api';7import type { AccountId, EventRecord } from '@polkadot/types/interfaces';8import { IKeyringPair } from '@polkadot/types/types';9import { evmToAddress } from '@polkadot/util-crypto';10import { BigNumber } from 'bignumber.js';11import BN from 'bn.js';12import chai from 'chai';13import chaiAsPromised from 'chai-as-promised';14import { alicesPublicKey } from '../accounts';15import privateKey from '../substrate/privateKey';16import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';17import { ICollectionInterface } from '../types';18import { hexToStr, strToUTF16, utf16ToStr } from './util';1920chai.use(chaiAsPromised);21const expect = chai.expect;2223export type CrossAccountId = {24  substrate: string,25} | {26  ethereum: string,27};28export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {29  if (typeof input === 'string')30    return { substrate: input };31  if ('address' in input) {32    return { substrate: input.address };33  }34  if ('ethereum' in input) {35    input.ethereum = input.ethereum.toLowerCase();36    return input;37  }38  if ('substrate' in input) {39    return input;40  }4142  // AccountId43  return {substrate: input.toString()};44}45export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {46  input = normalizeAccountId(input);47  if ('substrate' in input) {48    return input.substrate;49  } else {50    return evmToAddress(input.ethereum);51  }52}5354export const U128_MAX = (1n << 128n) - 1n;5556type GenericResult = {57  success: boolean,58};5960interface CreateCollectionResult {61  success: boolean;62  collectionId: number;63}6465interface CreateItemResult {66  success: boolean;67  collectionId: number;68  itemId: number;69  recipient?: CrossAccountId;70}7172interface TransferResult {73  success: boolean;74  collectionId: number;75  itemId: number;76  sender?: CrossAccountId;77  recipient?: CrossAccountId;78  value: bigint;79}8081interface IReFungibleOwner {82  Fraction: BN;83  Owner: number[];84}8586interface ITokenDataType {87  Owner: IKeyringPair;88  ConstData: number[];89  VariableData: number[];90}9192interface IGetMessage {93  checkMsgNftMethod: string;94  checkMsgTrsMethod: string;95  checkMsgSysMethod: string;96}9798export interface IFungibleTokenDataType {99  Value: number;100}101102export interface IChainLimits {103  CollectionNumbersLimit: number;104	AccountTokenOwnershipLimit: number;105	CollectionsAdminsLimit: number;106	CustomDataLimit: number;107	NftSponsorTransferTimeout: number;108	FungibleSponsorTransferTimeout: number;109	RefungibleSponsorTransferTimeout: number;110	OffchainSchemaLimit: number;111	VariableOnChainSchemaLimit: number;112	ConstOnChainSchemaLimit: number;113}114115export interface IReFungibleTokenDataType {116  Owner: IReFungibleOwner[];117  ConstData: number[];118  VariableData: number[];119}120121export function nftEventMessage(events: EventRecord[]): IGetMessage {122  let checkMsgNftMethod = '';123  let checkMsgTrsMethod = '';124  let checkMsgSysMethod = '';125  events.forEach(({ event: { method, section } }) => {126    if (section === 'nft') {127      checkMsgNftMethod = method;128    } else if (section === 'treasury') {129      checkMsgTrsMethod = method;130    } else if (section === 'system') {131      checkMsgSysMethod = method;132    } else { return null; }133  });134  const result: IGetMessage = {135    checkMsgNftMethod,136    checkMsgTrsMethod,137    checkMsgSysMethod,138  };139  return result;140}141142export function getGenericResult(events: EventRecord[]): GenericResult {143  const result: GenericResult = {144    success: false,145  };146  events.forEach(({ event: { method } }) => {147    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);148    if (method === 'ExtrinsicSuccess') {149      result.success = true;150    }151  });152  return result;153}154155156157export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {158  let success = false;159  let collectionId = 0;160  events.forEach(({ event: { data, method, section } }) => {161    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);162    if (method == 'ExtrinsicSuccess') {163      success = true;164    } else if ((section == 'nft') && (method == 'CollectionCreated')) {165      collectionId = parseInt(data[0].toString());166    }167  });168  const result: CreateCollectionResult = {169    success,170    collectionId,171  };172  return result;173}174175export function getCreateItemResult(events: EventRecord[]): CreateItemResult {176  let success = false;177  let collectionId = 0;178  let itemId = 0;179  let recipient;180  events.forEach(({ event: { data, method, section } }) => {181    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);182    if (method == 'ExtrinsicSuccess') {183      success = true;184    } else if ((section == 'nft') && (method == 'ItemCreated')) {185      collectionId = parseInt(data[0].toString());186      itemId = parseInt(data[1].toString());187      recipient = data[2].toJSON();188    }189  });190  const result: CreateItemResult = {191    success,192    collectionId,193    itemId,194    recipient,195  };196  return result;197}198199export function getTransferResult(events: EventRecord[]): TransferResult {200  const result: TransferResult = {201    success: false,202    collectionId: 0,203    itemId: 0,204    value: 0n,205  };206207  events.forEach(({ event: { data, method, section } }) => {208    if (method === 'ExtrinsicSuccess') {209      result.success = true;210    } else if (section === 'nft' && method === 'Transfer') {211      result.collectionId = +data[0].toString();212      result.itemId = +data[1].toString();213      result.sender = data[2].toJSON() as CrossAccountId;214      result.recipient = data[3].toJSON() as CrossAccountId;215      result.value = BigInt(data[4].toString());216    }217  });218219  return result;220}221222interface Invalid {223  type: 'Invalid';224}225226interface Nft {227  type: 'NFT';228}229230interface Fungible {231  type: 'Fungible';232  decimalPoints: number;233}234235interface ReFungible {236  type: 'ReFungible';237}238239type CollectionMode = Nft | Fungible | ReFungible | Invalid;240241export type CreateCollectionParams = {242  mode: CollectionMode,243  name: string,244  description: string,245  tokenPrefix: string,246};247248const defaultCreateCollectionParams: CreateCollectionParams = {249  description: 'description',250  mode: { type: 'NFT' },251  name: 'name',252  tokenPrefix: 'prefix',253};254255export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {256  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };257258  let collectionId = 0;259  await usingApi(async (api) => {260    // Get number of collections before the transaction261    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);262263    // Run the CreateCollection transaction264    const alicePrivateKey = privateKey('//Alice');265266    let modeprm = {};267    if (mode.type === 'NFT') {268      modeprm = { nft: null };269    } else if (mode.type === 'Fungible') {270      modeprm = { fungible: mode.decimalPoints };271    } else if (mode.type === 'ReFungible') {272      modeprm = { refungible: null };273    } else if (mode.type === 'Invalid') {274      modeprm = { invalid: null };275    }276277    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);278    const events = await submitTransactionAsync(alicePrivateKey, tx);279    const result = getCreateCollectionResult(events);280281    // Get number of collections after the transaction282    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);283284    // Get the collection285    const collection: any = (await api.query.nft.collectionById(result.collectionId) as any).toJSON();286287    // What to expect288    // tslint:disable-next-line:no-unused-expression289    expect(result.success).to.be.true;290    expect(result.collectionId).to.be.equal(BcollectionCount);291    // tslint:disable-next-line:no-unused-expression292    expect(collection).to.be.not.null;293    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');294    expect(collection.Owner).to.be.equal(toSubstrateAddress(alicesPublicKey));295    expect(utf16ToStr(collection.Name)).to.be.equal(name);296    expect(utf16ToStr(collection.Description)).to.be.equal(description);297    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);298299    collectionId = result.collectionId;300  });301302  return collectionId;303}304305export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {306  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };307308  let modeprm = {};309  if (mode.type === 'NFT') {310    modeprm = { nft: null };311  } else if (mode.type === 'Fungible') {312    modeprm = { fungible: mode.decimalPoints };313  } else if (mode.type === 'ReFungible') {314    modeprm = { refungible: null };315  } else if (mode.type === 'Invalid') {316    modeprm = { invalid: null };317  }318319  await usingApi(async (api) => {320    // Get number of collections before the transaction321    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());322323    // Run the CreateCollection transaction324    const alicePrivateKey = privateKey('//Alice');325    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);326    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;327    const result = getCreateCollectionResult(events);328329    // Get number of collections after the transaction330    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());331332    // What to expect333    // tslint:disable-next-line:no-unused-expression334    expect(result.success).to.be.false;335    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');336  });337}338339export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {340  let bal = new BigNumber(0);341  let unused;342  do {343    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;344    const keyring = new Keyring({ type: 'sr25519' });345    unused = keyring.addFromUri(`//${randomSeed}`);346    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());347  } while (bal.toFixed() != '0');348  return unused;349}350351export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {352  return await usingApi(async (api) => {353    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;354    return BigInt(bn.toString());355  });356}357358export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {359  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));360}361362export async function findNotExistingCollection(api: ApiPromise): Promise<number> {363  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;364  const newCollection: number = totalNumber + 1;365  return newCollection;366}367368function getDestroyResult(events: EventRecord[]): boolean {369  let success = false;370  events.forEach(({ event: { method } }) => {371    if (method == 'ExtrinsicSuccess') {372      success = true;373    }374  });375  return success;376}377378export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {379  await usingApi(async (api) => {380    // Run the DestroyCollection transaction381    const alicePrivateKey = privateKey(senderSeed);382    const tx = api.tx.nft.destroyCollection(collectionId);383    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;384  });385}386387export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {388  await usingApi(async (api) => {389    // Run the DestroyCollection transaction390    const alicePrivateKey = privateKey(senderSeed);391    const tx = api.tx.nft.destroyCollection(collectionId);392    const events = await submitTransactionAsync(alicePrivateKey, tx);393    const result = getDestroyResult(events);394395    // Get the collection396    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();397398    // What to expect399    expect(result).to.be.true;400    expect(collection).to.be.null;401  });402}403404export async function queryCollectionLimits(collectionId: number) {405  return await usingApi(async (api) => {406    return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;407  });408}409410export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {411  await usingApi(async (api) => {412    const oldLimits = await queryCollectionLimits(collectionId);413    const newLimits = { ...oldLimits as any, ...limits };414    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);415    const events = await submitTransactionAsync(sender, tx);416    const result = getGenericResult(events);417418    expect(result.success).to.be.true;419  });420}421422export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {423  await usingApi(async (api) => {424    const oldLimits = await queryCollectionLimits(collectionId);425    const newLimits = { ...oldLimits as any, ...limits };426    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);427    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;428    const result = getGenericResult(events);429430    expect(result.success).to.be.false;431  });432}433434export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {435  await usingApi(async (api) => {436437    // Run the transaction438    const alicePrivateKey = privateKey('//Alice');439    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);440    const events = await submitTransactionAsync(alicePrivateKey, tx);441    const result = getGenericResult(events);442443    // Get the collection444    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();445446    // What to expect447    expect(result.success).to.be.true;448    expect(collection.Sponsorship).to.deep.equal({449      unconfirmed: sponsor,450    });451  });452}453454export async function removeCollectionSponsorExpectSuccess(collectionId: number) {455  await usingApi(async (api) => {456457    // Run the transaction458    const alicePrivateKey = privateKey('//Alice');459    const tx = api.tx.nft.removeCollectionSponsor(collectionId);460    const events = await submitTransactionAsync(alicePrivateKey, tx);461    const result = getGenericResult(events);462463    // Get the collection464    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();465466    // What to expect467    expect(result.success).to.be.true;468    expect(collection.Sponsorship).to.be.deep.equal({ disabled: null });469  });470}471472export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {473  await usingApi(async (api) => {474475    // Run the transaction476    const alicePrivateKey = privateKey(senderSeed);477    const tx = api.tx.nft.removeCollectionSponsor(collectionId);478    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;479  });480}481482export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {483  await usingApi(async (api) => {484485    // Run the transaction486    const alicePrivateKey = privateKey(senderSeed);487    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);488    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;489  });490}491492export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {493  await usingApi(async (api) => {494495    // Run the transaction496    const sender = privateKey(senderSeed);497    const tx = api.tx.nft.confirmSponsorship(collectionId);498    const events = await submitTransactionAsync(sender, tx);499    const result = getGenericResult(events);500501    // Get the collection502    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();503504    // What to expect505    expect(result.success).to.be.true;506    expect(collection.Sponsorship).to.be.deep.equal({507      confirmed: sender.address,508    });509  });510}511512513export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {514  await usingApi(async (api) => {515516    // Run the transaction517    const sender = privateKey(senderSeed);518    const tx = api.tx.nft.confirmSponsorship(collectionId);519    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;520  });521}522523export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {524  await usingApi(async (api) => {525    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);526    const events = await submitTransactionAsync(sender, tx);527    const result = getGenericResult(events);528529    expect(result.success).to.be.true;530  });531}532533export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {534  await usingApi(async (api) => {535    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);536    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;537    const result = getGenericResult(events);538539    expect(result.success).to.be.false;540  });541}542543export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {544545  await usingApi(async (api) => {546547    const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);548    const events = await submitTransactionAsync(sender, tx);549    const result = getGenericResult(events);550551    expect(result.success).to.be.true;552  }); 553}554555export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {556557  await usingApi(async (api) => {558559    const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);560    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;561    const result = getGenericResult(events);562563    expect(result.success).to.be.false;564  }); 565}566567export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {568  await usingApi(async (api) => {569    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);570    const events = await submitTransactionAsync(sender, tx);571    const result = getGenericResult(events);572573    expect(result.success).to.be.true;574  });575}576577export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {578  await usingApi(async (api) => {579    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);580    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;581    const result = getGenericResult(events);582583    expect(result.success).to.be.false;584  });585}586587export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {588  await usingApi(async (api) => {589    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, value);590    const events = await submitTransactionAsync(sender, tx);591    const result = getGenericResult(events);592593    expect(result.success).to.be.true;594  });595}596597export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {598  let whitelisted = false;599  await usingApi(async (api) => {600    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;601  });602  return whitelisted;603}604605export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {606  await usingApi(async (api) => {607    const tx = api.tx.nft.addToContractWhiteList(contractAddress.toString(), user.toString());608    const events = await submitTransactionAsync(sender, tx);609    const result = getGenericResult(events);610611    expect(result.success).to.be.true;612  });613}614615export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {616  await usingApi(async (api) => {617    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());618    const events = await submitTransactionAsync(sender, tx);619    const result = getGenericResult(events);620621    expect(result.success).to.be.true;622  });623}624625export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {626  await usingApi(async (api) => {627    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());628    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;629    const result = getGenericResult(events);630631    expect(result.success).to.be.false;632  });633}634635export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {636  await usingApi(async (api) => {637    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));638    const events = await submitTransactionAsync(sender, tx);639    const result = getGenericResult(events);640641    expect(result.success).to.be.true;642  });643}644645export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {646  await usingApi(async (api) => {647    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));648    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;649  });650}651652export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {653  await usingApi(async (api) => {654    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));655    const events = await submitTransactionAsync(sender, tx);656    const result = getGenericResult(events);657658    expect(result.success).to.be.true;659  });660}661662export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {663  await usingApi(async (api) => {664    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));665    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;666  });667}668669export interface CreateFungibleData {670  readonly Value: bigint;671}672673export interface CreateReFungibleData { }674export interface CreateNftData { }675676export type CreateItemData = {677  NFT: CreateNftData;678} | {679  Fungible: CreateFungibleData;680} | {681  ReFungible: CreateReFungibleData;682};683684export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {685  await usingApi(async (api) => {686    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);687    const events = await submitTransactionAsync(owner, tx);688    const result = getGenericResult(events);689    // Get the item690    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();691    // What to expect692    // tslint:disable-next-line:no-unused-expression693    expect(result.success).to.be.true;694    // tslint:disable-next-line:no-unused-expression695    expect(item).to.be.null;696  });697}698699export async function700approveExpectSuccess(701  collectionId: number,702  tokenId: number, owner: IKeyringPair, approved: IKeyringPair | CrossAccountId | string, amount: number | bigint = 1,703) {704  await usingApi(async (api: ApiPromise) => {705    approved = normalizeAccountId(approved);706    const allowanceBefore =707      await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;708    const approveNftTx = api.tx.nft.approve(approved, collectionId, tokenId, amount);709    const events = await submitTransactionAsync(owner, approveNftTx);710    const result = getCreateItemResult(events);711    // tslint:disable-next-line:no-unused-expression712    expect(result.success).to.be.true;713    const allowanceAfter =714      await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;715    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());716  });717}718719export async function720transferFromExpectSuccess(721  collectionId: number,722  tokenId: number,723  accountApproved: IKeyringPair,724  accountFrom: IKeyringPair | CrossAccountId,725  accountTo: IKeyringPair | CrossAccountId,726  value: number | bigint = 1,727  type = 'NFT',728) {729  await usingApi(async (api: ApiPromise) => {730    const to = normalizeAccountId(accountTo);731    let balanceBefore = new BN(0);732    if (type === 'Fungible') {733      balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;734    }735    const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);736    const events = await submitTransactionAsync(accountApproved, transferFromTx);737    const result = getCreateItemResult(events);738    // tslint:disable-next-line:no-unused-expression739    expect(result.success).to.be.true;740    if (type === 'NFT') {741      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).toJSON() as ITokenDataType;742      expect(nftItemData.Owner).to.be.deep.equal(to);743    }744    if (type === 'Fungible') {745      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;746      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());747    }748    if (type === 'ReFungible') {749      const nftItemData =750        (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).toJSON() as IReFungibleTokenDataType;751      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(normalizeAccountId(to));752      expect(nftItemData.Owner[0].Fraction).to.be.equal(value);753    }754  });755}756757export async function758transferFromExpectFail(759  collectionId: number,760  tokenId: number,761  accountApproved: IKeyringPair,762  accountFrom: IKeyringPair,763  accountTo: IKeyringPair,764  value: number | bigint = 1,765) {766  await usingApi(async (api: ApiPromise) => {767    const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);768    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;769    const result = getCreateCollectionResult(events);770    // tslint:disable-next-line:no-unused-expression771    expect(result.success).to.be.false;772  });773}774775/* eslint no-async-promise-executor: "off" */776async function getBlockNumber(api: ApiPromise): Promise<number> {777  return new Promise<number>(async (resolve) => {778    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {779      unsubscribe();780      resolve(head.number.toNumber());781    });782  });783}784785export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: IKeyringPair) {786  await usingApi(async (api) => {787    const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(address.address));788    const events = await submitTransactionAsync(sender, changeAdminTx);789    const result = getCreateCollectionResult(events);790    expect(result.success).to.be.true;791  });792}793794export async function795scheduleTransferExpectSuccess(796  collectionId: number,797  tokenId: number,798  sender: IKeyringPair,799  recipient: IKeyringPair,800  value: number | bigint = 1,801  blockTimeMs: number,802  blockSchedule: number,803) {804  await usingApi(async (api: ApiPromise) => {805    const blockNumber: number | undefined = await getBlockNumber(api);806    const expectedBlockNumber = blockNumber + blockSchedule;807808    expect(blockNumber).to.be.greaterThan(0);809    const transferTx = await api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value); 810    const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);811812    await submitTransactionAsync(sender, scheduleTx);813814    const recipientBalanceBefore = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());815816    const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as any as ITokenDataType;817    expect(toSubstrateAddress(nftItemDataBefore.Owner)).to.be.equal(sender.address);818819    // sleep for 4 blocks820    await new Promise(resolve => setTimeout(resolve, blockTimeMs * (blockSchedule + 1)));821822    const recipientBalanceAfter = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());823824    const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;825    expect(toSubstrateAddress(nftItemData.Owner)).to.be.equal(recipient.address);826    expect(recipientBalanceAfter.toNumber()).to.be.equal(recipientBalanceBefore.toNumber());827  });828}829830831export async function832transferExpectSuccess(833  collectionId: number,834  tokenId: number,835  sender: IKeyringPair,836  recipient: IKeyringPair | CrossAccountId,837  value: number | bigint = 1,838  type = 'NFT',839) {840  await usingApi(async (api: ApiPromise) => {841    const to = normalizeAccountId(recipient);842843    let balanceBefore = new BN(0);844    if (type === 'Fungible') {845      balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;846    }847    const transferTx = api.tx.nft.transfer(to, collectionId, tokenId, value);848    const events = await submitTransactionAsync(sender, transferTx);849    const result = getTransferResult(events);850    // tslint:disable-next-line:no-unused-expression851    expect(result.success).to.be.true;852    expect(result.collectionId).to.be.equal(collectionId);853    expect(result.itemId).to.be.equal(tokenId);854    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));855    expect(result.recipient).to.be.deep.equal(to);856    expect(result.value.toString()).to.be.equal(value.toString());857    if (type === 'NFT') {858      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;859      expect(nftItemData.Owner).to.be.deep.equal(to);860    }861    if (type === 'Fungible') {862      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;863      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());864    }865    if (type === 'ReFungible') {866      const nftItemData =867        (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;868      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(to);869      expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());870    }871  });872}873874export async function875transferExpectFailure(876  collectionId: number,877  tokenId: number,878  sender: IKeyringPair,879  recipient: IKeyringPair,880  value: number | bigint = 1,881) {882  await usingApi(async (api: ApiPromise) => {883    const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);884    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;885    if (events && Array.isArray(events)) {886      const result = getCreateCollectionResult(events);887      // tslint:disable-next-line:no-unused-expression888      expect(result.success).to.be.false;889    }890  });891}892893export async function894approveExpectFail(895  collectionId: number,896  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,897) {898  await usingApi(async (api: ApiPromise) => {899    const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);900    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;901    const result = getCreateCollectionResult(events);902    // tslint:disable-next-line:no-unused-expression903    expect(result.success).to.be.false;904  });905}906907export async function getFungibleBalance(908  collectionId: number,909  owner: string,910) {911  return await usingApi(async (api) => {912    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as { Value: string };913    return BigInt(response.Value);914  });915}916917export async function createFungibleItemExpectSuccess(918  sender: IKeyringPair,919  collectionId: number,920  data: CreateFungibleData,921  owner: CrossAccountId | string = sender.address,922) {923  return await usingApi(async (api) => {924    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), { Fungible: data });925926    const events = await submitTransactionAsync(sender, tx);927    const result = getCreateItemResult(events);928929    expect(result.success).to.be.true;930    return result.itemId;931  });932}933934export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {935  let newItemId = 0;936  await usingApi(async (api) => {937    const to = normalizeAccountId(owner);938    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);939    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();940    const AItemBalance = new BigNumber(Aitem.Value);941942    let tx;943    if (createMode === 'Fungible') {944      const createData = { fungible: { value: 10 } };945      tx = api.tx.nft.createItem(collectionId, to, createData);946    } else if (createMode === 'ReFungible') {947      const createData = { refungible: { const_data: [], variable_data: [], pieces: 100 } };948      tx = api.tx.nft.createItem(collectionId, to, createData);949    } else {950      const createData = { nft: { const_data: [], variable_data: [] } };951      tx = api.tx.nft.createItem(collectionId, to, createData);952    }953954    const events = await submitTransactionAsync(sender, tx);955    const result = getCreateItemResult(events);956957    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);958    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();959    const BItemBalance = new BigNumber(Bitem.Value);960961    // What to expect962    // tslint:disable-next-line:no-unused-expression963    expect(result.success).to.be.true;964    if (createMode === 'Fungible') {965      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);966    } else {967      expect(BItemCount).to.be.equal(AItemCount + 1);968    }969    expect(collectionId).to.be.equal(result.collectionId);970    expect(BItemCount.toString()).to.be.equal(result.itemId.toString());971    expect(to).to.be.deep.equal(result.recipient);972    newItemId = result.itemId;973  });974  return newItemId;975}976977export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {978  await usingApi(async (api) => {979    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createMode);980    981    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;982    const result = getCreateItemResult(events);983984    expect(result.success).to.be.false;985  });986}987988export async function setPublicAccessModeExpectSuccess(989  sender: IKeyringPair, collectionId: number,990  accessMode: 'Normal' | 'WhiteList',991) {992  await usingApi(async (api) => {993994    // Run the transaction995    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);996    const events = await submitTransactionAsync(sender, tx);997    const result = getGenericResult(events);998999    // Get the collection1000    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();10011002    // What to expect1003    // tslint:disable-next-line:no-unused-expression1004    expect(result.success).to.be.true;1005    expect(collection.Access).to.be.equal(accessMode);1006  });1007}10081009export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {1010  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');1011}10121013export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {1014  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1015}10161017export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1018  await usingApi(async (api) => {10191020    // Run the transaction1021    const tx = api.tx.nft.setMintPermission(collectionId, enabled);1022    const events = await submitTransactionAsync(sender, tx);1023    const result = getGenericResult(events);10241025    // Get the collection1026    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();10271028    // What to expect1029    // tslint:disable-next-line:no-unused-expression1030    expect(result.success).to.be.true;1031    expect(collection.MintMode).to.be.equal(enabled);1032  });1033}10341035export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1036  await setMintPermissionExpectSuccess(sender, collectionId, true);1037}10381039export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1040  await usingApi(async (api) => {1041    // Run the transaction1042    const tx = api.tx.nft.setMintPermission(collectionId, enabled);1043    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1044    const result = getCreateCollectionResult(events);1045    // tslint:disable-next-line:no-unused-expression1046    expect(result.success).to.be.false;1047  });1048}10491050export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1051  await usingApi(async (api) => {1052    // Run the transaction1053    const tx = api.tx.nft.setChainLimits(limits);1054    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1055    const result = getCreateCollectionResult(events);1056    // tslint:disable-next-line:no-unused-expression1057    expect(result.success).to.be.false;1058  });1059}10601061export async function isWhitelisted(collectionId: number, address: string) {1062  let whitelisted = false;1063  await usingApi(async (api) => {1064    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;1065  });1066  return whitelisted;1067}10681069export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1070  await usingApi(async (api) => {10711072    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();10731074    // Run the transaction1075    const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));1076    const events = await submitTransactionAsync(sender, tx);1077    const result = getGenericResult(events);10781079    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();10801081    // What to expect1082    // tslint:disable-next-line:no-unused-expression1083    expect(result.success).to.be.true;1084    // tslint:disable-next-line: no-unused-expression1085    expect(whiteListedBefore).to.be.false;1086    // tslint:disable-next-line: no-unused-expression1087    expect(whiteListedAfter).to.be.true;1088  });1089}10901091export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1092  await usingApi(async (api) => {1093    // Run the transaction1094    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));1095    const events = await submitTransactionAsync(sender, tx);1096    const result = getGenericResult(events);10971098    // What to expect1099    // tslint:disable-next-line:no-unused-expression1100    expect(result.success).to.be.true;1101  });1102}11031104export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1105  await usingApi(async (api) => {1106    // Run the transaction1107    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));1108    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1109    const result = getGenericResult(events);11101111    // What to expect1112    // tslint:disable-next-line:no-unused-expression1113    expect(result.success).to.be.false;1114  });1115}11161117export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1118  : Promise<ICollectionInterface | null> => {1119  return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1120};11211122export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1123  // set global object - collectionsCount1124  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();1125};11261127export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {1128  return await usingApi(async (api) => {1129    return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1130  });1131}