git.delta.rocks / unique-network / refs/commits / 147c8928fe2f

difftreelog

Merge pull request #61 from usetech-llc/feature/NFTPAR-236_burn_item

str-mv2021-01-14parents: #aa3aa05 #c356c0a.patch.diff
in: master
Feature/nftpar 236 burn item

9 files changed

addedtests/src/burnItem.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/burnItem.test.ts
@@ -0,0 +1,237 @@
+import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';
+import { Keyring } from "@polkadot/api";
+import { IKeyringPair } from "@polkadot/types/types";
+import { 
+  createCollectionExpectSuccess, 
+  createItemExpectSuccess,
+  getGenericResult,
+  destroyCollectionExpectSuccess
+} from './util/helpers';
+import { nullPublicKey } from "./accounts";
+
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+let alice: IKeyringPair;
+let bob: IKeyringPair;
+
+describe('integration test: ext. burnItem():', () => {
+  before(async () => {
+    await usingApi(async (api) => {
+      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 usingApi(async (api) => {
+      const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);
+      const events = await submitTransactionAsync(alice, tx);
+      const result = getGenericResult(events);
+  
+      // Get the item 
+      const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();
+ 
+      // What to expect
+      expect(result.success).to.be.true;
+      expect(item).to.be.not.null;
+      expect(item.Owner).to.be.equal(nullPublicKey);
+    });
+  
+  });
+  it('Burn item in Fungible collection', async () => {
+    const createMode = 'Fungible';
+    const collectionId = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0 }});
+    await createItemExpectSuccess(alice, collectionId, createMode); // Helper creates 10 fungible tokens
+    const tokenId = 0; // ignored
+
+    await usingApi(async (api) => {
+      // Destroy 1 of 10
+      const tx = api.tx.nft.burnItem(collectionId, tokenId, 1);
+      const events = await submitTransactionAsync(alice, tx);
+      const result = getGenericResult(events);
+  
+      // Get alice balance 
+      const balance: any = (await api.query.nft.fungibleItemList(collectionId, alice.address)).toJSON();
+ 
+      // What to expect
+      expect(result.success).to.be.true;
+      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, decimalPoints: 2 }});
+    const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);
+
+    await usingApi(async (api) => {
+      const tx = api.tx.nft.burnItem(collectionId, tokenId, 1);
+      const events = await submitTransactionAsync(alice, tx);
+      const result = getGenericResult(events);
+  
+      // Get alice balance 
+      const balance: any = (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON();
+      
+      // What to expect
+      expect(result.success).to.be.true;
+      expect(balance).to.be.not.null;
+      expect(balance.Owner.length).to.be.equal(0);
+    });
+
+  });
+
+  it('Burn owned portion of item in ReFungible collection', async () => {
+    const createMode = 'ReFungible';
+    const collectionId = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 2 }});
+    const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);
+
+    await usingApi(async (api) => {
+      // Transfer 1/100 of the token to Bob
+      const transfertx = api.tx.nft.transfer(bob.address, collectionId, tokenId, 1);
+      const events1 = await submitTransactionAsync(alice, transfertx);
+      const result1 = getGenericResult(events1);
+
+      // Get balances
+      const balanceBefore: any = (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON();
+
+      // Bob burns his portion
+      const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);
+      const events2 = await submitTransactionAsync(bob, tx);
+      const result2 = getGenericResult(events2);
+  
+      // Get balances 
+      const balance: any = (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON();
+      // console.log(balance);
+      
+      // What to expect before burning
+      expect(result1.success).to.be.true;
+      expect(balanceBefore).to.be.not.null;
+      expect(balanceBefore.Owner.length).to.be.equal(2);
+      expect(balanceBefore.Owner[0].Owner).to.be.equal(alice.address);
+      expect(balanceBefore.Owner[0].Fraction).to.be.equal(99);
+      expect(balanceBefore.Owner[1].Owner).to.be.equal(bob.address);
+      expect(balanceBefore.Owner[1].Fraction).to.be.equal(1);
+
+      // What to expect after burning
+      expect(result2.success).to.be.true;
+      expect(balance).to.be.not.null;
+      expect(balance.Owner.length).to.be.equal(1);
+      expect(balance.Owner[0].Fraction).to.be.equal(99);
+      expect(balance.Owner[0].Owner).to.be.equal(alice.address);
+    });
+
+  });
+
+});
+
+describe('Negative integration test: ext. burnItem():', () => {
+  before(async () => {
+    await usingApi(async (api) => {
+      const keyring = new Keyring({ type: 'sr25519' });
+      alice = keyring.addFromUri(`//Alice`);
+      bob = keyring.addFromUri(`//Bob`);
+    });
+  });
+
+  it('Burn a token in a destroyed collection', async () => {
+    const createMode = 'NFT';
+    const collectionId = await createCollectionExpectSuccess({mode: {type: createMode }});
+    const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);
+    await destroyCollectionExpectSuccess(collectionId);
+
+    await usingApi(async (api) => {
+      const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);
+      const badTransaction = async function () { 
+        await submitTransactionExpectFailAsync(alice, tx);
+      };
+      await expect(badTransaction()).to.be.rejected;
+    });
+
+  });
+
+  it('Burn a token that was never created', async () => {
+    const createMode = 'NFT';
+    const collectionId = await createCollectionExpectSuccess({mode: {type: createMode }});
+    const tokenId = 10;
+
+    await usingApi(async (api) => {
+      const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);
+      const badTransaction = async function () { 
+        await submitTransactionExpectFailAsync(alice, tx);
+      };
+      await expect(badTransaction()).to.be.rejected;
+    });
+
+  });
+
+  it('Burn a token using the address that does not own it', async () => {
+    const createMode = 'NFT';
+    const collectionId = await createCollectionExpectSuccess({mode: {type: createMode }});
+    const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);
+
+    await usingApi(async (api) => {
+      const tx = api.tx.nft.burnItem(collectionId, tokenId, 0);
+      const badTransaction = async function () { 
+        await submitTransactionExpectFailAsync(bob, tx);
+      };
+      await expect(badTransaction()).to.be.rejected;
+    });
+
+  });
+
+  it('Transfer a burned a token', async () => {
+    const createMode = 'NFT';
+    const collectionId = await createCollectionExpectSuccess({mode: {type: createMode }});
+    const tokenId = await createItemExpectSuccess(alice, collectionId, createMode);
+
+    await usingApi(async (api) => {
+
+      const burntx = api.tx.nft.burnItem(collectionId, tokenId, 0);
+      const events1 = await submitTransactionAsync(alice, burntx);
+      const result1 = getGenericResult(events1);
+      expect(result1.success).to.be.true;
+  
+      const tx = api.tx.nft.transfer(bob.address, collectionId, tokenId, 0);
+      const badTransaction = async function () { 
+        await submitTransactionExpectFailAsync(alice, tx);
+      };
+      await expect(badTransaction()).to.be.rejected;
+    });
+
+  });
+
+  it('Burn more than owned in Fungible collection', async () => {
+    const createMode = 'Fungible';
+    const collectionId = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0 }});
+    // Helper creates 10 fungible tokens
+    await createItemExpectSuccess(alice, collectionId, createMode);
+    const tokenId = 0; // ignored
+
+    await usingApi(async (api) => {
+      // Destroy 11 of 10
+      const tx = api.tx.nft.burnItem(collectionId, tokenId, 11);
+      const badTransaction = async function () { 
+        await submitTransactionExpectFailAsync(alice, tx);
+      };
+      await expect(badTransaction()).to.be.rejected;
+      
+      // Get alice balance 
+      const balance: any = (await api.query.nft.fungibleItemList(collectionId, alice.address)).toJSON();
+ 
+      // What to expect
+      expect(balance).to.be.not.null;
+      expect(balance.Value).to.be.equal(10);
+    });
+
+  });
+
+});
modifiedtests/src/confirmSponsorship.test.tsdiffbeforeafterboth
--- a/tests/src/confirmSponsorship.test.ts
+++ b/tests/src/confirmSponsorship.test.ts
@@ -89,7 +89,7 @@
   });
 
   it('Fungible: Transfer fees are paid by the sponsor after confirmation', async () => {
-    const collectionId = await createCollectionExpectSuccess({mode: 'Fungible'});
+    const collectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0 }});
     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({mode: 'ReFungible'});
