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

difftreelog

Merge remote-tracking branch 'origin/develop' into feature/NFTPAR-265

kpozdnikin2020-12-29parents: #10c5b4f #a9dbb97.patch.diff
in: master

13 files changed

addedtests/src/change-collection-owner.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/change-collection-owner.test.ts
@@ -0,0 +1,59 @@
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from './substrate/privateKey';
+import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";
+import { createCollectionExpectSuccess, createCollectionExpectFailure } from "./util/helpers";
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+describe('Integration Test changeCollectionOwner(collection_id, new_owner):', () => {
+  it('Changing owner changes owner.', async () => {
+    await usingApi(async api => {
+      const collectionId = await createCollectionExpectSuccess();
+      const alice = privateKey('//Alice');
+      const bob = privateKey('//Bob');
+
+      const collection: any = (await api.query.nft.collection(collectionId));
+      expect(collection.Owner.toString()).to.be.eq(alice.address);
+
+      const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
+      await submitTransactionAsync(alice, changeOwnerTx);
+
+      const collectionAfterOwnerChange: any = (await api.query.nft.collection(collectionId));
+      expect(collectionAfterOwnerChange.Owner.toString()).to.be.eq(bob.address);
+    });
+  });
+});
+
+describe('Negative Integration Test changeCollectionOwner(collection_id, new_owner):', () => {
+  it(`Not owner can't change owner.`, async () => {
+    await usingApi(async api => {
+      const collectionId = await createCollectionExpectSuccess();
+      const alice = privateKey('//Alice');
+      const bob = privateKey('//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.collection(collectionId));
+      expect(collectionAfterOwnerChange.Owner.toString()).to.be.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 not existing collection.`, async () => {
+    await usingApi(async api => {
+      const collectionId = (1<<32) - 1;
+      const alice = privateKey('//Alice');
+      const bob = privateKey('//Bob');
+
+      const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
+      await expect(submitTransactionExpectFailAsync(alice, changeOwnerTx)).to.be.rejected;
+
+      // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
+      await createCollectionExpectSuccess();
+    });
+  });
+});
modifiedtests/src/confirmSponsorship.test.tsdiffbeforeafterboth
--- a/tests/src/confirmSponsorship.test.ts
+++ b/tests/src/confirmSponsorship.test.ts
@@ -5,7 +5,7 @@
 
 import chai from 'chai';
 import chaiAsPromised from 'chai-as-promised';
-import { default as usingApi, submitTransactionAsync } from "./substrate/substrate-api";
+import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";
 import { 
   createCollectionExpectSuccess, 
   setCollectionSponsorExpectSuccess, 
@@ -44,25 +44,25 @@
   });
 
   it('Confirm collection sponsorship', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
   });
   it('Add sponsor to a collection after the same sponsor was already added and confirmed', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
   });
   it('Add new sponsor to a collection after another sponsor was already added and confirmed', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
     await setCollectionSponsorExpectSuccess(collectionId, charlie.address);
   });
 
   it('NFT: Transfer fees are paid by the sponsor after confirmation', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
@@ -89,7 +89,7 @@
   });
 
   it('Fungible: Transfer fees are paid by the sponsor after confirmation', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'Fungible');
+    const collectionId = await createCollectionExpectSuccess({mode: 'Fungible'});
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
@@ -115,7 +115,7 @@
   });
 
   it('ReFungible: Transfer fees are paid by the sponsor after confirmation', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'ReFungible');
+    const collectionId = await createCollectionExpectSuccess({mode: 'ReFungible'});
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
@@ -141,7 +141,7 @@
   });
 
   it('CreateItem fees are paid by the sponsor after confirmation', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
@@ -171,7 +171,7 @@
   });
 
   it('NFT: Sponsoring is rate limited', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
@@ -192,11 +192,7 @@
       const AsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());
       const zeroToAlice = api.tx.nft.transfer(alice.address, collectionId, itemId, 0);
       const badTransaction = async function () { 
-        console.log = function () {};
-        console.error = function () {};
-        await submitTransactionAsync(zeroBalance, zeroToAlice);
-        delete console.log;
-        delete console.error;
+        await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
       };
       await expect(badTransaction()).to.be.rejectedWith("Inability to pay some fees");
       const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());
@@ -214,7 +210,7 @@
   });
 
   it('Fungible: Sponsoring is rate limited', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'Fungible');
+    const collectionId = await createCollectionExpectSuccess({mode: 'Fungible'});
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
@@ -233,11 +229,7 @@
       const AsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());
 
       const badTransaction = async function () { 
-        console.log = function () {};
-        console.error = function () {};
-        await submitTransactionAsync(zeroBalance, zeroToAlice);
-        delete console.log;
-        delete console.error;
+        await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
       };
 
       const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());
@@ -255,7 +247,7 @@
   });
 
   it('ReFungible: Sponsoring is rate limited', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'ReFungible');
+    const collectionId = await createCollectionExpectSuccess({mode: 'ReFungible'});
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
@@ -276,11 +268,7 @@
       const AsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());
       const zeroToAlice = api.tx.nft.transfer(alice.address, collectionId, itemId, 1);
       const badTransaction = async function () { 
-        console.log = function () {};
-        console.error = function () {};
-        await submitTransactionAsync(zeroBalance, zeroToAlice);
-        delete console.log;
-        delete console.error;
+        await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
       };
       await expect(badTransaction()).to.be.rejectedWith("Inability to pay some fees");
       const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());
@@ -320,7 +308,7 @@
   });
 
   it('(!negative test!) Confirm sponsorship using a non-sponsor address', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
 
     await usingApi(async (api) => {
@@ -332,18 +320,18 @@
   });
 
   it('(!negative test!) Confirm sponsorship using owner address', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectFailure(collectionId, '//Alice');
   });
 
   it('(!negative test!) Confirm sponsorship without sponsor being set with setCollectionSponsor', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await confirmSponsorshipExpectFailure(collectionId, '//Bob');
   });
     
   it('(!negative test!) Confirm sponsorship in a collection that was destroyed', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await destroyCollectionExpectSuccess(collectionId);
     await confirmSponsorshipExpectFailure(collectionId, '//Bob');
   });
modifiedtests/src/connection.test.tsdiffbeforeafterboth
--- a/tests/src/connection.test.ts
+++ b/tests/src/connection.test.ts
@@ -21,6 +21,8 @@
   });
 
   it('Cannot connect to 255.255.255.255', async () => {
+    const log = console.log;
+    const error = console.error;
     console.log = function () {};
     console.error = function () {};
 
@@ -31,7 +33,7 @@
       }, { provider: neverConnectProvider });
     })()).to.be.eventually.rejected;
 
-    delete console.log;
-    delete console.error;
+    console.log = log;
+    console.error = error;
   });
 });
\ No newline at end of file
modifiedtests/src/contracts.test.tsdiffbeforeafterboth
--- a/tests/src/contracts.test.ts
+++ b/tests/src/contracts.test.ts
@@ -111,9 +111,6 @@
       const bob = privateKey("//Bob");
 
       const [contract, deployer] = await deployFlipper(api);
-      const consoleError = console.error;
-      console.error = (...data: any[]) => {
-      };
 
       let expectedFlipValue = await getFlipValue(contract, deployer);
 
@@ -168,7 +165,6 @@
       const afterWhiteListDisabled = await getFlipValue(contract,deployer);
       expect(afterWhiteListDisabled).to.be.eq(expectedFlipValue, `Anyone can call contract with disabled whitelist.`);
 
-      console.error = consoleError;
     });
   });
 
modifiedtests/src/createCollection.test.tsdiffbeforeafterboth
--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -6,37 +6,29 @@
 import chai from 'chai';
 import chaiAsPromised from 'chai-as-promised';
 import { default as usingApi } from "./substrate/substrate-api";
-import { createCollectionExpectSuccess, createCollectionExpectFailure } from "./util/helpers";
+import { createCollectionExpectSuccess, createCollectionExpectFailure, CollectionMode } from "./util/helpers";
 
 chai.use(chaiAsPromised);
 const expect = chai.expect;
 
 describe('integration test: ext. createCollection():', () => {
   it('Create new NFT collection', async () => {
-    await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: 'NFT'});
   });
   it('Create new NFT collection whith collection_name of maximum length (64 bytes)', async () => {
-    await createCollectionExpectSuccess(
-      'ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCD',
-      '1', '1', 'NFT');
+    await createCollectionExpectSuccess({name: 'A'.repeat(64)});
   });
   it('Create new NFT collection whith collection_description of maximum length (256 bytes)', async () => {
-    await createCollectionExpectSuccess(
-      'A', 
-      'ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJabcdef',
-      '1', 'NFT');
+    await createCollectionExpectSuccess({description: 'A'.repeat(256)});
   });
   it('Create new NFT collection whith token_prefix of maximum length (16 bytes)', async () => {
-    await createCollectionExpectSuccess(
-      '1', 
-      '1',
-      'ABCDEFGHIJABCDEF', 'NFT');
+    await createCollectionExpectSuccess({tokenPrefix: 'A'.repeat(16)});
   });
   it('Create new Fungible collection', async () => {
-    await createCollectionExpectSuccess('1', '1', '1', 'Fungible');
+    await createCollectionExpectSuccess({mode: 'Fungible'});
   });
   it('Create new ReFungible collection', async () => {
-    await createCollectionExpectSuccess('1', '1', '1', 'ReFungible');
+    await createCollectionExpectSuccess({mode: 'ReFungible'});
   });
 });
 
@@ -46,7 +38,7 @@
       const AcollectionCount = parseInt((await api.query.nft.collectionCount()).toString());
 
       const badTransaction = async function () { 
-        await createCollectionExpectSuccess('1', '1', '1', 'BadMode');
+        await createCollectionExpectSuccess({mode: 'BadMode' as CollectionMode});
       };
       expect(badTransaction()).to.be.rejected;
 
@@ -55,18 +47,12 @@
     });
   });
   it('(!negative test!) create new NFT collection whith incorrect data (collection_name)', async () => {
-    await createCollectionExpectFailure(
-      'ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDE', 
-      '1', '1', 'NFT');
+    await createCollectionExpectFailure({name: 'A'.repeat(65)});
   });
   it('(!negative test!) create new NFT collection whith incorrect data (collection_description)', async () => {
-    await createCollectionExpectFailure('1',
-      'ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJabcdefg',
-      '1', 'NFT');
+    await createCollectionExpectFailure({description: 'A'.repeat(257)});
   });
   it('(!negative test!) create new NFT collection whith incorrect data (token_prefix)', async () => {
-    await createCollectionExpectFailure('1', '1', 
-    'ABCDEFGHIJABCDEFG',
-    'NFT');
+    await createCollectionExpectFailure({tokenPrefix: 'A'.repeat(17)});
   });
 });
modifiedtests/src/createItem.test.tsdiffbeforeafterboth
--- a/tests/src/createItem.test.ts
+++ b/tests/src/createItem.test.ts
@@ -18,17 +18,17 @@
 
   it('Create new item in NFT collection', async () => {
     const createMode = 'NFT';
-    const newCollectionID = await createCollectionExpectSuccess('0', '0', '0', createMode);
+    const newCollectionID = await createCollectionExpectSuccess({mode: createMode});
     await createItemExpectSuccess(alice, newCollectionID, createMode);
   });
   it('Create new item in Fungible collection', async () => {
     const createMode = 'Fungible';
-    const newCollectionID = await createCollectionExpectSuccess('0', '0', '0', createMode);
+    const newCollectionID = await createCollectionExpectSuccess({mode: createMode});
     await createItemExpectSuccess(alice, newCollectionID, createMode);
   });
   it('Create new item in ReFungible collection', async () => {
     const createMode = 'ReFungible';
-    const newCollectionID = await createCollectionExpectSuccess('0', '0', '0', createMode);
+    const newCollectionID = await createCollectionExpectSuccess({mode: createMode});
     await createItemExpectSuccess(alice, newCollectionID, createMode);
   });
 });
modifiedtests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth
--- a/tests/src/creditFeesToTreasury.test.ts
+++ b/tests/src/creditFeesToTreasury.test.ts
@@ -5,7 +5,7 @@
 
 import chai from 'chai';
 import chaiAsPromised from 'chai-as-promised';
-import { default as usingApi, submitTransactionAsync } from "./substrate/substrate-api";
+import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";
 import { alicesPublicKey, bobsPublicKey } from "./accounts";
 import privateKey from "./substrate/privateKey";
 import { BigNumber } from 'bignumber.js';
@@ -63,14 +63,13 @@
       const bobBalanceBefore = new BigNumber((await api.query.system.account(bobsPublicKey)).data.free.toString());
 
       const badTx = api.tx.balances.setBalance(alicesPublicKey, 0, 0);
-      const result = getGenericResult(await submitTransactionAsync(bobPrivateKey, badTx));
+      await expect(submitTransactionExpectFailAsync(bobPrivateKey, badTx)).to.be.rejected;
 
       const treasuryBalanceAfter = new BigNumber((await api.query.system.account(Treasury)).data.free.toString());
       const bobBalanceAfter = new BigNumber((await api.query.system.account(bobsPublicKey)).data.free.toString());
       const fee = bobBalanceBefore.minus(bobBalanceAfter);
       const treasuryIncrease = treasuryBalanceAfter.minus(treasuryBalanceBefore);
 
-      expect(result.success).to.be.false;
       expect(treasuryIncrease.toFixed()).to.be.equal(fee.toFixed());
     });
   });
@@ -80,7 +79,7 @@
       const treasuryBalanceBefore = new BigNumber((await api.query.system.account(Treasury)).data.free.toString());
       const aliceBalanceBefore = new BigNumber((await api.query.system.account(alicesPublicKey)).data.free.toString());
 
-      await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+      await createCollectionExpectSuccess();
 
       const treasuryBalanceAfter = new BigNumber((await api.query.system.account(Treasury)).data.free.toString());
       const aliceBalanceAfter = new BigNumber((await api.query.system.account(alicesPublicKey)).data.free.toString());
@@ -96,7 +95,7 @@
       const treasuryBalanceBefore = new BigNumber((await api.query.system.account(Treasury)).data.free.toString());
       const aliceBalanceBefore = new BigNumber((await api.query.system.account(alicesPublicKey)).data.free.toString());
 
-      await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+      await createCollectionExpectSuccess();
 
       const treasuryBalanceAfter = new BigNumber((await api.query.system.account(Treasury)).data.free.toString());
       const aliceBalanceAfter = new BigNumber((await api.query.system.account(alicesPublicKey)).data.free.toString());
modifiedtests/src/destroyCollection.test.tsdiffbeforeafterboth
--- a/tests/src/destroyCollection.test.ts
+++ b/tests/src/destroyCollection.test.ts
@@ -10,15 +10,15 @@
 
 describe('integration test: ext. destroyCollection():', () => {
   it('NFT collection can be destroyed', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await destroyCollectionExpectSuccess(collectionId);
   });
   it('Fungible collection can be destroyed', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'Fungible');
+    const collectionId = await createCollectionExpectSuccess({ mode: 'Fungible' });
     await destroyCollectionExpectSuccess(collectionId);
   });
   it('ReFungible collection can be destroyed', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'ReFungible');
+    const collectionId = await createCollectionExpectSuccess({ mode: 'ReFungible' });
     await destroyCollectionExpectSuccess(collectionId);
   });
 });
@@ -32,12 +32,12 @@
     });
   });
   it('(!negative test!) Destroy a collection that has already been destroyed', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await destroyCollectionExpectSuccess(collectionId);
     await destroyCollectionExpectFailure(collectionId);
   });
   it('(!negative test!) Destroy a collection using non-owner account', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await destroyCollectionExpectFailure(collectionId, '//Bob');
     await destroyCollectionExpectSuccess(collectionId, '//Alice');
   });
modifiedtests/src/removeCollectionSponsor.test.tsdiffbeforeafterboth
--- a/tests/src/removeCollectionSponsor.test.ts
+++ b/tests/src/removeCollectionSponsor.test.ts
@@ -5,7 +5,7 @@
 
 import chai from 'chai';
 import chaiAsPromised from 'chai-as-promised';
-import { default as usingApi, submitTransactionAsync } from "./substrate/substrate-api";
+import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";
 import { 
   createCollectionExpectSuccess, 
   setCollectionSponsorExpectSuccess, 
@@ -46,7 +46,7 @@
   });
 
   it('Remove NFT collection sponsor stops sponsorship', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
     await removeCollectionSponsorExpectSuccess(collectionId);
@@ -62,11 +62,7 @@
       const AsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());
       const zeroToAlice = api.tx.nft.transfer(alice.address, collectionId, itemId, 0);
       const badTransaction = async function () { 
-        console.log = function () {};
-        console.error = function () {};
-        await submitTransactionAsync(zeroBalance, zeroToAlice);
-        delete console.log;
-        delete console.error;
+        await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
       };
       await expect(badTransaction()).to.be.rejectedWith("Inability to pay some fees");
       const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());
@@ -76,7 +72,7 @@
   });
 
   it('Remove a sponsor after it was already removed', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
     await removeCollectionSponsorExpectSuccess(collectionId);
@@ -84,12 +80,12 @@
   });
 
   it('Remove sponsor in a collection that never had the sponsor set', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await removeCollectionSponsorExpectSuccess(collectionId);
   });
 
   it('Remove sponsor for a collection that had the sponsor set, but not confirmed', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await removeCollectionSponsorExpectSuccess(collectionId);
   });
@@ -117,21 +113,21 @@
   });
 
   it('(!negative test!) Remove sponsor in a destroyed collection', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await destroyCollectionExpectSuccess(collectionId);
     await removeCollectionSponsorExpectFailure(collectionId);
   });
 
   it('Set - remove - confirm: fails', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await removeCollectionSponsorExpectSuccess(collectionId);
     await confirmSponsorshipExpectFailure(collectionId, '//Bob');
   });
 
   it('Set - confirm - remove - confirm: Sponsor cannot come back', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
     await removeCollectionSponsorExpectSuccess(collectionId);
modifiedtests/src/setCollectionSponsor.test.tsdiffbeforeafterboth
--- a/tests/src/setCollectionSponsor.test.ts
+++ b/tests/src/setCollectionSponsor.test.ts
@@ -26,25 +26,25 @@
   });
 
   it('Set NFT collection sponsor', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
   });
   it('Set Fungible collection sponsor', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'Fungible');
+    const collectionId = await createCollectionExpectSuccess({ mode: 'Fungible' });
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
   });
   it('Set ReFungible collection sponsor', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'ReFungible');
+    const collectionId = await createCollectionExpectSuccess({ mode: 'ReFungible' });
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
   });
 
   it('Set the same sponsor repeatedly', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
   });
   it('Replace collection sponsor', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
 
     const keyring = new Keyring({ type: 'sr25519' });
     const charlie = keyring.addFromUri(`//Charlie`);
@@ -62,7 +62,7 @@
   });
 
   it('(!negative test!) Add sponsor with a non-owner', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectFailure(collectionId, bob.address, '//Bob');
   });
   it('(!negative test!) Add sponsor to a collection that never existed', async () => {
@@ -75,7 +75,7 @@
     await setCollectionSponsorExpectFailure(collectionId, bob.address);
   });
   it('(!negative test!) Add sponsor to a collection that was destroyed', async () => {
-    const collectionId = await createCollectionExpectSuccess('A', 'B', 'C', 'NFT');
+    const collectionId = await createCollectionExpectSuccess();
     await destroyCollectionExpectSuccess(collectionId);
     await setCollectionSponsorExpectFailure(collectionId, bob.address);
   });
modifiedtests/src/substrate/substrate-api.tsdiffbeforeafterboth
--- a/tests/src/substrate/substrate-api.ts
+++ b/tests/src/substrate/substrate-api.ts
@@ -33,21 +33,42 @@
   }
 }
 
+enum TransactionStatus {
+  Success,
+  Fail,
+  NotReady
+}
+
+function getTransactionStatus(events: EventRecord[], status: ExtrinsicStatus): TransactionStatus {
+  if (status.isReady) {
+    return TransactionStatus.NotReady;
+  }
+  if (status.isBroadcast) {
+    return TransactionStatus.NotReady;
+  } 
+  if (status.isInBlock || status.isFinalized) {
+    if(events.filter(e => e.event.data.method === 'ExtrinsicFailed').length > 0) {
+      return TransactionStatus.Fail;
+    }
+    if(events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {
+      return TransactionStatus.Success;
+    }
+  }
+
+  return TransactionStatus.Fail;
+}
+
 export function submitTransactionAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {
   return new Promise(async function(resolve, reject) {
     try {
       await transaction.signAndSend(sender, ({ events = [], status }) => {
-        if (status.isReady) {
-          // nothing to do
-          // console.log(`Current tx status is Ready`);
-        } else if (status.isBroadcast) {
-          // nothing to do
-          // console.log(`Current tx status is Broadcast`);
-        } else if (status.isInBlock || status.isFinalized) {
+        const transactionStatus = getTransactionStatus(events, status);
+
+        if (transactionStatus == TransactionStatus.Success) {
           resolve(events);
-        } else {
+        } else if (transactionStatus == TransactionStatus.Fail) {
           console.log(`Something went wrong with transaction. Status: ${status}`);
-          reject("Transaction failed");
+          reject(events);
         }
       });
     } catch (e) {
@@ -58,19 +79,35 @@
 }
 
 export function submitTransactionExpectFailAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {
-  return new Promise(async function(resolve, reject) {
+  const consoleError = console.error;
+  const consoleLog = console.log;
+  console.error = () => {};
+  console.log = () => {};
+
+  return new Promise<EventRecord[]>(async function(res, rej) {
+    const resolve = (rec: EventRecord[]) => {
+      setTimeout(() => {
+        res(rec);
+        console.error = consoleError;
+        console.log = consoleLog;
+        
+      });
+    };
+    const reject = (errror: any) => {
+      setTimeout(() => {
+        rej(errror);
+        console.error = consoleError;
+        console.log = consoleLog;
+      });
+    };
     try {
       await transaction.signAndSend(sender, ({ events = [], status }) => {
-        if (status.isReady) {
-          // nothing to do
-          // console.log(`Current tx status is Ready`);
-        } else if (status.isBroadcast) {
-          // nothing to do
-          // console.log(`Current tx status is Broadcast`);
-        } else if (status.isInBlock || status.isFinalized) {
+        const transactionStatus = getTransactionStatus(events, status);
+
+        if (transactionStatus == TransactionStatus.Success) {
           resolve(events);
-        } else {
-          reject("Transaction failed");
+        } else if (transactionStatus == TransactionStatus.Fail) {
+          reject(events);
         }
       });
     } catch (e) {
modifiedtests/src/transfer.test.tsdiffbeforeafterboth
--- a/tests/src/transfer.test.ts
+++ b/tests/src/transfer.test.ts
@@ -33,6 +33,8 @@
       // Find unused address
       const pk = await findUnusedAddress(api);
 
+      const error = console.error;
+      const log = console.log;
       console.log = function () {};
       console.error = function () {};
   
@@ -42,8 +44,8 @@
       };
       await expect(badTransaction()).to.be.rejectedWith("Inability to pay some fees");
 
-      delete console.log;
-      delete console.error;
+      console.log = log;
+      console.error = error;
     });
   });
 });
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 chai from 'chai';7import chaiAsPromised from 'chai-as-promised';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { ApiPromise, Keyring } from "@polkadot/api";10import { default as usingApi, submitTransactionAsync } from "../substrate/substrate-api";11import privateKey from '../substrate/privateKey';12import { alicesPublicKey, nullPublicKey } from "../accounts";13import { strToUTF16, utf16ToStr, hexToStr } from '../util/util';14import { IKeyringPair } from "@polkadot/types/types";15import { BigNumber } from 'bignumber.js';16import { Struct, Enum } from '@polkadot/types/codec';17import { u128 } from '@polkadot/types/primitive';1819chai.use(chaiAsPromised);20const expect = chai.expect;2122type GenericResult = {23  success: boolean,24};2526type CreateCollectionResult = {27  success: boolean,28  collectionId: number29};3031type CreateItemResult = {32  success: boolean,33  collectionId: number,34  itemId: number35};3637export function getGenericResult(events: EventRecord[]): GenericResult {38  let result: GenericResult = {39    success: false40  }41  events.forEach(({ phase, event: { data, method, section } }) => {42    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);43    if (method == 'ExtrinsicSuccess') {44      result.success = true;45    }46  });47  return result;48}4950function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {51  let success = false;52  let collectionId: number = 0;53  events.forEach(({ phase, event: { data, method, section } }) => {54    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);55    if (method == 'ExtrinsicSuccess') {56      success = true;57    } else if ((section == 'nft') && (method == 'Created')) {58      collectionId = parseInt(data[0].toString());59    }60  });61  let result: CreateCollectionResult = {62    success,63    collectionId64  }65  return result;66}6768function getCreateItemResult(events: EventRecord[]): CreateItemResult {69  let success = false;70  let collectionId: number = 0;71  let itemId: number = 0;72  events.forEach(({ phase, event: { data, method, section } }) => {73    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);74    if (method == 'ExtrinsicSuccess') {75      success = true;76    } else if ((section == 'nft') && (method == 'ItemCreated')) {77      collectionId = parseInt(data[0].toString());78      itemId = parseInt(data[1].toString());79    }80  });81  let result: CreateItemResult = {82    success,83    collectionId,84    itemId85  }86  return result;87}8889export async function createCollectionExpectSuccess(name: string, description: string, tokenPrefix: string, mode: string): Promise<number> {90  let collectionId: number = 0;91  await usingApi(async (api) => {92    // Get number of collections before the transaction93    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());9495    // Run the CreateCollection transaction96    const alicePrivateKey = privateKey('//Alice');97    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), mode);98    const events = await submitTransactionAsync(alicePrivateKey, tx);99    const result = getCreateCollectionResult(events);100101    // Get number of collections after the transaction102    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());103104    // Get the collection 105    const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();106107    // What to expect108    expect(result.success).to.be.true;109    expect(result.collectionId).to.be.equal(BcollectionCount);110    expect(collection).to.be.not.null;111    expect(BcollectionCount).to.be.equal(AcollectionCount+1, 'Error: NFT collection NOT created.');112    expect(collection.Owner).to.be.equal(alicesPublicKey);113    expect(utf16ToStr(collection.Name)).to.be.equal(name);114    expect(utf16ToStr(collection.Description)).to.be.equal(description);115    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);116117    collectionId = result.collectionId;118  });119120  return collectionId;121}122  123export async function createCollectionExpectFailure(name: string, description: string, tokenPrefix: string, mode: string) {124  await usingApi(async (api) => {125    // Get number of collections before the transaction126    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());127128    // Run the CreateCollection transaction129    const alicePrivateKey = privateKey('//Alice');130    const tx = api.tx.nft.createCollection(name, description, tokenPrefix, mode);131    const events = await submitTransactionAsync(alicePrivateKey, tx);132    const result = getCreateCollectionResult(events);133134    // Get number of collections after the transaction135    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());136137    // What to expect138    expect(result.success).to.be.false;139    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');140  });141}142  143export async function findUnusedAddress(api: ApiPromise): Promise<IKeyringPair> {144  let bal = new BigNumber(0);145  let unused;146  do {147    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000));148    const keyring = new Keyring({ type: 'sr25519' });149    unused = keyring.addFromUri(`//${randomSeed}`);150    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());151  } while (bal.toFixed() != '0');152  return unused; 153}154155function getDestroyResult(events: EventRecord[]): boolean {156  let success: boolean = false;157  events.forEach(({ phase, event: { data, method, section } }) => {158    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);159    if (method == 'ExtrinsicSuccess') {160      success = true;161    }162  });163  return success;164}165166export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {167  await usingApi(async (api) => {168    // Run the DestroyCollection transaction169    const alicePrivateKey = privateKey(senderSeed);170    const tx = api.tx.nft.destroyCollection(collectionId);171    const events = await submitTransactionAsync(alicePrivateKey, tx);172    const result = getDestroyResult(events);173174    // What to expect175    expect(result).to.be.false;176  });177}178179export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {180  await usingApi(async (api) => {181    // Run the DestroyCollection transaction182    const alicePrivateKey = privateKey(senderSeed);183    const tx = api.tx.nft.destroyCollection(collectionId);184    const events = await submitTransactionAsync(alicePrivateKey, tx);185    const result = getDestroyResult(events);186187    // Get the collection 188    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();189190    // What to expect191    expect(result).to.be.true;192    expect(collection).to.be.not.null;193    expect(collection.Owner).to.be.equal(nullPublicKey);194  });195}196197export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {198  await usingApi(async (api) => {199200    // Run the transaction201    const alicePrivateKey = privateKey('//Alice');202    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);203    const events = await submitTransactionAsync(alicePrivateKey, tx);204    const result = getGenericResult(events);205206    // Get the collection 207    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();208209    // What to expect210    expect(result.success).to.be.true;211    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());212    expect(collection.SponsorConfirmed).to.be.false;213  });214}215216export async function removeCollectionSponsorExpectSuccess(collectionId: number) {217  await usingApi(async (api) => {218219    // Run the transaction220    const alicePrivateKey = privateKey('//Alice');221    const tx = api.tx.nft.removeCollectionSponsor(collectionId);222    const events = await submitTransactionAsync(alicePrivateKey, tx);223    const result = getGenericResult(events);224225    // Get the collection 226    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();227228    // What to expect229    expect(result.success).to.be.true;230    expect(collection.Sponsor).to.be.equal(nullPublicKey);231    expect(collection.SponsorConfirmed).to.be.false;232  });233}234235export async function removeCollectionSponsorExpectFailure(collectionId: number) {236  await usingApi(async (api) => {237238    // Run the transaction239    const alicePrivateKey = privateKey('//Alice');240    const tx = api.tx.nft.removeCollectionSponsor(collectionId);241    const events = await submitTransactionAsync(alicePrivateKey, tx);242    const result = getGenericResult(events);243244    // What to expect245    expect(result.success).to.be.false;246  });247}248249export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {250  await usingApi(async (api) => {251252    // Run the transaction253    const alicePrivateKey = privateKey(senderSeed);254    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);255    const events = await submitTransactionAsync(alicePrivateKey, tx);256    const result = getGenericResult(events);257258    // What to expect259    expect(result.success).to.be.false;260  });261}262263export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {264  await usingApi(async (api) => {265266    // Run the transaction267    const sender = privateKey(senderSeed);268    const tx = api.tx.nft.confirmSponsorship(collectionId);269    const events = await submitTransactionAsync(sender, tx);270    const result = getGenericResult(events);271272    // Get the collection 273    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();274275    // What to expect276    expect(result.success).to.be.true;277    expect(collection.Sponsor).to.be.equal(sender.address);278    expect(collection.SponsorConfirmed).to.be.true;279  });280}281282export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {283  await usingApi(async (api) => {284285    // Run the transaction286    const sender = privateKey(senderSeed);287    const tx = api.tx.nft.confirmSponsorship(collectionId);288    const events = await submitTransactionAsync(sender, tx);289    const result = getGenericResult(events);290291    // What to expect292    expect(result.success).to.be.false;293  });294}295296export interface CreateFungibleData extends Struct {297  readonly value: u128;298};299300export interface CreateReFungibleData extends Struct {};301export interface CreateNftData extends Struct {};302303export interface CreateItemData extends Enum {304  NFT: CreateNftData,305  Fungible: CreateFungibleData,306  ReFungible: CreateReFungibleData307};308309export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {310  let newItemId: number = 0;311  await usingApi(async (api) => {312    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString());313    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();    314    const AItemBalance = new BigNumber(Aitem.Value);315316    if (owner === '') owner = sender.address;317318    let tx;319    if (createMode == 'Fungible') {320      let createData = {fungible: {value: 10}};321      tx = api.tx.nft.createItem(collectionId, owner, createData);322    }323    else {324      tx = api.tx.nft.createItem(collectionId, owner, createMode);325    }326    const events = await submitTransactionAsync(sender, tx);327    const result = getCreateItemResult(events);328329    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString());330    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();    331    const BItemBalance = new BigNumber(Bitem.Value);332333    // What to expect334    expect(result.success).to.be.true;335    if (createMode == 'Fungible') {336      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);337    }338    else {339      expect(BItemCount).to.be.equal(AItemCount+1);340    }341    expect(collectionId).to.be.equal(result.collectionId);342    expect(BItemCount).to.be.equal(result.itemId);343    newItemId = result.itemId;344  });345  return newItemId;346}347348export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {349  await usingApi(async (api) => {350351    // Run the transaction352    const tx = api.tx.nft.setPublicAccessMode(collectionId, 'WhiteList');353    const events = await submitTransactionAsync(sender, tx);354    const result = getGenericResult(events);355356    // Get the collection 357    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();358359    // What to expect360    expect(result.success).to.be.true;361    expect(collection.Access).to.be.equal('WhiteList');362  });363}364365export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {366  await usingApi(async (api) => {367368    // Run the transaction369    const tx = api.tx.nft.setMintPermission(collectionId, true);370    const events = await submitTransactionAsync(sender, tx);371    const result = getGenericResult(events);372373    // Get the collection 374    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();375376    // What to expect377    expect(result.success).to.be.true;378    expect(collection.MintMode).to.be.equal(true);379  });380}381382export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {383  await usingApi(async (api) => {384385    // Run the transaction386    const tx = api.tx.nft.addToWhiteList(collectionId, address);387    const events = await submitTransactionAsync(sender, tx);388    const result = getGenericResult(events);389390    // Get the collection 391    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();392393    // What to expect394    expect(result.success).to.be.true;395    expect(collection.MintMode).to.be.equal(true);396  });397}398
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 chai from 'chai';7import chaiAsPromised from 'chai-as-promised';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { ApiPromise, Keyring } from "@polkadot/api";10import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from "../substrate/substrate-api";11import privateKey from '../substrate/privateKey';12import { alicesPublicKey, nullPublicKey } from "../accounts";13import { strToUTF16, utf16ToStr, hexToStr } from '../util/util';14import { IKeyringPair } from "@polkadot/types/types";15import { BigNumber } from 'bignumber.js';16import { Struct, Enum } from '@polkadot/types/codec';17import { u128 } from '@polkadot/types/primitive';1819chai.use(chaiAsPromised);20const expect = chai.expect;2122type GenericResult = {23  success: boolean,24};2526type CreateCollectionResult = {27  success: boolean,28  collectionId: number29};3031type CreateItemResult = {32  success: boolean,33  collectionId: number,34  itemId: number35};3637export function getGenericResult(events: EventRecord[]): GenericResult {38  let result: GenericResult = {39    success: false40  }41  events.forEach(({ phase, event: { data, method, section } }) => {42    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);43    if (method == 'ExtrinsicSuccess') {44      result.success = true;45    }46  });47  return result;48}4950function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {51  let success = false;52  let collectionId: number = 0;53  events.forEach(({ phase, event: { data, method, section } }) => {54    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);55    if (method == 'ExtrinsicSuccess') {56      success = true;57    } else if ((section == 'nft') && (method == 'Created')) {58      collectionId = parseInt(data[0].toString());59    }60  });61  let result: CreateCollectionResult = {62    success,63    collectionId64  }65  return result;66}6768function getCreateItemResult(events: EventRecord[]): CreateItemResult {69  let success = false;70  let collectionId: number = 0;71  let itemId: number = 0;72  events.forEach(({ phase, event: { data, method, section } }) => {73    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);74    if (method == 'ExtrinsicSuccess') {75      success = true;76    } else if ((section == 'nft') && (method == 'ItemCreated')) {77      collectionId = parseInt(data[0].toString());78      itemId = parseInt(data[1].toString());79    }80  });81  let result: CreateItemResult = {82    success,83    collectionId,84    itemId85  }86  return result;87}8889export type CollectionMode = 'NFT' | 'Fungible' | 'ReFungible';90export type CreateCollectionParams = {91  mode: CollectionMode,92  name: string,93  description: string,94  tokenPrefix: string95};9697const defaultCreateCollectionParams: CreateCollectionParams = {98  name: 'name',99  description: 'description',100  mode: 'NFT',101  tokenPrefix: 'prefix'102}103104export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {105  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};106107  let collectionId: number = 0;108  await usingApi(async (api) => {109    // Get number of collections before the transaction110    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());111112    // Run the CreateCollection transaction113    const alicePrivateKey = privateKey('//Alice');114    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), mode);115    const events = await submitTransactionAsync(alicePrivateKey, tx);116    const result = getCreateCollectionResult(events);117118    // Get number of collections after the transaction119    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());120121    // Get the collection 122    const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();123124    // What to expect125    expect(result.success).to.be.true;126    expect(result.collectionId).to.be.equal(BcollectionCount);127    expect(collection).to.be.not.null;128    expect(BcollectionCount).to.be.equal(AcollectionCount+1, 'Error: NFT collection NOT created.');129    expect(collection.Owner).to.be.equal(alicesPublicKey);130    expect(utf16ToStr(collection.Name)).to.be.equal(name);131    expect(utf16ToStr(collection.Description)).to.be.equal(description);132    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);133134    collectionId = result.collectionId;135  });136137  return collectionId;138}139  140export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {141  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};142143  await usingApi(async (api) => {144    // Get number of collections before the transaction145    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());146147    // Run the CreateCollection transaction148    const alicePrivateKey = privateKey('//Alice');149    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), mode);150    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;151    const result = getCreateCollectionResult(events);152153    // Get number of collections after the transaction154    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());155156    // What to expect157    expect(result.success).to.be.false;158    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');159  });160}161  162export async function findUnusedAddress(api: ApiPromise): Promise<IKeyringPair> {163  let bal = new BigNumber(0);164  let unused;165  do {166    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000));167    const keyring = new Keyring({ type: 'sr25519' });168    unused = keyring.addFromUri(`//${randomSeed}`);169    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());170  } while (bal.toFixed() != '0');171  return unused; 172}173174function getDestroyResult(events: EventRecord[]): boolean {175  let success: boolean = false;176  events.forEach(({ phase, event: { data, method, section } }) => {177    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);178    if (method == 'ExtrinsicSuccess') {179      success = true;180    }181  });182  return success;183}184185export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {186  await usingApi(async (api) => {187    // Run the DestroyCollection transaction188    const alicePrivateKey = privateKey(senderSeed);189    const tx = api.tx.nft.destroyCollection(collectionId);190    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;191  });192}193194export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {195  await usingApi(async (api) => {196    // Run the DestroyCollection transaction197    const alicePrivateKey = privateKey(senderSeed);198    const tx = api.tx.nft.destroyCollection(collectionId);199    const events = await submitTransactionAsync(alicePrivateKey, tx);200    const result = getDestroyResult(events);201202    // Get the collection 203    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();204205    // What to expect206    expect(result).to.be.true;207    expect(collection).to.be.not.null;208    expect(collection.Owner).to.be.equal(nullPublicKey);209  });210}211212export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {213  await usingApi(async (api) => {214215    // Run the transaction216    const alicePrivateKey = privateKey('//Alice');217    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);218    const events = await submitTransactionAsync(alicePrivateKey, tx);219    const result = getGenericResult(events);220221    // Get the collection 222    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();223224    // What to expect225    expect(result.success).to.be.true;226    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());227    expect(collection.SponsorConfirmed).to.be.false;228  });229}230231export async function removeCollectionSponsorExpectSuccess(collectionId: number) {232  await usingApi(async (api) => {233234    // Run the transaction235    const alicePrivateKey = privateKey('//Alice');236    const tx = api.tx.nft.removeCollectionSponsor(collectionId);237    const events = await submitTransactionAsync(alicePrivateKey, tx);238    const result = getGenericResult(events);239240    // Get the collection 241    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();242243    // What to expect244    expect(result.success).to.be.true;245    expect(collection.Sponsor).to.be.equal(nullPublicKey);246    expect(collection.SponsorConfirmed).to.be.false;247  });248}249250export async function removeCollectionSponsorExpectFailure(collectionId: number) {251  await usingApi(async (api) => {252253    // Run the transaction254    const alicePrivateKey = privateKey('//Alice');255    const tx = api.tx.nft.removeCollectionSponsor(collectionId);256    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;257  });258}259260export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {261  await usingApi(async (api) => {262263    // Run the transaction264    const alicePrivateKey = privateKey(senderSeed);265    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);266    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;267  });268}269270export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {271  await usingApi(async (api) => {272273    // Run the transaction274    const sender = privateKey(senderSeed);275    const tx = api.tx.nft.confirmSponsorship(collectionId);276    const events = await submitTransactionAsync(sender, tx);277    const result = getGenericResult(events);278279    // Get the collection 280    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();281282    // What to expect283    expect(result.success).to.be.true;284    expect(collection.Sponsor).to.be.equal(sender.address);285    expect(collection.SponsorConfirmed).to.be.true;286  });287}288289export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {290  await usingApi(async (api) => {291292    // Run the transaction293    const sender = privateKey(senderSeed);294    const tx = api.tx.nft.confirmSponsorship(collectionId);295    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;296  });297}298299export interface CreateFungibleData extends Struct {300  readonly value: u128;301};302303export interface CreateReFungibleData extends Struct {};304export interface CreateNftData extends Struct {};305306export interface CreateItemData extends Enum {307  NFT: CreateNftData,308  Fungible: CreateFungibleData,309  ReFungible: CreateReFungibleData310};311312export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {313  let newItemId: number = 0;314  await usingApi(async (api) => {315    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString());316    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();    317    const AItemBalance = new BigNumber(Aitem.Value);318319    if (owner === '') owner = sender.address;320321    let tx;322    if (createMode == 'Fungible') {323      let createData = {fungible: {value: 10}};324      tx = api.tx.nft.createItem(collectionId, owner, createData);325    }326    else {327      tx = api.tx.nft.createItem(collectionId, owner, createMode);328    }329    const events = await submitTransactionAsync(sender, tx);330    const result = getCreateItemResult(events);331332    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString());333    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();    334    const BItemBalance = new BigNumber(Bitem.Value);335336    // What to expect337    expect(result.success).to.be.true;338    if (createMode == 'Fungible') {339      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);340    }341    else {342      expect(BItemCount).to.be.equal(AItemCount+1);343    }344    expect(collectionId).to.be.equal(result.collectionId);345    expect(BItemCount).to.be.equal(result.itemId);346    newItemId = result.itemId;347  });348  return newItemId;349}350351export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {352  await usingApi(async (api) => {353354    // Run the transaction355    const tx = api.tx.nft.setPublicAccessMode(collectionId, 'WhiteList');356    const events = await submitTransactionAsync(sender, tx);357    const result = getGenericResult(events);358359    // Get the collection 360    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();361362    // What to expect363    expect(result.success).to.be.true;364    expect(collection.Access).to.be.equal('WhiteList');365  });366}367368export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {369  await usingApi(async (api) => {370371    // Run the transaction372    const tx = api.tx.nft.setMintPermission(collectionId, true);373    const events = await submitTransactionAsync(sender, tx);374    const result = getGenericResult(events);375376    // Get the collection 377    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();378379    // What to expect380    expect(result.success).to.be.true;381    expect(collection.MintMode).to.be.equal(true);382  });383}384385export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {386  await usingApi(async (api) => {387388    // Run the transaction389    const tx = api.tx.nft.addToWhiteList(collectionId, address);390    const events = await submitTransactionAsync(sender, tx);391    const result = getGenericResult(events);392393    // Get the collection 394    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();395396    // What to expect397    expect(result.success).to.be.true;398    expect(collection.MintMode).to.be.equal(true);399  });400}401