+    const collectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible', decimalPoints: 0 }});
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
@@ -210,7 +210,7 @@
   });
 
   it('Fungible: Sponsoring is rate limited', async () => {
-    const collectionId = await createCollectionExpectSuccess({mode: 'Fungible'});
+    const collectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0 }});
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
@@ -247,7 +247,7 @@
   });
 
   it('ReFungible: Sponsoring is rate limited', async () => {
-    const collectionId = await createCollectionExpectSuccess({mode: 'ReFungible'});
+    const collectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible', decimalPoints: 0 }});
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
modifiedtests/src/createCollection.test.tsdiffbeforeafterboth
--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -6,14 +6,14 @@
 import chai from 'chai';
 import chaiAsPromised from 'chai-as-promised';
 import { default as usingApi } from "./substrate/substrate-api";
-import { createCollectionExpectSuccess, createCollectionExpectFailure, CollectionMode } from "./util/helpers";
+import { createCollectionExpectSuccess, createCollectionExpectFailure } from "./util/helpers";
 
 chai.use(chaiAsPromised);
 const expect = chai.expect;
 
 describe('integration test: ext. createCollection():', () => {
   it('Create new NFT collection', async () => {
-    await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: 'NFT'});
+    await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
   });
   it('Create new NFT collection whith collection_name of maximum length (64 bytes)', async () => {
     await createCollectionExpectSuccess({name: 'A'.repeat(64)});
@@ -25,10 +25,10 @@
     await createCollectionExpectSuccess({tokenPrefix: 'A'.repeat(16)});
   });
   it('Create new Fungible collection', async () => {
-    await createCollectionExpectSuccess({mode: 'Fungible'});
+    await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
   });
   it('Create new ReFungible collection', async () => {
-    await createCollectionExpectSuccess({mode: 'ReFungible'});
+    await createCollectionExpectSuccess({mode: {type: 'ReFungible', decimalPoints: 0}});
   });
 });
 
@@ -38,7 +38,7 @@
       const AcollectionCount = parseInt((await api.query.nft.collectionCount()).toString());
 
       const badTransaction = async function () { 
-        await createCollectionExpectSuccess({mode: 'BadMode' as CollectionMode});
+        await createCollectionExpectSuccess({mode: {type: 'Invalid'}});
       };
       expect(badTransaction()).to.be.rejected;
 
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({mode: createMode});
+    const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode}});
     await createItemExpectSuccess(alice, newCollectionID, createMode);
   });
   it('Create new item in Fungible collection', async () => {
     const createMode = 'Fungible';
-    const newCollectionID = await createCollectionExpectSuccess({mode: createMode});
+    const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0}});
     await createItemExpectSuccess(alice, newCollectionID, createMode);
   });
   it('Create new item in ReFungible collection', async () => {
     const createMode = 'ReFungible';
-    const newCollectionID = await createCollectionExpectSuccess({mode: createMode});
+    const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0}});
     await createItemExpectSuccess(alice, newCollectionID, createMode);
   });
 });
modifiedtests/src/destroyCollection.test.tsdiffbeforeafterboth
--- a/tests/src/destroyCollection.test.ts
+++ b/tests/src/destroyCollection.test.ts
@@ -14,11 +14,11 @@
     await destroyCollectionExpectSuccess(collectionId);
   });
   it('Fungible collection can be destroyed', async () => {
-    const collectionId = await createCollectionExpectSuccess({ mode: 'Fungible' });
+    const collectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
     await destroyCollectionExpectSuccess(collectionId);
   });
   it('ReFungible collection can be destroyed', async () => {
-    const collectionId = await createCollectionExpectSuccess({ mode: 'ReFungible' });
+    const collectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible', decimalPoints: 0}});
     await destroyCollectionExpectSuccess(collectionId);
   });
 });
modifiedtests/src/setCollectionLimits.test.tsdiffbeforeafterboth
--- a/tests/src/setCollectionLimits.test.ts
+++ b/tests/src/setCollectionLimits.test.ts
@@ -32,7 +32,7 @@
   });
   it('choose or create collection for testing', async () => {
     await usingApi(async () => {
-      collectionIdForTesting = await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: 'NFT'});
+      collectionIdForTesting = await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
     });
   });
 });
modifiedtests/src/setCollectionSponsor.test.tsdiffbeforeafterboth
--- a/tests/src/setCollectionSponsor.test.ts
+++ b/tests/src/setCollectionSponsor.test.ts
@@ -30,11 +30,11 @@
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
   });
   it('Set Fungible collection sponsor', async () => {
-    const collectionId = await createCollectionExpectSuccess({ mode: 'Fungible' });
+    const collectionId = await createCollectionExpectSuccess({ mode: {type: 'Fungible', decimalPoints: 0} });
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
   });
   it('Set ReFungible collection sponsor', async () => {
-    const collectionId = await createCollectionExpectSuccess({ mode: 'ReFungible' });
+    const collectionId = await createCollectionExpectSuccess({ mode: {type: 'ReFungible', decimalPoints: 0} });
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
   });
 
modifiedtests/src/setSchemaVersion.test.tsdiffbeforeafterboth
--- a/tests/src/setSchemaVersion.test.ts
+++ b/tests/src/setSchemaVersion.test.ts
@@ -35,7 +35,7 @@
   });
   it('choose or create collection for testing', async () => {
     await usingApi(async () => {
-      collectionIdForTesting = await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: 'NFT'});
+      collectionIdForTesting = await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
     });
   });
 });
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, submitTransactionExpectFailAsync } from "../substrate/substrate-api";11import privateKey from '../substrate/privateKey';12import { alicesPublicKey, nullPublicKey } from "../accounts";13import { strToUTF16, utf16ToStr, hexToStr } from './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';18import { ICollectionInterface } from '../types';19import BN from "bn.js";2021chai.use(chaiAsPromised);22const expect = chai.expect;2324type GenericResult = {25  success: boolean,26};2728type CreateCollectionResult = {29  success: boolean,30  collectionId: number31};3233type CreateItemResult = {34  success: boolean,35  collectionId: number,36  itemId: number37};3839export function getGenericResult(events: EventRecord[]): GenericResult {40  let result: GenericResult = {41    success: false42  }43  events.forEach(({ phase, event: { data, method, section } }) => {44    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);45    if (method == 'ExtrinsicSuccess') {46      result.success = true;47    }48  });49  return result;50}5152export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {53  let success = false;54  let collectionId: number = 0;55  events.forEach(({ phase, event: { data, method, section } }) => {56    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);57    if (method == 'ExtrinsicSuccess') {58      success = true;59    } else if ((section == 'nft') && (method == 'Created')) {60      collectionId = parseInt(data[0].toString());61    }62  });63  let result: CreateCollectionResult = {64    success,65    collectionId66  }67  return result;68}6970export function getCreateItemResult(events: EventRecord[]): CreateItemResult {71  let success = false;72  let collectionId: number = 0;73  let itemId: number = 0;74  events.forEach(({ phase, event: { data, method, section } }) => {75    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);76    if (method == 'ExtrinsicSuccess') {77      success = true;78    } else if ((section == 'nft') && (method == 'ItemCreated')) {79      collectionId = parseInt(data[0].toString());80      itemId = parseInt(data[1].toString());81    }82  });83  let result: CreateItemResult = {84    success,85    collectionId,86    itemId87  }88  return result;89}9091export type CollectionMode = 'NFT' | 'Fungible' | 'ReFungible';92export type CreateCollectionParams = {93  mode: CollectionMode,94  name: string,95  description: string,96  tokenPrefix: string97};9899const defaultCreateCollectionParams: CreateCollectionParams = {100  name: 'name',101  description: 'description',102  mode: 'NFT',103  tokenPrefix: 'prefix'104}105106export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {107  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};108109  let collectionId: number = 0;110  await usingApi(async (api) => {111    // Get number of collections before the transaction112    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());113114    // Run the CreateCollection transaction115    const alicePrivateKey = privateKey('//Alice');116    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), mode);117    const events = await submitTransactionAsync(alicePrivateKey, tx);118    const result = getCreateCollectionResult(events);119120    // Get number of collections after the transaction121    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());122123    // Get the collection 124    const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();125126    // What to expect127    expect(result.success).to.be.true;128    expect(result.collectionId).to.be.equal(BcollectionCount);129    expect(collection).to.be.not.null;130    expect(BcollectionCount).to.be.equal(AcollectionCount+1, 'Error: NFT collection NOT created.');131    expect(collection.Owner).to.be.equal(alicesPublicKey);132    expect(utf16ToStr(collection.Name)).to.be.equal(name);133    expect(utf16ToStr(collection.Description)).to.be.equal(description);134    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);135136    collectionId = result.collectionId;137  });138139  return collectionId;140}141  142export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {143  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};144145  await usingApi(async (api) => {146    // Get number of collections before the transaction147    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());148149    // Run the CreateCollection transaction150    const alicePrivateKey = privateKey('//Alice');151    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), mode);152    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;153    const result = getCreateCollectionResult(events);154155    // Get number of collections after the transaction156    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());157158    // What to expect159    expect(result.success).to.be.false;160    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');161  });162}163  164export async function findUnusedAddress(api: ApiPromise): Promise<IKeyringPair> {165  let bal = new BigNumber(0);166  let unused;167  do {168    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000));169    const keyring = new Keyring({ type: 'sr25519' });170    unused = keyring.addFromUri(`//${randomSeed}`);171    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());172  } while (bal.toFixed() != '0');173  return unused; 174}175176function getDestroyResult(events: EventRecord[]): boolean {177  let success: boolean = false;178  events.forEach(({ phase, event: { data, method, section } }) => {179    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);180    if (method == 'ExtrinsicSuccess') {181      success = true;182    }183  });184  return success;185}186187export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {188  await usingApi(async (api) => {189    // Run the DestroyCollection transaction190    const alicePrivateKey = privateKey(senderSeed);191    const tx = api.tx.nft.destroyCollection(collectionId);192    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;193  });194}195196export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {197  await usingApi(async (api) => {198    // Run the DestroyCollection transaction199    const alicePrivateKey = privateKey(senderSeed);200    const tx = api.tx.nft.destroyCollection(collectionId);201    const events = await submitTransactionAsync(alicePrivateKey, tx);202    const result = getDestroyResult(events);203204    // Get the collection 205    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();206207    // What to expect208    expect(result).to.be.true;209    expect(collection).to.be.not.null;210    expect(collection.Owner).to.be.equal(nullPublicKey);211  });212}213214export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {215  await usingApi(async (api) => {216217    // Run the transaction218    const alicePrivateKey = privateKey('//Alice');219    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);220    const events = await submitTransactionAsync(alicePrivateKey, tx);221    const result = getGenericResult(events);222223    // Get the collection 224    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();225226    // What to expect227    expect(result.success).to.be.true;228    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());229    expect(collection.SponsorConfirmed).to.be.false;230  });231}232233export async function removeCollectionSponsorExpectSuccess(collectionId: number) {234  await usingApi(async (api) => {235236    // Run the transaction237    const alicePrivateKey = privateKey('//Alice');238    const tx = api.tx.nft.removeCollectionSponsor(collectionId);239    const events = await submitTransactionAsync(alicePrivateKey, tx);240    const result = getGenericResult(events);241242    // Get the collection 243    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();244245    // What to expect246    expect(result.success).to.be.true;247    expect(collection.Sponsor).to.be.equal(nullPublicKey);248    expect(collection.SponsorConfirmed).to.be.false;249  });250}251252export async function removeCollectionSponsorExpectFailure(collectionId: number) {253  await usingApi(async (api) => {254255    // Run the transaction256    const alicePrivateKey = privateKey('//Alice');257    const tx = api.tx.nft.removeCollectionSponsor(collectionId);258    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;259  });260}261262export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {263  await usingApi(async (api) => {264265    // Run the transaction266    const alicePrivateKey = privateKey(senderSeed);267    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);268    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;269  });270}271272export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {273  await usingApi(async (api) => {274275    // Run the transaction276    const sender = privateKey(senderSeed);277    const tx = api.tx.nft.confirmSponsorship(collectionId);278    const events = await submitTransactionAsync(sender, tx);279    const result = getGenericResult(events);280281    // Get the collection 282    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();283284    // What to expect285    expect(result.success).to.be.true;286    expect(collection.Sponsor).to.be.equal(sender.address);287    expect(collection.SponsorConfirmed).to.be.true;288  });289}290291export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {292  await usingApi(async (api) => {293294    // Run the transaction295    const sender = privateKey(senderSeed);296    const tx = api.tx.nft.confirmSponsorship(collectionId);297    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;298  });299}300301export interface CreateFungibleData extends Struct {302  readonly value: u128;303};304305export interface CreateReFungibleData extends Struct {};306export interface CreateNftData extends Struct {};307308export interface CreateItemData extends Enum {309  NFT: CreateNftData,310  Fungible: CreateFungibleData,311  ReFungible: CreateReFungibleData312};313314export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {315  let newItemId: number = 0;316  await usingApi(async (api) => {317    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString());318    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();    319    const AItemBalance = new BigNumber(Aitem.Value);320321    if (owner === '') owner = sender.address;322323    let tx;324    if (createMode == 'Fungible') {325      let createData = {fungible: {value: 10}};326      tx = api.tx.nft.createItem(collectionId, owner, createData);327    }328    else {329      tx = api.tx.nft.createItem(collectionId, owner, createMode);330    }331    const events = await submitTransactionAsync(sender, tx);332    const result = getCreateItemResult(events);333334    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString());335    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();    336    const BItemBalance = new BigNumber(Bitem.Value);337338    // What to expect339    expect(result.success).to.be.true;340    if (createMode == 'Fungible') {341      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);342    }343    else {344      expect(BItemCount).to.be.equal(AItemCount+1);345    }346    expect(collectionId).to.be.equal(result.collectionId);347    expect(BItemCount).to.be.equal(result.itemId);348    newItemId = result.itemId;349  });350  return newItemId;351}352353export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {354  await usingApi(async (api) => {355356    // Run the transaction357    const tx = api.tx.nft.setPublicAccessMode(collectionId, 'WhiteList');358    const events = await submitTransactionAsync(sender, tx);359    const result = getGenericResult(events);360361    // Get the collection 362    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();363364    // What to expect365    expect(result.success).to.be.true;366    expect(collection.Access).to.be.equal('WhiteList');367  });368}369370export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {371  await usingApi(async (api) => {372373    // Run the transaction374    const tx = api.tx.nft.setMintPermission(collectionId, true);375    const events = await submitTransactionAsync(sender, tx);376    const result = getGenericResult(events);377378    // Get the collection 379    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();380381    // What to expect382    expect(result.success).to.be.true;383    expect(collection.MintMode).to.be.equal(true);384  });385}386387export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {388  await usingApi(async (api) => {389390    // Run the transaction391    const tx = api.tx.nft.addToWhiteList(collectionId, address);392    const events = await submitTransactionAsync(sender, tx);393    const result = getGenericResult(events);394395    // Get the collection 396    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();397398    // What to expect399    expect(result.success).to.be.true;400    expect(collection.MintMode).to.be.equal(true);401  });402}403404export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)405  : Promise<ICollectionInterface | null> => {406  return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;407};408409export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {410  // set global object - collectionsCount411  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();412};
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';14import { IKeyringPair } from '@polkadot/types/types';15import { BigNumber } from 'bignumber.js';16import { Struct, Enum } from '@polkadot/types/codec';17import { u128 } from '@polkadot/types/primitive';18import { ICollectionInterface } from '../types';19import BN from "bn.js";2021chai.use(chaiAsPromised);22const expect = chai.expect;2324type GenericResult = {25  success: boolean,26};2728type CreateCollectionResult = {29  success: boolean,30  collectionId: number31};3233type CreateItemResult = {34  success: boolean,35  collectionId: number,36  itemId: number37};3839export function getGenericResult(events: EventRecord[]): GenericResult {40  let result: GenericResult = {41    success: false42  }43  events.forEach(({ phase, event: { data, method, section } }) => {44    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);45    if (method == 'ExtrinsicSuccess') {46      result.success = true;47    }48  });49  return result;50}5152export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {53  let success = false;54  let collectionId: number = 0;55  events.forEach(({ phase, event: { data, method, section } }) => {56    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);57    if (method == 'ExtrinsicSuccess') {58      success = true;59    } else if ((section == 'nft') && (method == 'Created')) {60      collectionId = parseInt(data[0].toString());61    }62  });63  let result: CreateCollectionResult = {64    success,65    collectionId66  }67  return result;68}6970export function getCreateItemResult(events: EventRecord[]): CreateItemResult {71  let success = false;72  let collectionId: number = 0;73  let itemId: number = 0;74  events.forEach(({ phase, event: { data, method, section } }) => {75    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);76    if (method == 'ExtrinsicSuccess') {77      success = true;78    } else if ((section == 'nft') && (method == 'ItemCreated')) {79      collectionId = parseInt(data[0].toString());80      itemId = parseInt(data[1].toString());81    }82  });83  let result: CreateItemResult = {84    success,85    collectionId,86    itemId87  }88  return result;89}9091interface Invalid {92  type: 'Invalid'93}9495interface Nft {96  type: 'NFT'97}9899interface Fungible {100  type: 'Fungible',101  decimalPoints: number102}103104interface ReFungible {105  type: 'ReFungible',106  decimalPoints: number107}108109type CollectionMode = Nft | Fungible | ReFungible | Invalid;110111export type CreateCollectionParams = {112  mode: CollectionMode,113  name: string,114  description: string,115  tokenPrefix: string116};117118const defaultCreateCollectionParams: CreateCollectionParams = {119  name: 'name',120  description: 'description',121  mode: { type: "NFT" },122  tokenPrefix: 'prefix'123}124125export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {126  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};127128  let collectionId: number = 0;129  await usingApi(async (api) => {130    // Get number of collections before the transaction131    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());132133    // Run the CreateCollection transaction134    const alicePrivateKey = privateKey('//Alice');135136    let modeprm = {};137    if (mode.type == 'NFT') {138      modeprm = {nft: null};139    }140    else if (mode.type == 'Fungible') {141      modeprm = {fungible: mode.decimalPoints};142    }143    else if (mode.type == 'ReFungible') {144      modeprm = {refungible: mode.decimalPoints};145    }146    else if (mode.type == 'Invalid') {147      modeprm = {invalid: null};148    }149150    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);151    const events = await submitTransactionAsync(alicePrivateKey, tx);152    const result = getCreateCollectionResult(events);153154    // Get number of collections after the transaction155    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());156157    // Get the collection 158    const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();159160    // What to expect161    expect(result.success).to.be.true;162    expect(result.collectionId).to.be.equal(BcollectionCount);163    expect(collection).to.be.not.null;164    expect(BcollectionCount).to.be.equal(AcollectionCount+1, 'Error: NFT collection NOT created.');165    expect(collection.Owner).to.be.equal(alicesPublicKey);166    expect(utf16ToStr(collection.Name)).to.be.equal(name);167    expect(utf16ToStr(collection.Description)).to.be.equal(description);168    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);169170    collectionId = result.collectionId;171  });172173  return collectionId;174}175  176export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {177  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};178179  await usingApi(async (api) => {180    // Get number of collections before the transaction181    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());182183    // Run the CreateCollection transaction184    const alicePrivateKey = privateKey('//Alice');185    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), mode);186    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;187    const result = getCreateCollectionResult(events);188189    // Get number of collections after the transaction190    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());191192    // What to expect193    expect(result.success).to.be.false;194    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');195  });196}197  198export async function findUnusedAddress(api: ApiPromise): Promise<IKeyringPair> {199  let bal = new BigNumber(0);200  let unused;201  do {202    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000));203    const keyring = new Keyring({ type: 'sr25519' });204    unused = keyring.addFromUri(`//${randomSeed}`);205    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());206  } while (bal.toFixed() != '0');207  return unused; 208}209210function getDestroyResult(events: EventRecord[]): boolean {211  let success: boolean = false;212  events.forEach(({ phase, event: { data, method, section } }) => {213    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);214    if (method == 'ExtrinsicSuccess') {215      success = true;216    }217  });218  return success;219}220221export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {222  await usingApi(async (api) => {223    // Run the DestroyCollection transaction224    const alicePrivateKey = privateKey(senderSeed);225    const tx = api.tx.nft.destroyCollection(collectionId);226    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;227  });228}229230export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {231  await usingApi(async (api) => {232    // Run the DestroyCollection transaction233    const alicePrivateKey = privateKey(senderSeed);234    const tx = api.tx.nft.destroyCollection(collectionId);235    const events = await submitTransactionAsync(alicePrivateKey, tx);236    const result = getDestroyResult(events);237238    // Get the collection 239    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();240241    // What to expect242    expect(result).to.be.true;243    expect(collection).to.be.not.null;244    expect(collection.Owner).to.be.equal(nullPublicKey);245  });246}247248export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {249  await usingApi(async (api) => {250251    // Run the transaction252    const alicePrivateKey = privateKey('//Alice');253    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);254    const events = await submitTransactionAsync(alicePrivateKey, tx);255    const result = getGenericResult(events);256257    // Get the collection 258    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();259260    // What to expect261    expect(result.success).to.be.true;262    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());263    expect(collection.SponsorConfirmed).to.be.false;264  });265}266267export async function removeCollectionSponsorExpectSuccess(collectionId: number) {268  await usingApi(async (api) => {269270    // Run the transaction271    const alicePrivateKey = privateKey('//Alice');272    const tx = api.tx.nft.removeCollectionSponsor(collectionId);273    const events = await submitTransactionAsync(alicePrivateKey, tx);274    const result = getGenericResult(events);275276    // Get the collection 277    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();278279    // What to expect280    expect(result.success).to.be.true;281    expect(collection.Sponsor).to.be.equal(nullPublicKey);282    expect(collection.SponsorConfirmed).to.be.false;283  });284}285286export async function removeCollectionSponsorExpectFailure(collectionId: number) {287  await usingApi(async (api) => {288289    // Run the transaction290    const alicePrivateKey = privateKey('//Alice');291    const tx = api.tx.nft.removeCollectionSponsor(collectionId);292    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;293  });294}295296export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {297  await usingApi(async (api) => {298299    // Run the transaction300    const alicePrivateKey = privateKey(senderSeed);301    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);302    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;303  });304}305306export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {307  await usingApi(async (api) => {308309    // Run the transaction310    const sender = privateKey(senderSeed);311    const tx = api.tx.nft.confirmSponsorship(collectionId);312    const events = await submitTransactionAsync(sender, tx);313    const result = getGenericResult(events);314315    // Get the collection 316    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();317318    // What to expect319    expect(result.success).to.be.true;320    expect(collection.Sponsor).to.be.equal(sender.address);321    expect(collection.SponsorConfirmed).to.be.true;322  });323}324325export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {326  await usingApi(async (api) => {327328    // Run the transaction329    const sender = privateKey(senderSeed);330    const tx = api.tx.nft.confirmSponsorship(collectionId);331    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;332  });333}334335export interface CreateFungibleData extends Struct {336  readonly value: u128;337};338339export interface CreateReFungibleData extends Struct {};340export interface CreateNftData extends Struct {};341342export interface CreateItemData extends Enum {343  NFT: CreateNftData,344  Fungible: CreateFungibleData,345  ReFungible: CreateReFungibleData346};347348export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {349  let newItemId: number = 0;350  await usingApi(async (api) => {351    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString());352    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();    353    const AItemBalance = new BigNumber(Aitem.Value);354355    if (owner === '') owner = sender.address;356357    let tx;358    if (createMode == 'Fungible') {359      let createData = {fungible: {value: 10}};360      tx = api.tx.nft.createItem(collectionId, owner, createData);361    }362    else {363      tx = api.tx.nft.createItem(collectionId, owner, createMode);364    }365    const events = await submitTransactionAsync(sender, tx);366    const result = getCreateItemResult(events);367368    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString());369    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();    370    const BItemBalance = new BigNumber(Bitem.Value);371372    // What to expect373    expect(result.success).to.be.true;374    if (createMode == 'Fungible') {375      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);376    }377    else {378      expect(BItemCount).to.be.equal(AItemCount+1);379    }380    expect(collectionId).to.be.equal(result.collectionId);381    expect(BItemCount).to.be.equal(result.itemId);382    newItemId = result.itemId;383  });384  return newItemId;385}386387export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {388  await usingApi(async (api) => {389390    // Run the transaction391    const tx = api.tx.nft.setPublicAccessMode(collectionId, 'WhiteList');392    const events = await submitTransactionAsync(sender, tx);393    const result = getGenericResult(events);394395    // Get the collection 396    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();397398    // What to expect399    expect(result.success).to.be.true;400    expect(collection.Access).to.be.equal('WhiteList');401  });402}403404export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {405  await usingApi(async (api) => {406407    // Run the transaction408    const tx = api.tx.nft.setMintPermission(collectionId, true);409    const events = await submitTransactionAsync(sender, tx);410    const result = getGenericResult(events);411412    // Get the collection 413    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();414415    // What to expect416    expect(result.success).to.be.true;417    expect(collection.MintMode).to.be.equal(true);418  });419}420421export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {422  await usingApi(async (api) => {423424    // Run the transaction425    const tx = api.tx.nft.addToWhiteList(collectionId, address);426    const events = await submitTransactionAsync(sender, tx);427    const result = getGenericResult(events);428429    // Get the collection 430    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();431432    // What to expect433    expect(result.success).to.be.true;434    expect(collection.MintMode).to.be.equal(true);435  });436}437438export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)439  : Promise<ICollectionInterface | null> => {440  return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;441};442443export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {444  // set global object - collectionsCount445  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();446};